diff --git a/Bukkit/build.gradle b/Bukkit/build.gradle index 4d6bb295c..af38aea0f 100644 --- a/Bukkit/build.gradle +++ b/Bukkit/build.gradle @@ -1,27 +1,29 @@ repositories { - maven {url "https://hub.spigotmc.org/nexus/content/groups/public/"} - maven { url = "https://oss.sonatype.org/content/repositories/snapshots/"} - maven {url "http://nexus.hc.to/content/repositories/pub_releases"} + maven { url "https://hub.spigotmc.org/nexus/content/repositories/snapshots/" } + maven { url = "https://oss.sonatype.org/content/repositories/snapshots/" } + maven { url "http://nexus.hc.to/content/repositories/pub_releases" } mavenLocal() } dependencies { compile project(':Core') - compile 'org.spigotmc:spigot-api:1.12.1-R0.1-SNAPSHOT' + compile 'org.spigotmc:spigot-api:1.13-R0.1-SNAPSHOT' + compile(group: 'com.sk89q.worldedit', name: 'worldedit-bukkit', version: '7.0.0-SNAPSHOT') compile("net.milkbowl.vault:VaultAPI:1.6") { exclude module: 'bukkit' } + compileOnly 'org.projectlombok:lombok:1.16.18' } -sourceCompatibility = 1.7 -targetCompatibility = 1.7 +sourceCompatibility = 1.8 +targetCompatibility = 1.8 processResources { from('src/main/resources') { include 'plugin.yml' expand( - name: project.parent.name, - version: project.parent.version + name: project.parent.name, + version: project.parent.version ) } } @@ -39,7 +41,7 @@ shadowJar { shadowJar.doLast { task -> - ant.checksum file: task.archivePath + ant.checksum file: task.archivePath } build.dependsOn(shadowJar); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/BukkitMain.java similarity index 60% rename from Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/BukkitMain.java index 059d65d46..f7b9239a2 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/BukkitMain.java @@ -1,100 +1,38 @@ -package com.plotsquared.bukkit; +package com.github.intellectualsites.plotsquared.bukkit; -import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; - -import com.intellectualcrafters.configuration.ConfigurationSection; -import com.intellectualcrafters.plot.IPlotMain; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.ConfigurationNode; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.generator.GeneratorWrapper; -import com.intellectualcrafters.plot.generator.HybridGen; -import com.intellectualcrafters.plot.generator.HybridUtils; -import com.intellectualcrafters.plot.generator.IndependentPlotGenerator; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.SetupObject; -import com.intellectualcrafters.plot.object.chat.PlainChatManager; -import com.intellectualcrafters.plot.object.worlds.PlotAreaManager; -import com.intellectualcrafters.plot.object.worlds.SinglePlotArea; -import com.intellectualcrafters.plot.object.worlds.SinglePlotAreaManager; -import com.intellectualcrafters.plot.object.worlds.SingleWorldGenerator; -import com.intellectualcrafters.plot.util.AbstractTitle; -import com.intellectualcrafters.plot.util.ChatManager; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.ConsoleColors; -import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.InventoryUtil; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.ReflectionUtils; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.SetupUtils; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.UUIDHandlerImplementation; -import com.intellectualcrafters.plot.util.WorldUtil; -import com.intellectualcrafters.plot.util.block.QueueProvider; -import com.intellectualcrafters.plot.uuid.UUIDWrapper; -import com.plotsquared.bukkit.database.plotme.ClassicPlotMeConnector; -import com.plotsquared.bukkit.database.plotme.LikePlotMeConverter; -import com.plotsquared.bukkit.database.plotme.PlotMeConnector_017; -import com.plotsquared.bukkit.generator.BukkitPlotGenerator; -import com.plotsquared.bukkit.listeners.ChunkListener; -import com.plotsquared.bukkit.listeners.EntityPortal_1_7_9; -import com.plotsquared.bukkit.listeners.EntitySpawnListener; -import com.plotsquared.bukkit.listeners.PlayerEvents; -import com.plotsquared.bukkit.listeners.PlayerEvents183; -import com.plotsquared.bukkit.listeners.PlayerEvents_1_8; -import com.plotsquared.bukkit.listeners.PlayerEvents_1_9; -import com.plotsquared.bukkit.listeners.PlotPlusListener; -import com.plotsquared.bukkit.listeners.PlotPlusListener_1_12; -import com.plotsquared.bukkit.listeners.PlotPlusListener_Legacy; -import com.plotsquared.bukkit.listeners.SingleWorldListener; -import com.plotsquared.bukkit.listeners.WorldEvents; -import com.plotsquared.bukkit.titles.DefaultTitle_111; -import com.plotsquared.bukkit.util.BukkitChatManager; -import com.plotsquared.bukkit.util.BukkitChunkManager; -import com.plotsquared.bukkit.util.BukkitCommand; -import com.plotsquared.bukkit.util.BukkitEconHandler; -import com.plotsquared.bukkit.util.BukkitEventUtil; -import com.plotsquared.bukkit.util.BukkitHybridUtils; -import com.plotsquared.bukkit.util.BukkitInventoryUtil; -import com.plotsquared.bukkit.util.BukkitSchematicHandler; -import com.plotsquared.bukkit.util.BukkitSetupUtils; -import com.plotsquared.bukkit.util.BukkitTaskManager; -import com.plotsquared.bukkit.util.BukkitUtil; -import com.plotsquared.bukkit.util.BukkitVersion; -import com.plotsquared.bukkit.util.Metrics; -import com.plotsquared.bukkit.util.SendChunk; -import com.plotsquared.bukkit.util.SetGenCB; -import com.plotsquared.bukkit.util.block.BukkitLocalQueue; -import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_7; -import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_8; -import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_8_3; -import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_9; -import com.plotsquared.bukkit.uuid.DefaultUUIDWrapper; -import com.plotsquared.bukkit.uuid.FileUUIDHandler; -import com.plotsquared.bukkit.uuid.LowerOfflineUUIDWrapper; -import com.plotsquared.bukkit.uuid.OfflineUUIDWrapper; -import com.plotsquared.bukkit.uuid.SQLUUIDHandler; +import com.github.intellectualsites.plotsquared.bukkit.database.plotme.ClassicPlotMeConnector; +import com.github.intellectualsites.plotsquared.bukkit.database.plotme.LikePlotMeConverter; +import com.github.intellectualsites.plotsquared.bukkit.database.plotme.PlotMeConnector_017; +import com.github.intellectualsites.plotsquared.bukkit.generator.BukkitPlotGenerator; +import com.github.intellectualsites.plotsquared.bukkit.listeners.*; +import com.github.intellectualsites.plotsquared.bukkit.titles.DefaultTitle_111; +import com.github.intellectualsites.plotsquared.bukkit.util.*; +import com.github.intellectualsites.plotsquared.bukkit.util.block.BukkitLocalQueue; +import com.github.intellectualsites.plotsquared.bukkit.uuid.*; +import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection; +import com.github.intellectualsites.plotsquared.plot.IPlotMain; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.ConfigurationNode; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; +import com.github.intellectualsites.plotsquared.plot.generator.HybridGen; +import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; +import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.chat.PlainChatManager; +import com.github.intellectualsites.plotsquared.plot.object.worlds.PlotAreaManager; +import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea; +import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotAreaManager; +import com.github.intellectualsites.plotsquared.plot.object.worlds.SingleWorldGenerator; +import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.block.QueueProvider; +import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper; import com.sk89q.worldedit.WorldEdit; -import java.io.File; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Chunk; +import lombok.Getter; +import lombok.NonNull; +import org.bukkit.*; import org.bukkit.Location; -import org.bukkit.OfflinePlayer; -import org.bukkit.World; import org.bukkit.command.PluginCommand; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; @@ -107,9 +45,19 @@ import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; +import javax.annotation.Nullable; +import java.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + +import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass; + public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain { - private static ConcurrentHashMap pluginMap; + @Getter private static WorldEdit worldEdit; + private static Map pluginMap; static { // Disable AWE as otherwise both fail to load @@ -128,14 +76,15 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain iter.remove(); } } - Map lookupNames = (Map) lookupNamesField.get(manager); + Map lookupNames = + (Map) lookupNamesField.get(manager); lookupNames.remove("PlotMe"); lookupNames.remove("PlotMe-DefaultGenerator"); pluginsField.set(manager, new ArrayList(plugins) { - @Override - public boolean add(Plugin plugin) { + @Override public boolean add(Plugin plugin) { if (plugin.getName().startsWith("PlotMe")) { - System.out.print("Disabling `" + plugin.getName() + "` for PlotMe conversion (configure in PlotSquared settings.yml)"); + System.out.print("Disabling `" + plugin.getName() + + "` for PlotMe conversion (configure in PlotSquared settings.yml)"); } else { return super.add(plugin); } @@ -143,8 +92,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } }); pluginMap = new ConcurrentHashMap(lookupNames) { - @Override - public Plugin put(String key, Plugin plugin) { + @Override public Plugin put(String key, Plugin plugin) { if (!plugin.getName().startsWith("PlotMe")) { return super.put(key, plugin); } @@ -153,17 +101,20 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain }; lookupNamesField.set(manager, pluginMap); } - } catch (Throwable ignore) {} + } catch (Throwable ignore) { + } } - public static WorldEdit worldEdit; - + private final LegacyMappings legacyMappings = new BukkitLegacyMappings(); + private final BlockRegistry blockRegistry = + new BukkitBlockRegistry(Material.values()); private int[] version; - private String name; - private SingleWorldListener singleWorldListener; + @Getter private String pluginName; + @Getter private SingleWorldListener singleWorldListener; + private Method methodUnloadChunk0; + private boolean methodUnloadSetup = false; - @Override - public int[] getServerVersion() { + @Override public int[] getServerVersion() { if (this.version == null) { try { this.version = new int[3]; @@ -175,32 +126,34 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } } catch (NumberFormatException e) { e.printStackTrace(); - PS.debug(StringMan.getString(Bukkit.getBukkitVersion())); - PS.debug(StringMan.getString(Bukkit.getBukkitVersion().split("-")[0].split("\\."))); - return new int[]{1, 13, 0}; + PlotSquared.debug(StringMan.getString(Bukkit.getBukkitVersion())); + PlotSquared.debug( + StringMan.getString(Bukkit.getBukkitVersion().split("-")[0].split("\\."))); + return new int[] {1, 13, 0}; } } return this.version; } - @Override - public void onEnable() { + @Override public void onEnable() { if (pluginMap != null) { pluginMap.put("PlotMe-DefaultGenerator", this); } - this.name = getDescription().getName(); + this.pluginName = getDescription().getName(); getServer().getName(); - new PS(this, "Bukkit"); + + PlotPlayer.registerConverter(Player.class, BukkitUtil::getPlayer); + + new PlotSquared(this, "Bukkit"); if (Settings.Enabled_Components.METRICS) { new Metrics(this).start(); - PS.log(C.PREFIX + "&6Metrics enabled."); + PlotSquared.log(C.PREFIX + "&6Metrics enabled."); } else { - PS.log(C.CONSOLE_PLEASE_ENABLE_METRICS.f(getPluginName())); + PlotSquared.log(C.CONSOLE_PLEASE_ENABLE_METRICS.f(getPluginName())); } if (Settings.Enabled_Components.WORLDS) { TaskManager.IMP.taskRepeat(new Runnable() { - @Override - public void run() { + @Override public void run() { unload(); } }, 20); @@ -212,72 +165,73 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } } - public SingleWorldListener getSingleWorldListener() { - return singleWorldListener; - } - - private Method methodUnloadChunk0; - private boolean methodUnloadSetup = false; - public void unload() { - if (!methodUnloadSetup) { - methodUnloadSetup = true; + if (!this.methodUnloadSetup) { + this.methodUnloadSetup = true; try { ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld"); - methodUnloadChunk0 = classCraftWorld.getRealClass().getDeclaredMethod("unloadChunk0", int.class, int.class, boolean.class); - methodUnloadChunk0.setAccessible(true); + this.methodUnloadChunk0 = classCraftWorld.getRealClass() + .getDeclaredMethod("unloadChunk0", int.class, int.class, boolean.class); + this.methodUnloadChunk0.setAccessible(true); } catch (Throwable ignore) { ignore.printStackTrace(); } } - PlotAreaManager manager = PS.get().getPlotAreaManager(); + final PlotAreaManager manager = PlotSquared.get().getPlotAreaManager(); if (manager instanceof SinglePlotAreaManager) { long start = System.currentTimeMillis(); - SinglePlotArea area = ((SinglePlotAreaManager) manager).getArea(); + final SinglePlotArea area = ((SinglePlotAreaManager) manager).getArea(); + outer: - for (World world : Bukkit.getWorlds()) { - String name = world.getName(); - char char0 = name.charAt(0); - if (!Character.isDigit(char0) && char0 != '-') continue; + for (final World world : Bukkit.getWorlds()) { + final String name = world.getName(); + final char char0 = name.charAt(0); + if (!Character.isDigit(char0) && char0 != '-') { + continue; + } + if (!world.getPlayers().isEmpty()) { continue; } - PlotId id = PlotId.fromString(name); + final PlotId id = PlotId.fromString(name); if (id != null) { - Plot plot = area.getOwnedPlot(id); + final Plot plot = area.getOwnedPlot(id); if (plot != null) { if (PlotPlayer.wrap(plot.owner) == null) { if (world.getKeepSpawnInMemory()) { world.setKeepSpawnInMemory(false); return; } - Chunk[] chunks = world.getLoadedChunks(); + final Chunk[] chunks = world.getLoadedChunks(); if (chunks.length == 0) { if (!Bukkit.unloadWorld(world, true)) { - PS.debug("Failed to unload " + world.getName()); + PlotSquared.debug("Failed to unload " + world.getName()); } return; } else { int index = 0; do { - Chunk chunkI = chunks[index++]; + final Chunk chunkI = chunks[index++]; boolean result; if (methodUnloadChunk0 != null) { try { - result = (boolean) methodUnloadChunk0.invoke(world, chunkI.getX(), chunkI.getZ(), true); + result = (boolean) methodUnloadChunk0 + .invoke(world, chunkI.getX(), chunkI.getZ(), true); } catch (Throwable e) { methodUnloadChunk0 = null; e.printStackTrace(); continue outer; } } else { - result = world.unloadChunk(chunkI.getX(), chunkI.getZ(), true, false); + result = world + .unloadChunk(chunkI.getX(), chunkI.getZ(), true, false); } if (!result) { continue outer; } - } while (index < chunks.length && System.currentTimeMillis() - start < 5); + } while (index < chunks.length + && System.currentTimeMillis() - start < 5); return; } } @@ -287,83 +241,68 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } } - @Override - public void onDisable() { - PS.get().disable(); + @Override public void onDisable() { + PlotSquared.get().disable(); Bukkit.getScheduler().cancelTasks(this); } - @Override - public void log(String message) { + @Override public void log(@NonNull String message) { try { message = C.color(message); if (!Settings.Chat.CONSOLE_COLOR) { message = ChatColor.stripColor(message); } this.getServer().getConsoleSender().sendMessage(message); - } catch (Throwable ignored) { + } catch (final Throwable ignored) { System.out.println(ConsoleColors.fromString(message)); } } - @Override - public void disable() { + @Override public void disable() { onDisable(); } - @Override - public int[] getPluginVersion() { + @Override public int[] getPluginVersion() { String ver = getDescription().getVersion(); if (ver.contains("-")) { ver = ver.split("-")[0]; } String[] split = ver.split("\\."); - return new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2])}; + return new int[] {Integer.parseInt(split[0]), Integer.parseInt(split[1]), + Integer.parseInt(split[2])}; } @Override public String getPluginVersionString() { return getDescription().getVersion(); } - @Override - public String getPluginName() { - return name; - } - - @Override - public void registerCommands() { - BukkitCommand bukkitCommand = new BukkitCommand(); - PluginCommand plotCommand = getCommand("plots"); + @Override public void registerCommands() { + final BukkitCommand bukkitCommand = new BukkitCommand(); + final PluginCommand plotCommand = getCommand("plots"); plotCommand.setExecutor(bukkitCommand); plotCommand.setAliases(Arrays.asList("p", "ps", "plotme", "plot")); plotCommand.setTabCompleter(bukkitCommand); } - @Override - public File getDirectory() { + @Override public File getDirectory() { return getDataFolder(); } - @Override - public File getWorldContainer() { + @Override public File getWorldContainer() { return Bukkit.getWorldContainer(); } - @Override - public TaskManager getTaskManager() { + @Override public TaskManager getTaskManager() { return new BukkitTaskManager(this); } - @Override - public void runEntityTask() { - PS.log(C.PREFIX + "KillAllEntities started."); + @Override @SuppressWarnings("deprecation") public void runEntityTask() { + PlotSquared.log(C.PREFIX + "KillAllEntities started."); TaskManager.runTaskRepeat(new Runnable() { - @Override - public void run() { - PS.get().foreachPlotArea(new RunnableVal() { - @Override - public void run(PlotArea plotArea) { - World world = Bukkit.getWorld(plotArea.worldname); + @Override public void run() { + PlotSquared.get().foreachPlotArea(new RunnableVal() { + @Override public void run(PlotArea plotArea) { + final World world = Bukkit.getWorld(plotArea.worldname); try { if (world == null) { return; @@ -416,10 +355,15 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain case MINECART_TNT: case BOAT: if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) { - com.intellectualcrafters.plot.object.Location location = BukkitUtil.getLocation(entity.getLocation()); + com.github.intellectualsites.plotsquared.plot.object.Location + location = + BukkitUtil.getLocation(entity.getLocation()); Plot plot = location.getPlot(); if (plot == null) { if (location.isPlotArea()) { + if (entity.hasMetadata("ps-tmp-teleport")) { + continue; + } iterator.remove(); entity.remove(); } @@ -431,6 +375,9 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } Plot origin = (Plot) meta.get(0).value(); if (!plot.equals(origin.getBasePlot(false))) { + if (entity.hasMetadata("ps-tmp-teleport")) { + continue; + } iterator.remove(); entity.remove(); } @@ -503,10 +450,17 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain Location location = entity.getLocation(); if (BukkitUtil.getLocation(location).isPlotRoad()) { if (entity instanceof LivingEntity) { - LivingEntity livingEntity = (LivingEntity) entity; - if (!livingEntity.isLeashed() || !entity.hasMetadata("keep")) { + LivingEntity livingEntity = + (LivingEntity) entity; + if (!livingEntity.isLeashed() || !entity + .hasMetadata("keep")) { Entity passenger = entity.getPassenger(); - if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) { + if (!(passenger instanceof Player) && entity + .getMetadata("keep").isEmpty()) { + if (entity + .hasMetadata("ps-tmp-teleport")) { + continue; + } iterator.remove(); entity.remove(); continue; @@ -514,7 +468,11 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } } else { Entity passenger = entity.getPassenger(); - if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) { + if (!(passenger instanceof Player) && entity + .getMetadata("keep").isEmpty()) { + if (entity.hasMetadata("ps-tmp-teleport")) { + continue; + } iterator.remove(); entity.remove(); continue; @@ -529,18 +487,32 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain LivingEntity livingEntity = (LivingEntity) entity; List meta = entity.getMetadata("plot"); if (meta != null && !meta.isEmpty()) { - if (livingEntity.isLeashed()) continue; + if (livingEntity.isLeashed()) + continue; - List keep = entity.getMetadata("keep"); - if (keep != null && !keep.isEmpty()) continue; + List keep = + entity.getMetadata("keep"); + if (keep != null && !keep.isEmpty()) + continue; - PlotId originalPlotId = (PlotId) meta.get(0).value(); + PlotId originalPlotId = + (PlotId) meta.get(0).value(); if (originalPlotId != null) { - com.intellectualcrafters.plot.object.Location pLoc = BukkitUtil.getLocation(entity.getLocation()); + com.github.intellectualsites.plotsquared.plot.object.Location + pLoc = BukkitUtil + .getLocation(entity.getLocation()); PlotArea area = pLoc.getPlotArea(); if (area != null) { - PlotId currentPlotId = PlotId.of(area.getPlotAbs(pLoc)); - if (!originalPlotId.equals(currentPlotId) && (currentPlotId == null || !area.getPlot(originalPlotId).equals(area.getPlot(currentPlotId)))) { + PlotId currentPlotId = + PlotId.of(area.getPlotAbs(pLoc)); + if (!originalPlotId.equals(currentPlotId) + && (currentPlotId == null || !area + .getPlot(originalPlotId) + .equals(area.getPlot(currentPlotId)))) { + if (entity + .hasMetadata("ps-tmp-teleport")) { + continue; + } iterator.remove(); entity.remove(); } @@ -548,17 +520,22 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } } else { //This is to apply the metadata to already spawned shulkers (see EntitySpawnListener.java) - com.intellectualcrafters.plot.object.Location pLoc = BukkitUtil.getLocation(entity.getLocation()); + com.github.intellectualsites.plotsquared.plot.object.Location + pLoc = + BukkitUtil.getLocation(entity.getLocation()); PlotArea area = pLoc.getPlotArea(); if (area != null) { - PlotId currentPlotId = PlotId.of(area.getPlotAbs(pLoc)); + PlotId currentPlotId = + PlotId.of(area.getPlotAbs(pLoc)); if (currentPlotId != null) { - entity.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, currentPlotId)); + entity.setMetadata("plot", + new FixedMetadataValue( + (Plugin) PlotSquared.get().IMP, + currentPlotId)); } } } } - continue; } } } @@ -571,87 +548,49 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain }, 20); } - @Override - public final ChunkGenerator getDefaultWorldGenerator(String world, String id) { + @Override @Nullable + public final ChunkGenerator getDefaultWorldGenerator(final String world, final String id) { if (Settings.Enabled_Components.PLOTME_CONVERTER) { initPlotMeConverter(); Settings.Enabled_Components.PLOTME_CONVERTER = false; } - IndependentPlotGenerator result; + final IndependentPlotGenerator result; if (id != null && id.equalsIgnoreCase("single")) { result = new SingleWorldGenerator(); } else { - result = PS.get().IMP.getDefaultGenerator(); - if (!PS.get().setupPlotWorld(world, id, result)) { + result = PlotSquared.get().IMP.getDefaultGenerator(); + if (!PlotSquared.get().setupPlotWorld(world, id, result)) { return null; } } return (ChunkGenerator) result.specify(world); } - @Override - public void registerPlayerEvents() { - PlayerEvents main = new PlayerEvents(); + @Override public void registerPlayerEvents() { + final PlayerEvents main = new PlayerEvents(); getServer().getPluginManager().registerEvents(main, this); try { getServer().getClass().getMethod("spigot"); Class.forName("org.bukkit.event.entity.EntitySpawnEvent"); getServer().getPluginManager().registerEvents(new EntitySpawnListener(), this); - } catch (NoSuchMethodException | ClassNotFoundException ignored) { - PS.debug("Not running Spigot. Skipping EntitySpawnListener event."); - } - if (PS.get().checkVersion(getServerVersion(), 1, 7, 9)) { - try { - getServer().getPluginManager().registerEvents(new EntityPortal_1_7_9(), this); - } catch (Throwable e) { - e.printStackTrace(); - } - } - if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_8_0)) { - try { - getServer().getPluginManager().registerEvents(new PlayerEvents_1_8(), this); - } catch (Throwable e) { - e.printStackTrace(); - } - } - if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_8_3)) { - try { - getServer().getPluginManager().registerEvents(new PlayerEvents183(), this); - } catch (Throwable e) { - e.printStackTrace(); - } - } - if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_9_0)) { - try { - getServer().getPluginManager().registerEvents(new PlayerEvents_1_9(main), this); - } catch (Throwable e) { - e.printStackTrace(); - } + } catch (final NoSuchMethodException | ClassNotFoundException ignored) { + PlotSquared.debug("Not running Spigot. Skipping EntitySpawnListener event."); } } - @Override - public void registerInventoryEvents() { + @Override public void registerInventoryEvents() { // Part of PlayerEvents - can be moved if necessary } - @Override - public void registerPlotPlusEvents() { + @Override public void registerPlotPlusEvents() { PlotPlusListener.startRunnable(this); getServer().getPluginManager().registerEvents(new PlotPlusListener(), this); - if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_12_0)) { - getServer().getPluginManager().registerEvents(new PlotPlusListener_1_12(), this); - } else { - getServer().getPluginManager().registerEvents(new PlotPlusListener_Legacy(), this); - } } - @Override - public void registerForceFieldEvents() { + @Override public void registerForceFieldEvents() { } - @Override - public boolean initWorldEdit() { + @Override public boolean initWorldEdit() { if (getServer().getPluginManager().getPlugin("WorldEdit") != null) { worldEdit = WorldEdit.getInstance(); return true; @@ -659,50 +598,35 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return false; } - @Override - public EconHandler getEconomyHandler() { + @Override public EconHandler getEconomyHandler() { try { BukkitEconHandler econ = new BukkitEconHandler(); if (econ.init()) { return econ; } } catch (Throwable ignored) { - PS.debug("No economy detected!"); + PlotSquared.debug("No economy detected!"); } return null; } - @Override - public QueueProvider initBlockQueue() { + @Override public QueueProvider initBlockQueue() { try { new SendChunk(); MainUtil.canSendChunk = true; } catch (ClassNotFoundException | NoSuchFieldException | NoSuchMethodException e) { - PS.debug(SendChunk.class + " does not support " + StringMan.getString(getServerVersion())); + PlotSquared.debug( + SendChunk.class + " does not support " + StringMan.getString(getServerVersion())); MainUtil.canSendChunk = false; } - if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_13_0)) { - return QueueProvider.of(BukkitLocalQueue.class, BukkitLocalQueue.class); - } - if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_9_0)) { - return QueueProvider.of(BukkitLocalQueue_1_9.class, BukkitLocalQueue.class); - } - if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_8_3)) { - return QueueProvider.of(BukkitLocalQueue_1_8_3.class, BukkitLocalQueue.class); - } - if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_8_0)) { - return QueueProvider.of(BukkitLocalQueue_1_8.class, BukkitLocalQueue.class); - } - return QueueProvider.of(BukkitLocalQueue_1_7.class, BukkitLocalQueue.class); + return QueueProvider.of(BukkitLocalQueue.class, BukkitLocalQueue.class); } - @Override - public WorldUtil initWorldUtil() { + @Override public WorldUtil initWorldUtil() { return new BukkitUtil(); } - @Override - public boolean initPlotMeConverter() { + @Override public boolean initPlotMeConverter() { if (new LikePlotMeConverter("PlotMe").run(new ClassicPlotMeConnector())) { return true; } else if (new LikePlotMeConverter("PlotMe").run(new PlotMeConnector_017())) { @@ -711,12 +635,12 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return false; } - @Override - public GeneratorWrapper getGenerator(String world, String name) { + @Override @Nullable public GeneratorWrapper getGenerator(@NonNull final String world, + @Nullable final String name) { if (name == null) { return null; } - Plugin genPlugin = Bukkit.getPluginManager().getPlugin(name); + final Plugin genPlugin = Bukkit.getPluginManager().getPlugin(name); if (genPlugin != null && genPlugin.isEnabled()) { ChunkGenerator gen = genPlugin.getDefaultWorldGenerator(world, ""); if (gen instanceof GeneratorWrapper) { @@ -724,28 +648,26 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } return new BukkitPlotGenerator(world, gen); } else { - return new BukkitPlotGenerator(PS.get().IMP.getDefaultGenerator()); + return new BukkitPlotGenerator(PlotSquared.get().IMP.getDefaultGenerator()); } } - @Override - public HybridUtils initHybridUtils() { + @Override public HybridUtils initHybridUtils() { return new BukkitHybridUtils(); } - @Override - public SetupUtils initSetupUtils() { + @Override public SetupUtils initSetupUtils() { return new BukkitSetupUtils(); } - @Override - public UUIDHandlerImplementation initUUIDHandler() { + @Override public UUIDHandlerImplementation initUUIDHandler() { boolean checkVersion = false; try { OfflinePlayer.class.getDeclaredMethod("getUniqueId"); checkVersion = true; - } catch (Throwable ignore) {} - UUIDWrapper wrapper; + } catch (Throwable ignore) { + } + final UUIDWrapper wrapper; if (Settings.UUID.OFFLINE) { if (Settings.UUID.FORCE_LOWERCASE) { wrapper = new LowerOfflineUUIDWrapper(); @@ -765,20 +687,22 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain Settings.UUID.OFFLINE = true; } if (!checkVersion) { - PS.log(C.PREFIX + " &c[WARN] Titles are disabled - please update your version of Bukkit to support this feature."); + PlotSquared.log(C.PREFIX + + " &c[WARN] Titles are disabled - please update your version of Bukkit to support this feature."); Settings.TITLES = false; } else { AbstractTitle.TITLE_CLASS = new DefaultTitle_111(); - if (wrapper instanceof DefaultUUIDWrapper || wrapper.getClass() == OfflineUUIDWrapper.class && !Bukkit.getOnlineMode()) { + if (wrapper instanceof DefaultUUIDWrapper + || wrapper.getClass() == OfflineUUIDWrapper.class && !Bukkit.getOnlineMode()) { Settings.UUID.NATIVE_UUID_PROVIDER = true; } } if (Settings.UUID.OFFLINE) { - PS.log(C.PREFIX - + " &6" + getPluginName() + " is using Offline Mode UUIDs either because of user preference, or because you are using an old version of " - + "Bukkit"); + PlotSquared.log(C.PREFIX + " &6" + getPluginName() + + " is using Offline Mode UUIDs either because of user preference, or because you are using an old version of " + + "Bukkit"); } else { - PS.log(C.PREFIX + " &6" + getPluginName() + " is using online UUIDs"); + PlotSquared.log(C.PREFIX + " &6" + getPluginName() + " is using online UUIDs"); } if (Settings.UUID.USE_SQLUUIDHANDLER) { return new SQLUUIDHandler(wrapper); @@ -787,53 +711,45 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } } - @Override - public ChunkManager initChunkManager() { + @Override public ChunkManager initChunkManager() { return new BukkitChunkManager(); } - @Override - public EventUtil initEventUtil() { + @Override public EventUtil initEventUtil() { return new BukkitEventUtil(); } - @Override - public void unregister(PlotPlayer player) { + @Override public void unregister(@NonNull final PlotPlayer player) { BukkitUtil.removePlayer(player.getName()); } - @Override - public void registerChunkProcessor() { + @Override public void registerChunkProcessor() { getServer().getPluginManager().registerEvents(new ChunkListener(), this); } - @Override - public void registerWorldEvents() { + @Override public void registerWorldEvents() { getServer().getPluginManager().registerEvents(new WorldEvents(), this); } - @Override - public IndependentPlotGenerator getDefaultGenerator() { + @Override public IndependentPlotGenerator getDefaultGenerator() { return new HybridGen(); } - @Override - public InventoryUtil initInventoryUtil() { + @Override public InventoryUtil initInventoryUtil() { return new BukkitInventoryUtil(); } - @Override - public void startMetrics() { + @Override public void startMetrics() { new Metrics(this).start(); - PS.log(C.PREFIX + "&6Metrics enabled."); + PlotSquared.log(C.PREFIX + "&6Metrics enabled."); } - @Override - public void setGenerator(String worldName) { + @Override public void setGenerator(@NonNull final String worldName) { World world = BukkitUtil.getWorld(worldName); if (world == null) { // create world - ConfigurationSection worldConfig = PS.get().worlds.getConfigurationSection("worlds." + worldName); + ConfigurationSection worldConfig = + PlotSquared.get().worlds.getConfigurationSection("worlds." + worldName); String manager = worldConfig.getString("generator.plugin", getPluginName()); SetupObject setup = new SetupObject(); setup.plotManager = manager; @@ -846,38 +762,35 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain world = Bukkit.getWorld(worldName); } else { try { - if (!PS.get().hasPlotArea(worldName)) { + if (!PlotSquared.get().hasPlotArea(worldName)) { SetGenCB.setGenerator(BukkitUtil.getWorld(worldName)); } } catch (Exception ignored) { - PS.log("Failed to reload world: " + world + " | " + ignored.getMessage()); + PlotSquared.log("Failed to reload world: " + world + " | " + ignored.getMessage()); Bukkit.getServer().unloadWorld(world, false); return; } } ChunkGenerator gen = world.getGenerator(); if (gen instanceof BukkitPlotGenerator) { - PS.get().loadWorld(worldName, (BukkitPlotGenerator) gen); + PlotSquared.get().loadWorld(worldName, (BukkitPlotGenerator) gen); } else if (gen != null) { - PS.get().loadWorld(worldName, new BukkitPlotGenerator(worldName, gen)); - } else if (PS.get().worlds.contains("worlds." + worldName)) { - PS.get().loadWorld(worldName, null); + PlotSquared.get().loadWorld(worldName, new BukkitPlotGenerator(worldName, gen)); + } else if (PlotSquared.get().worlds.contains("worlds." + worldName)) { + PlotSquared.get().loadWorld(worldName, null); } } - @Override - public SchematicHandler initSchematicHandler() { + @Override public SchematicHandler initSchematicHandler() { return new BukkitSchematicHandler(); } - @Override - public AbstractTitle initTitleManager() { + @Override public AbstractTitle initTitleManager() { // Already initialized in UUID handler return AbstractTitle.TITLE_CLASS; } - @Override - public PlotPlayer wrapPlayer(Object player) { + @Override @Nullable public PlotPlayer wrapPlayer(final Object player) { if (player instanceof Player) { return BukkitUtil.getPlayer((Player) player); } @@ -893,14 +806,12 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return null; } - @Override - public String getNMSPackage() { - String name = Bukkit.getServer().getClass().getPackage().getName(); + @Override public String getNMSPackage() { + final String name = Bukkit.getServer().getClass().getPackage().getName(); return name.substring(name.lastIndexOf('.') + 1); } - @Override - public ChatManager initChatManager() { + @Override public ChatManager initChatManager() { if (Settings.Chat.INTERACTIVE) { return new BukkitChatManager(); } else { @@ -908,17 +819,25 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } } - @Override - public GeneratorWrapper wrapPlotGenerator(String world, IndependentPlotGenerator generator) { + @Override public GeneratorWrapper wrapPlotGenerator(@Nullable final String world, + @NonNull final IndependentPlotGenerator generator) { return new BukkitPlotGenerator(generator); } - @Override - public List getPluginIds() { - ArrayList names = new ArrayList<>(); - for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { - names.add(plugin.getName() + ';' + plugin.getDescription().getVersion() + ':' + plugin.isEnabled()); + @Override public List getPluginIds() { + final List names = new ArrayList<>(); + for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { + names.add(plugin.getName() + ';' + plugin.getDescription().getVersion() + ':' + plugin + .isEnabled()); } return names; } -} \ No newline at end of file + + @Override public BlockRegistry getBlockRegistry() { + return this.blockRegistry; + } + + @Override public LegacyMappings getLegacyMappings() { + return this.legacyMappings; + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/ArrayWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/ArrayWrapper.java similarity index 87% rename from Bukkit/src/main/java/com/plotsquared/bukkit/chat/ArrayWrapper.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/ArrayWrapper.java index 2dd68fa4e..064d77d86 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/ArrayWrapper.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/ArrayWrapper.java @@ -1,4 +1,4 @@ -package com.plotsquared.bukkit.chat; +package com.github.intellectualsites.plotsquared.bukkit.chat; import org.apache.commons.lang.Validate; @@ -19,6 +19,8 @@ import java.util.Collection; */ public final class ArrayWrapper { + private E[] _array; + /** * Creates an array wrapper with some elements. * @@ -28,7 +30,38 @@ public final class ArrayWrapper { setArray(elements); } - private E[] _array; + /** + * Converts an iterable element collection to an array of elements. + * The iteration order of the specified object will be used as the array element order. + * + * @param list The iterable of objects which will be converted to an array. + * @param c The type of the elements of the array. + * @return An array of elements in the specified iterable. + */ + @SuppressWarnings("unchecked") public static T[] toArray(Iterable list, + Class c) { + int size = -1; + if (list instanceof Collection) { + @SuppressWarnings("rawtypes") Collection coll = (Collection) list; + size = coll.size(); + } + + + if (size < 0) { + size = 0; + // Ugly hack: Count it ourselves + for (@SuppressWarnings("unused") T element : list) { + size++; + } + } + + T[] result = (T[]) Array.newInstance(c, size); + int i = 0; + for (T element : list) { // Assumes iteration order is consistent + result[i++] = element; // Assign array element at index THEN increment counter + } + return result; + } /** * Retrieves a reference to the wrapped array instance. @@ -54,9 +87,7 @@ public final class ArrayWrapper { * * @see Arrays#equals(Object[], Object[]) */ - @SuppressWarnings("rawtypes") - @Override - public boolean equals(Object other) { + @SuppressWarnings("rawtypes") @Override public boolean equals(Object other) { if (!(other instanceof ArrayWrapper)) { return false; } @@ -69,43 +100,8 @@ public final class ArrayWrapper { * @return This object's hash code. * @see Arrays#hashCode(Object[]) */ - @Override - public int hashCode() { + @Override public int hashCode() { return Arrays.hashCode(_array); } - /** - * Converts an iterable element collection to an array of elements. - * The iteration order of the specified object will be used as the array element order. - * - * @param list The iterable of objects which will be converted to an array. - * @param c The type of the elements of the array. - * @return An array of elements in the specified iterable. - */ - @SuppressWarnings("unchecked") - public static T[] toArray(Iterable list, Class c) { - int size = -1; - if (list instanceof Collection) { - @SuppressWarnings("rawtypes") - Collection coll = (Collection) list; - size = coll.size(); - } - - - if (size < 0) { - size = 0; - // Ugly hack: Count it ourselves - for (@SuppressWarnings("unused") T element : list) { - size++; - } - } - - T[] result = (T[]) Array.newInstance(c, size); - int i = 0; - for (T element : list) { // Assumes iteration order is consistent - result[i++] = element; // Assign array element at index THEN increment counter - } - return result; - } - } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/FancyMessage.java similarity index 83% rename from Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/FancyMessage.java index 0f1b0d529..41ec91e49 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/FancyMessage.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/FancyMessage.java @@ -1,17 +1,11 @@ -package com.plotsquared.bukkit.chat; - -import static com.plotsquared.bukkit.chat.TextualComponent.rawText; +package com.github.intellectualsites.plotsquared.bukkit.chat; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.stream.JsonWriter; -import org.bukkit.Achievement; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.Statistic; +import org.bukkit.*; import org.bukkit.Statistic.Type; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.ConfigurationSerializable; @@ -22,17 +16,8 @@ import org.bukkit.inventory.ItemStack; import java.io.IOException; import java.io.StringWriter; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.lang.reflect.*; +import java.util.*; import java.util.logging.Level; /** @@ -45,7 +30,14 @@ import java.util.logging.Level; * optionally initializing it with text. Further property-setting method calls will affect that editing component. *

*/ -public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable, ConfigurationSerializable { +public class FancyMessage + implements JsonRepresentedObject, Cloneable, Iterable, ConfigurationSerializable { + + private static Constructor nmsPacketPlayOutChatConstructor; + // The ChatSerializer's instance of Gson + private static Object nmsChatSerializerGsonInstance; + private static Method fromJsonMethod; + private static JsonParser _stringParser = new JsonParser(); static { ConfigurationSerialization.registerClass(FancyMessage.class); @@ -55,27 +47,13 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< private String jsonString; private boolean dirty; - private static Constructor nmsPacketPlayOutChatConstructor; - - @Override - public FancyMessage clone() throws CloneNotSupportedException { - FancyMessage instance = (FancyMessage) super.clone(); - instance.messageParts = new ArrayList<>(messageParts.size()); - for (int i = 0; i < messageParts.size(); i++) { - instance.messageParts.add(i, messageParts.get(i).clone()); - } - instance.dirty = false; - instance.jsonString = null; - return instance; - } - /** * Creates a JSON message with text. * * @param firstPartText The existing text in the message. */ public FancyMessage(final String firstPartText) { - this(rawText(firstPartText)); + this(TextualComponent.rawText(firstPartText)); } private FancyMessage(final TextualComponent firstPartText) { @@ -85,10 +63,12 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< dirty = false; if (nmsPacketPlayOutChatConstructor == null) { try { - nmsPacketPlayOutChatConstructor = Reflection.getNMSClass("PacketPlayOutChat").getDeclaredConstructor(Reflection.getNMSClass("IChatBaseComponent")); + nmsPacketPlayOutChatConstructor = Reflection.getNMSClass("PacketPlayOutChat") + .getDeclaredConstructor(Reflection.getNMSClass("IChatBaseComponent")); nmsPacketPlayOutChatConstructor.setAccessible(true); } catch (NoSuchMethodException e) { - Bukkit.getLogger().log(Level.SEVERE, "Could not find Minecraft method or constructor.", e); + Bukkit.getLogger() + .log(Level.SEVERE, "Could not find Minecraft method or constructor.", e); } catch (SecurityException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access constructor.", e); } @@ -102,6 +82,113 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< this((TextualComponent) null); } + /** + * Deserializes a JSON-represented message from a mapping of key-value pairs. + * This is called by the Bukkit serialization API. + * It is not intended for direct public API consumption. + * + * @param serialized The key-value mapping which represents a fancy message. + */ + @SuppressWarnings("unchecked") public static FancyMessage deserialize( + Map serialized) { + FancyMessage msg = new FancyMessage(); + msg.messageParts = (List) serialized.get("messageParts"); + msg.jsonString = serialized.containsKey("JSON") ? serialized.get("JSON").toString() : null; + msg.dirty = !serialized.containsKey("JSON"); + return msg; + } + + /** + * Deserializes a fancy message from its JSON representation. This JSON representation is of the format of + * that returned by {@link #toJSONString()}, and is compatible with vanilla inputs. + * + * @param json The JSON string which represents a fancy message. + * @return A {@code FancyMessage} representing the parameterized JSON message. + */ + public static FancyMessage deserialize(String json) { + JsonObject serialized = _stringParser.parse(json).getAsJsonObject(); + JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component + FancyMessage returnVal = new FancyMessage(); + returnVal.messageParts.clear(); + for (JsonElement mPrt : extra) { + MessagePart component = new MessagePart(); + JsonObject messagePart = mPrt.getAsJsonObject(); + for (Map.Entry entry : messagePart.entrySet()) { + // Deserialize text + if (TextualComponent.isTextKey(entry.getKey())) { + // The map mimics the YAML serialization, which has a "key" field and one or more "value" fields + Map serializedMapForm = + new HashMap<>(); // Must be object due to Bukkit serializer API compliance + serializedMapForm.put("key", entry.getKey()); + if (entry.getValue().isJsonPrimitive()) { + // Assume string + serializedMapForm.put("value", entry.getValue().getAsString()); + } else { + // Composite object, but we assume each element is a string + for (Map.Entry compositeNestedElement : entry + .getValue().getAsJsonObject().entrySet()) { + serializedMapForm.put("value." + compositeNestedElement.getKey(), + compositeNestedElement.getValue().getAsString()); + } + } + component.text = TextualComponent.deserialize(serializedMapForm); + } else if (MessagePart.stylesToNames.inverse().containsKey(entry.getKey())) { + if (entry.getValue().getAsBoolean()) { + component.styles + .add(MessagePart.stylesToNames.inverse().get(entry.getKey())); + } + } else if (entry.getKey().equals("color")) { + component.color = + ChatColor.valueOf(entry.getValue().getAsString().toUpperCase()); + } else if (entry.getKey().equals("clickEvent")) { + JsonObject object = entry.getValue().getAsJsonObject(); + component.clickActionName = object.get("action").getAsString(); + component.clickActionData = object.get("value").getAsString(); + } else if (entry.getKey().equals("hoverEvent")) { + JsonObject object = entry.getValue().getAsJsonObject(); + component.hoverActionName = object.get("action").getAsString(); + if (object.get("value").isJsonPrimitive()) { + // Assume string + component.hoverActionData = + new JsonString(object.get("value").getAsString()); + } else { + // Assume composite type + // The only composite type we currently store is another FancyMessage + // Therefore, recursion time! + component.hoverActionData = deserialize(object.get("value") + .toString() /* This should properly serialize the JSON object as a JSON string */); + } + } else if (entry.getKey().equals("insertion")) { + component.insertionData = entry.getValue().getAsString(); + } else if (entry.getKey().equals("with")) { + for (JsonElement object : entry.getValue().getAsJsonArray()) { + if (object.isJsonPrimitive()) { + component.translationReplacements + .add(new JsonString(object.getAsString())); + } else { + // Only composite type stored in this array is - again - FancyMessages + // Recurse within this function to parse this as a translation replacement + component.translationReplacements.add(deserialize(object.toString())); + } + } + } + } + returnVal.messageParts.add(component); + } + return returnVal; + } + + @Override public FancyMessage clone() throws CloneNotSupportedException { + FancyMessage instance = (FancyMessage) super.clone(); + instance.messageParts = new ArrayList<>(messageParts.size()); + for (int i = 0; i < messageParts.size(); i++) { + instance.messageParts.add(i, messageParts.get(i).clone()); + } + instance.dirty = false; + instance.jsonString = null; + return instance; + } + /** * Sets the text of the current editing component to a value. * @@ -110,7 +197,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< */ public FancyMessage text(String text) { MessagePart latest = latest(); - latest.text = rawText(text); + latest.text = TextualComponent.rawText(text); dirty = true; return this; } @@ -242,8 +329,12 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< */ public FancyMessage achievementTooltip(final Achievement which) { try { - Object achievement = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSAchievement", Achievement.class).invoke(null, which); - return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Achievement"), "name").get(achievement)); + Object achievement = Reflection + .getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSAchievement", + Achievement.class).invoke(null, which); + return achievementTooltip( + (String) Reflection.getField(Reflection.getNMSClass("Achievement"), "name") + .get(achievement)); } catch (IllegalAccessException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); return this; @@ -251,7 +342,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); return this; } catch (InvocationTargetException e) { - Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); + Bukkit.getLogger() + .log(Level.WARNING, "A error has occurred during invoking of method.", e); return this; } } @@ -267,11 +359,16 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< public FancyMessage statisticTooltip(final Statistic which) { Type type = which.getType(); if (type != Type.UNTYPED) { - throw new IllegalArgumentException("That statistic requires an additional " + type + " parameter!"); + throw new IllegalArgumentException( + "That statistic requires an additional " + type + " parameter!"); } try { - Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSStatistic", Statistic.class).invoke(null, which); - return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic)); + Object statistic = Reflection + .getMethod(Reflection.getOBCClass("CraftStatistic"), "getNMSStatistic", + Statistic.class).invoke(null, which); + return achievementTooltip( + (String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name") + .get(statistic)); } catch (IllegalAccessException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); return this; @@ -279,7 +376,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); return this; } catch (InvocationTargetException e) { - Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); + Bukkit.getLogger() + .log(Level.WARNING, "A error has occurred during invoking of method.", e); return this; } } @@ -299,11 +397,16 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< throw new IllegalArgumentException("That statistic needs no additional parameter!"); } if ((type == Type.BLOCK && item.isBlock()) || type == Type.ENTITY) { - throw new IllegalArgumentException("Wrong parameter type for that statistic - needs " + type + "!"); + throw new IllegalArgumentException( + "Wrong parameter type for that statistic - needs " + type + "!"); } try { - Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getMaterialStatistic", Statistic.class, Material.class).invoke(null, which, item); - return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic)); + Object statistic = Reflection + .getMethod(Reflection.getOBCClass("CraftStatistic"), "getMaterialStatistic", + Statistic.class, Material.class).invoke(null, which, item); + return achievementTooltip( + (String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name") + .get(statistic)); } catch (IllegalAccessException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); return this; @@ -311,7 +414,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); return this; } catch (InvocationTargetException e) { - Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); + Bukkit.getLogger() + .log(Level.WARNING, "A error has occurred during invoking of method.", e); return this; } } @@ -331,11 +435,16 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< throw new IllegalArgumentException("That statistic needs no additional parameter!"); } if (type != Type.ENTITY) { - throw new IllegalArgumentException("Wrong parameter type for that statistic - needs " + type + "!"); + throw new IllegalArgumentException( + "Wrong parameter type for that statistic - needs " + type + "!"); } try { - Object statistic = Reflection.getMethod(Reflection.getOBCClass("CraftStatistic"), "getEntityStatistic", Statistic.class, EntityType.class).invoke(null, which, entity); - return achievementTooltip((String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name").get(statistic)); + Object statistic = Reflection + .getMethod(Reflection.getOBCClass("CraftStatistic"), "getEntityStatistic", + Statistic.class, EntityType.class).invoke(null, which, entity); + return achievementTooltip( + (String) Reflection.getField(Reflection.getNMSClass("Statistic"), "name") + .get(statistic)); } catch (IllegalAccessException e) { Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); return this; @@ -343,7 +452,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); return this; } catch (InvocationTargetException e) { - Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); + Bukkit.getLogger() + .log(Level.WARNING, "A error has occurred during invoking of method.", e); return this; } } @@ -356,7 +466,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< * @return This builder instance. */ public FancyMessage itemTooltip(final String itemJSON) { - onHover("show_item", new JsonString(itemJSON)); // Seems a bit hacky, considering we have a JSON object as a parameter + onHover("show_item", new JsonString( + itemJSON)); // Seems a bit hacky, considering we have a JSON object as a parameter return this; } @@ -369,8 +480,13 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< */ public FancyMessage itemTooltip(final ItemStack itemStack) { try { - Object nmsItem = Reflection.getMethod(Reflection.getOBCClass("inventory.CraftItemStack"), "asNMSCopy", ItemStack.class).invoke(null, itemStack); - return itemTooltip(Reflection.getMethod(Reflection.getNMSClass("ItemStack"), "save", Reflection.getNMSClass("NBTTagCompound")).invoke(nmsItem, Reflection.getNMSClass("NBTTagCompound").newInstance()).toString()); + Object nmsItem = Reflection + .getMethod(Reflection.getOBCClass("inventory.CraftItemStack"), "asNMSCopy", + ItemStack.class).invoke(null, itemStack); + return itemTooltip(Reflection.getMethod(Reflection.getNMSClass("ItemStack"), "save", + Reflection.getNMSClass("NBTTagCompound")) + .invoke(nmsItem, Reflection.getNMSClass("NBTTagCompound").newInstance()) + .toString()); } catch (Exception e) { e.printStackTrace(); return this; @@ -397,9 +513,25 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< * @return This builder instance. */ public FancyMessage tooltip(final Iterable lines) { - tooltip(com.plotsquared.bukkit.chat.ArrayWrapper.toArray(lines, String.class)); + tooltip(ArrayWrapper.toArray(lines, String.class)); return this; } + /* + + /** + * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message. + * @param replacements The replacements, in order, that will be used in the language-specific message. + * @return This builder instance. + */ /* ------------ + public FancyMessage translationReplacements(final Iterable replacements){ + for(CharSequence str : replacements){ + latest().translationReplacements.add(new JsonString(str)); + } + + return this; + } + + */ /** * Set the behavior of the current editing component to display raw text when the client hovers over the text. @@ -453,29 +585,34 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< } FancyMessage result = new FancyMessage(); - result.messageParts.clear(); // Remove the one existing text component that exists by default, which destabilizes the object + result.messageParts + .clear(); // Remove the one existing text component that exists by default, which destabilizes the object for (int i = 0; i < lines.length; i++) { try { for (MessagePart component : lines[i]) { if (component.clickActionData != null && component.clickActionName != null) { - throw new IllegalArgumentException("The tooltip text cannot have click data."); - } else if (component.hoverActionData != null && component.hoverActionName != null) { - throw new IllegalArgumentException("The tooltip text cannot have a tooltip."); + throw new IllegalArgumentException( + "The tooltip text cannot have click data."); + } else if (component.hoverActionData != null + && component.hoverActionName != null) { + throw new IllegalArgumentException( + "The tooltip text cannot have a tooltip."); } if (component.hasText()) { result.messageParts.add(component.clone()); } } if (i != lines.length - 1) { - result.messageParts.add(new MessagePart(rawText("\n"))); + result.messageParts.add(new MessagePart(TextualComponent.rawText("\n"))); } } catch (CloneNotSupportedException e) { Bukkit.getLogger().log(Level.WARNING, "Failed to clone object", e); return this; } } - return formattedTooltip(result.messageParts.isEmpty() ? null : result); // Throws NPE if size is 0, intended + return formattedTooltip( + result.messageParts.isEmpty() ? null : result); // Throws NPE if size is 0, intended } /** @@ -486,7 +623,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< * @return This builder instance. */ public FancyMessage formattedTooltip(final Iterable lines) { - return formattedTooltip(com.plotsquared.bukkit.chat.ArrayWrapper.toArray(lines, FancyMessage.class)); + return formattedTooltip(ArrayWrapper.toArray(lines, FancyMessage.class)); } /** @@ -503,22 +640,6 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< return this; } - /* - - /** - * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message. - * @param replacements The replacements, in order, that will be used in the language-specific message. - * @return This builder instance. - */ /* ------------ - public FancyMessage translationReplacements(final Iterable replacements){ - for(CharSequence str : replacements){ - latest().translationReplacements.add(new JsonString(str)); - } - - return this; - } - - */ /** * If the text is a translatable key, and it has replaceable values, this function can be used to set the replacements that will be used in the message. @@ -543,7 +664,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< * @return This builder instance. */ public FancyMessage translationReplacements(final Iterable replacements) { - return translationReplacements(com.plotsquared.bukkit.chat.ArrayWrapper.toArray(replacements, FancyMessage.class)); + return translationReplacements(ArrayWrapper.toArray(replacements, FancyMessage.class)); } /** @@ -554,7 +675,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< * @return This builder instance. */ public FancyMessage then(final String text) { - return then(rawText(text)); + return then(TextualComponent.rawText(text)); } /** @@ -588,8 +709,7 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< return this; } - @Override - public void writeJson(JsonWriter writer) throws IOException { + @Override public void writeJson(JsonWriter writer) throws IOException { if (messageParts.size() == 1) { latest().writeJson(writer); } else { @@ -641,8 +761,11 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< Player player = (Player) sender; try { Object handle = Reflection.getHandle(player); - Object connection = Reflection.getField(handle.getClass(), "playerConnection").get(handle); - Reflection.getMethod(connection.getClass(), "sendPacket", Reflection.getNMSClass("Packet")).invoke(connection, createChatPacket(jsonString)); + Object connection = + Reflection.getField(handle.getClass(), "playerConnection").get(handle); + Reflection + .getMethod(connection.getClass(), "sendPacket", Reflection.getNMSClass("Packet")) + .invoke(connection, createChatPacket(jsonString)); } catch (IllegalArgumentException e) { Bukkit.getLogger().log(Level.WARNING, "Argument could not be passed.", e); } catch (IllegalAccessException e) { @@ -650,7 +773,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< } catch (InstantiationException e) { Bukkit.getLogger().log(Level.WARNING, "Underlying class is abstract.", e); } catch (InvocationTargetException e) { - Bukkit.getLogger().log(Level.WARNING, "A error has occurred during invoking of method.", e); + Bukkit.getLogger() + .log(Level.WARNING, "A error has occurred during invoking of method.", e); } catch (NoSuchMethodException e) { Bukkit.getLogger().log(Level.WARNING, "Could not find method.", e); } catch (ClassNotFoundException e) { @@ -658,11 +782,9 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< } } - // The ChatSerializer's instance of Gson - private static Object nmsChatSerializerGsonInstance; - private static Method fromJsonMethod; - - private Object createChatPacket(String json) throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { + private Object createChatPacket(String json) + throws IllegalArgumentException, IllegalAccessException, InstantiationException, + InvocationTargetException, NoSuchMethodException, ClassNotFoundException { if (nmsChatSerializerGsonInstance == null) { // Find the field and its value, completely bypassing obfuscation Class chatSerializerClazz; @@ -673,7 +795,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< // Y = minor // Z = revision final String version = Reflection.getVersion(); - String[] split = version.substring(1, version.length() - 1).split("_"); // Remove trailing dot + String[] split = + version.substring(1, version.length() - 1).split("_"); // Remove trailing dot //int majorVersion = Integer.parseInt(split[0]); int minorVersion = Integer.parseInt(split[1]); int revisionVersion = Integer.parseInt(split[2].substring(1)); // Substring to ignore R @@ -689,11 +812,14 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< } for (Field declaredField : chatSerializerClazz.getDeclaredFields()) { - if (Modifier.isFinal(declaredField.getModifiers()) && Modifier.isStatic(declaredField.getModifiers()) && declaredField.getType().getName().endsWith("Gson")) { + if (Modifier.isFinal(declaredField.getModifiers()) && Modifier + .isStatic(declaredField.getModifiers()) && declaredField.getType().getName() + .endsWith("Gson")) { // We've found our field declaredField.setAccessible(true); nmsChatSerializerGsonInstance = declaredField.get(null); - fromJsonMethod = nmsChatSerializerGsonInstance.getClass().getMethod("fromJson", String.class, Class.class); + fromJsonMethod = nmsChatSerializerGsonInstance.getClass() + .getMethod("fromJson", String.class, Class.class); break; } } @@ -701,7 +827,8 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< // Since the method is so simple, and all the obfuscated methods have the same name, it's easier to reimplement 'IChatBaseComponent a(String)' than to reflectively call it // Of course, the implementation may change, but fuzzy matches might break with signature changes - Object serializedChatComponent = fromJsonMethod.invoke(nmsChatSerializerGsonInstance, json, Reflection.getNMSClass("IChatBaseComponent")); + Object serializedChatComponent = fromJsonMethod.invoke(nmsChatSerializerGsonInstance, json, + Reflection.getNMSClass("IChatBaseComponent")); return nmsPacketPlayOutChatConstructor.newInstance(serializedChatComponent); } @@ -782,26 +909,10 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< public Map serialize() { HashMap map = new HashMap<>(); map.put("messageParts", messageParts); -// map.put("JSON", toJSONString()); + // map.put("JSON", toJSONString()); return map; } - /** - * Deserializes a JSON-represented message from a mapping of key-value pairs. - * This is called by the Bukkit serialization API. - * It is not intended for direct public API consumption. - * - * @param serialized The key-value mapping which represents a fancy message. - */ - @SuppressWarnings("unchecked") - public static FancyMessage deserialize(Map serialized) { - FancyMessage msg = new FancyMessage(); - msg.messageParts = (List) serialized.get("messageParts"); - msg.jsonString = serialized.containsKey("JSON") ? serialized.get("JSON").toString() : null; - msg.dirty = !serialized.containsKey("JSON"); - return msg; - } - /** * Internally called method. Not for API consumption. */ @@ -809,78 +920,4 @@ public class FancyMessage implements JsonRepresentedObject, Cloneable, Iterable< return messageParts.iterator(); } - private static JsonParser _stringParser = new JsonParser(); - - /** - * Deserializes a fancy message from its JSON representation. This JSON representation is of the format of - * that returned by {@link #toJSONString()}, and is compatible with vanilla inputs. - * - * @param json The JSON string which represents a fancy message. - * @return A {@code FancyMessage} representing the parameterized JSON message. - */ - public static FancyMessage deserialize(String json) { - JsonObject serialized = _stringParser.parse(json).getAsJsonObject(); - JsonArray extra = serialized.getAsJsonArray("extra"); // Get the extra component - FancyMessage returnVal = new FancyMessage(); - returnVal.messageParts.clear(); - for (JsonElement mPrt : extra) { - MessagePart component = new MessagePart(); - JsonObject messagePart = mPrt.getAsJsonObject(); - for (Map.Entry entry : messagePart.entrySet()) { - // Deserialize text - if (TextualComponent.isTextKey(entry.getKey())) { - // The map mimics the YAML serialization, which has a "key" field and one or more "value" fields - Map serializedMapForm = new HashMap<>(); // Must be object due to Bukkit serializer API compliance - serializedMapForm.put("key", entry.getKey()); - if (entry.getValue().isJsonPrimitive()) { - // Assume string - serializedMapForm.put("value", entry.getValue().getAsString()); - } else { - // Composite object, but we assume each element is a string - for (Map.Entry compositeNestedElement : entry.getValue().getAsJsonObject().entrySet()) { - serializedMapForm.put("value." + compositeNestedElement.getKey(), compositeNestedElement.getValue().getAsString()); - } - } - component.text = TextualComponent.deserialize(serializedMapForm); - } else if (MessagePart.stylesToNames.inverse().containsKey(entry.getKey())) { - if (entry.getValue().getAsBoolean()) { - component.styles.add(MessagePart.stylesToNames.inverse().get(entry.getKey())); - } - } else if (entry.getKey().equals("color")) { - component.color = ChatColor.valueOf(entry.getValue().getAsString().toUpperCase()); - } else if (entry.getKey().equals("clickEvent")) { - JsonObject object = entry.getValue().getAsJsonObject(); - component.clickActionName = object.get("action").getAsString(); - component.clickActionData = object.get("value").getAsString(); - } else if (entry.getKey().equals("hoverEvent")) { - JsonObject object = entry.getValue().getAsJsonObject(); - component.hoverActionName = object.get("action").getAsString(); - if (object.get("value").isJsonPrimitive()) { - // Assume string - component.hoverActionData = new JsonString(object.get("value").getAsString()); - } else { - // Assume composite type - // The only composite type we currently store is another FancyMessage - // Therefore, recursion time! - component.hoverActionData = deserialize(object.get("value").toString() /* This should properly serialize the JSON object as a JSON string */); - } - } else if (entry.getKey().equals("insertion")) { - component.insertionData = entry.getValue().getAsString(); - } else if (entry.getKey().equals("with")) { - for (JsonElement object : entry.getValue().getAsJsonArray()) { - if (object.isJsonPrimitive()) { - component.translationReplacements.add(new JsonString(object.getAsString())); - } else { - // Only composite type stored in this array is - again - FancyMessages - // Recurse within this function to parse this as a translation replacement - component.translationReplacements.add(deserialize(object.toString())); - } - } - } - } - returnVal.messageParts.add(component); - } - return returnVal; - } - } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/JsonRepresentedObject.java similarity index 87% rename from Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/JsonRepresentedObject.java index 6092bce60..04f036526 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonRepresentedObject.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/JsonRepresentedObject.java @@ -1,4 +1,4 @@ -package com.plotsquared.bukkit.chat; +package com.github.intellectualsites.plotsquared.bukkit.chat; import com.google.gson.stream.JsonWriter; @@ -11,6 +11,7 @@ interface JsonRepresentedObject { /** * Writes the JSON representation of this object to the specified writer. + * * @param writer The JSON writer which will receive the object. * @throws IOException If an error occurs writing to the stream. */ diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonString.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/JsonString.java similarity index 86% rename from Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonString.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/JsonString.java index 1fb197e8b..7f8dd4d29 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/JsonString.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/JsonString.java @@ -1,4 +1,4 @@ -package com.plotsquared.bukkit.chat; +package com.github.intellectualsites.plotsquared.bukkit.chat; import com.google.gson.stream.JsonWriter; import org.bukkit.configuration.serialization.ConfigurationSerializable; @@ -20,8 +20,11 @@ final class JsonString implements JsonRepresentedObject, ConfigurationSerializab _value = value == null ? null : value.toString(); } - @Override - public void writeJson(JsonWriter writer) throws IOException { + public static JsonString deserialize(Map map) { + return new JsonString(map.get("stringValue").toString()); + } + + @Override public void writeJson(JsonWriter writer) throws IOException { writer.value(getValue()); } @@ -35,12 +38,7 @@ final class JsonString implements JsonRepresentedObject, ConfigurationSerializab return theSingleValue; } - public static JsonString deserialize(Map map) { - return new JsonString(map.get("stringValue").toString()); - } - - @Override - public String toString() { + @Override public String toString() { return _value; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/MessagePart.java similarity index 83% rename from Bukkit/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/MessagePart.java index a3ed7fa2b..6c2e838d6 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/MessagePart.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/MessagePart.java @@ -1,4 +1,4 @@ -package com.plotsquared.bukkit.chat; +package com.github.intellectualsites.plotsquared.bukkit.chat; import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableBiMap; @@ -19,43 +19,6 @@ import java.util.logging.Level; */ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializable, Cloneable { - ChatColor color = ChatColor.WHITE; - ArrayList styles = new ArrayList<>(); - String clickActionName = null; - String clickActionData = null; - String hoverActionName = null; - JsonRepresentedObject hoverActionData = null; - TextualComponent text = null; - String insertionData = null; - ArrayList translationReplacements = new ArrayList<>(); - - MessagePart(final TextualComponent text) { - this.text = text; - } - - MessagePart() { - this.text = null; - } - - boolean hasText() { - return text != null; - } - - @Override - @SuppressWarnings("unchecked") - public MessagePart clone() throws CloneNotSupportedException { - MessagePart obj = (MessagePart) super.clone(); - obj.styles = (ArrayList) styles.clone(); - if (hoverActionData instanceof JsonString) { - obj.hoverActionData = new JsonString(((JsonString) hoverActionData).getValue()); - } else if (hoverActionData instanceof FancyMessage) { - obj.hoverActionData = ((FancyMessage) hoverActionData).clone(); - } - obj.translationReplacements = (ArrayList) translationReplacements.clone(); - return obj; - - } - static final BiMap stylesToNames; static { @@ -83,6 +46,62 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa stylesToNames = builder.build(); } + static { + ConfigurationSerialization.registerClass(MessagePart.class); + } + + ChatColor color = ChatColor.WHITE; + ArrayList styles = new ArrayList<>(); + String clickActionName = null; + String clickActionData = null; + String hoverActionName = null; + JsonRepresentedObject hoverActionData = null; + TextualComponent text = null; + String insertionData = null; + ArrayList translationReplacements = new ArrayList<>(); + + MessagePart(final TextualComponent text) { + this.text = text; + } + + MessagePart() { + this.text = null; + } + + @SuppressWarnings("unchecked") + public static MessagePart deserialize(Map serialized) { + MessagePart part = new MessagePart((TextualComponent) serialized.get("text")); + part.styles = (ArrayList) serialized.get("styles"); + part.color = ChatColor.getByChar(serialized.get("color").toString()); + part.hoverActionName = (String) serialized.get("hoverActionName"); + part.hoverActionData = (JsonRepresentedObject) serialized.get("hoverActionData"); + part.clickActionName = (String) serialized.get("clickActionName"); + part.clickActionData = (String) serialized.get("clickActionData"); + part.insertionData = (String) serialized.get("insertion"); + part.translationReplacements = + (ArrayList) serialized.get("translationReplacements"); + return part; + } + + boolean hasText() { + return text != null; + } + + @Override @SuppressWarnings("unchecked") public MessagePart clone() + throws CloneNotSupportedException { + MessagePart obj = (MessagePart) super.clone(); + obj.styles = (ArrayList) styles.clone(); + if (hoverActionData instanceof JsonString) { + obj.hoverActionData = new JsonString(((JsonString) hoverActionData).getValue()); + } else if (hoverActionData instanceof FancyMessage) { + obj.hoverActionData = ((FancyMessage) hoverActionData).clone(); + } + obj.translationReplacements = + (ArrayList) translationReplacements.clone(); + return obj; + + } + public void writeJson(JsonWriter json) { try { json.beginObject(); @@ -92,24 +111,20 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa json.name(stylesToNames.get(style)).value(true); } if (clickActionName != null && clickActionData != null) { - json.name("clickEvent") - .beginObject() - .name("action").value(clickActionName) - .name("value").value(clickActionData) - .endObject(); + json.name("clickEvent").beginObject().name("action").value(clickActionName) + .name("value").value(clickActionData).endObject(); } if (hoverActionName != null && hoverActionData != null) { - json.name("hoverEvent") - .beginObject() - .name("action").value(hoverActionName) - .name("value"); + json.name("hoverEvent").beginObject().name("action").value(hoverActionName) + .name("value"); hoverActionData.writeJson(json); json.endObject(); } if (insertionData != null) { json.name("insertion").value(insertionData); } - if (translationReplacements.size() > 0 && text != null && TextualComponent.isTranslatableText(text)) { + if (translationReplacements.size() > 0 && text != null && TextualComponent + .isTranslatableText(text)) { json.name("with").beginArray(); for (JsonRepresentedObject obj : translationReplacements) { obj.writeJson(json); @@ -118,7 +133,8 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa } json.endObject(); } catch (IOException e) { - Bukkit.getLogger().log(Level.WARNING, "A problem occured during writing of JSON string", e); + Bukkit.getLogger() + .log(Level.WARNING, "A problem occured during writing of JSON string", e); } } @@ -136,22 +152,4 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa return map; } - @SuppressWarnings("unchecked") - public static MessagePart deserialize(Map serialized) { - MessagePart part = new MessagePart((TextualComponent) serialized.get("text")); - part.styles = (ArrayList) serialized.get("styles"); - part.color = ChatColor.getByChar(serialized.get("color").toString()); - part.hoverActionName = (String) serialized.get("hoverActionName"); - part.hoverActionData = (JsonRepresentedObject) serialized.get("hoverActionData"); - part.clickActionName = (String) serialized.get("clickActionName"); - part.clickActionData = (String) serialized.get("clickActionData"); - part.insertionData = (String) serialized.get("insertion"); - part.translationReplacements = (ArrayList) serialized.get("translationReplacements"); - return part; - } - - static { - ConfigurationSerialization.registerClass(MessagePart.class); - } - } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/Reflection.java similarity index 95% rename from Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/Reflection.java index de315c06e..79c445dcc 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/Reflection.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/Reflection.java @@ -1,4 +1,4 @@ -package com.plotsquared.bukkit.chat; +package com.github.intellectualsites.plotsquared.bukkit.chat; import org.bukkit.Bukkit; @@ -28,10 +28,12 @@ public final class Reflection { * Contains loaded methods in a cache. * The map maps [types to maps of [method names to maps of [parameter types to method instances]]]. */ - private static final Map, Map>, Method>>> _loadedMethods = new HashMap<>(); + private static final Map, Map>, Method>>> + _loadedMethods = new HashMap<>(); private static String _versionString; - private Reflection() { } + private Reflection() { + } /** * Gets the version string from the package name of the CraftBukkit server implementation. @@ -109,8 +111,9 @@ public final class Reflection { * @param obj The object for which to retrieve an NMS handle. * @return The NMS handle of the specified object, or {@code null} if it could not be retrieved using {@code getHandle()}. */ - public synchronized static Object getHandle(Object obj) throws InvocationTargetException, IllegalAccessException, IllegalArgumentException { - return getMethod(obj.getClass(), "getHandle").invoke(obj); + public synchronized static Object getHandle(Object obj) + throws InvocationTargetException, IllegalAccessException, IllegalArgumentException { + return getMethod(obj.getClass(), "getHandle").invoke(obj); } /** @@ -181,7 +184,8 @@ public final class Reflection { _loadedMethods.put(clazz, new HashMap>, Method>>()); } - Map>, Method>> loadedMethodNames = _loadedMethods.get(clazz); + Map>, Method>> loadedMethodNames = + _loadedMethods.get(clazz); if (!loadedMethodNames.containsKey(name)) { loadedMethodNames.put(name, new HashMap>, Method>()); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/TextualComponent.java similarity index 81% rename from Bukkit/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/TextualComponent.java index 44005ed39..14e3d2305 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/chat/TextualComponent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/TextualComponent.java @@ -1,4 +1,4 @@ -package com.plotsquared.bukkit.chat; +package com.github.intellectualsites.plotsquared.bukkit.chat; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; @@ -27,7 +27,8 @@ public abstract class TextualComponent implements Cloneable { if (map.containsKey("key") && map.size() == 2 && map.containsKey("value")) { // Arbitrary text component return ArbitraryTextTypeComponent.deserialize(map); - } else if (map.size() >= 2 && map.containsKey("key") && !map.containsKey("value") /* It contains keys that START WITH value */) { + } else if (map.size() >= 2 && map.containsKey("key") && !map + .containsKey("value") /* It contains keys that START WITH value */) { // Complex JSON object return ComplexTextTypeComponent.deserialize(map); } @@ -36,11 +37,13 @@ public abstract class TextualComponent implements Cloneable { } static boolean isTextKey(String key) { - return key.equals("translate") || key.equals("text") || key.equals("score") || key.equals("selector"); + return key.equals("translate") || key.equals("text") || key.equals("score") || key + .equals("selector"); } static boolean isTranslatableText(TextualComponent component) { - return component instanceof ComplexTextTypeComponent && component.getKey().equals("translate"); + return component instanceof ComplexTextTypeComponent && component.getKey() + .equals("translate"); } /** @@ -73,7 +76,8 @@ public abstract class TextualComponent implements Cloneable { } private static void throwUnsupportedSnapshot() { - throw new UnsupportedOperationException("This feature is only supported in snapshot releases."); + throw new UnsupportedOperationException( + "This feature is only supported in snapshot releases."); } /** @@ -98,11 +102,11 @@ public abstract class TextualComponent implements Cloneable { *

This method is currently guaranteed to throw an {@code UnsupportedOperationException} * as it is only supported on snapshot clients. * - * @param playerName The name of the player whos score will be shown. If - * this string represents the single-character sequence - * "*", the viewing player's score will be displayed. - * Standard minecraft selectors (@a, @p, etc) - * are not supported. + * @param playerName The name of the player whos score will be shown. If + * this string represents the single-character sequence + * "*", the viewing player's score will be displayed. + * Standard minecraft selectors (@a, @p, etc) + * are not supported. * @param scoreboardObjective The name of the objective for * which to display the score. * @return The text component representing the specified scoreboard score @@ -112,10 +116,9 @@ public abstract class TextualComponent implements Cloneable { throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE // OVERLOADS documentation accordingly - return new ComplexTextTypeComponent("score", ImmutableMap.builder() - .put("name", playerName) - .put("objective", scoreboardObjective) - .build()); + return new ComplexTextTypeComponent("score", + ImmutableMap.builder().put("name", playerName) + .put("objective", scoreboardObjective).build()); } /** @@ -126,7 +129,7 @@ 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. + * the place of this text component. * @return The text component representing the name of the entities captured by the selector. */ public static TextualComponent selector(String selector) { @@ -136,8 +139,7 @@ public abstract class TextualComponent implements Cloneable { return new ArbitraryTextTypeComponent("selector", selector); } - @Override - public String toString() { + @Override public String toString() { return getReadableString(); } @@ -155,8 +157,7 @@ public abstract class TextualComponent implements Cloneable { * Clones a textual component instance. * The returned object should not reference this textual component instance, but should maintain the same key and value. */ - @Override - public abstract TextualComponent clone() throws CloneNotSupportedException; + @Override public abstract TextualComponent clone() throws CloneNotSupportedException; /** * Writes the text data represented by this textual component to the specified JSON writer object. @@ -171,7 +172,8 @@ public abstract class TextualComponent implements Cloneable { * Internal class used to represent all types of text components. * Exception validating done is on keys and values. */ - private static final class ArbitraryTextTypeComponent extends TextualComponent implements ConfigurationSerializable { + private static final class ArbitraryTextTypeComponent extends TextualComponent + implements ConfigurationSerializable { private String key; private String value; @@ -182,16 +184,17 @@ public abstract class TextualComponent implements Cloneable { } public static ArbitraryTextTypeComponent deserialize(Map map) { - return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString()); + return new ArbitraryTextTypeComponent(map.get("key").toString(), + map.get("value").toString()); } - @Override - public String getKey() { + @Override public String getKey() { return key; } public void setKey(String key) { - Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified."); + Preconditions + .checkArgument(key != null && !key.isEmpty(), "The key must be specified."); this.key = key; } @@ -204,20 +207,16 @@ public abstract class TextualComponent implements Cloneable { this.value = value; } - @Override - public TextualComponent clone() throws CloneNotSupportedException { + @Override public TextualComponent clone() throws CloneNotSupportedException { // Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone return new ArbitraryTextTypeComponent(getKey(), getValue()); } - @Override - public void writeJson(JsonWriter writer) throws IOException { + @Override public void writeJson(JsonWriter writer) throws IOException { writer.name(getKey()).value(getValue()); } - @Override - @SuppressWarnings("serial") - public Map serialize() { + @Override @SuppressWarnings("serial") public Map serialize() { return new HashMap() { { put("key", getKey()); @@ -226,19 +225,20 @@ public abstract class TextualComponent implements Cloneable { }; } - @Override - public String getReadableString() { + @Override public String getReadableString() { return getValue(); } } + /** * Internal class used to represent a text component with a nested JSON * value. * *

Exception validating done is on keys and values. */ - private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable { + private static final class ComplexTextTypeComponent extends TextualComponent + implements ConfigurationSerializable { private String key; private Map value; @@ -255,19 +255,20 @@ public abstract class TextualComponent implements Cloneable { if (valEntry.getKey().equals("key")) { key = (String) valEntry.getValue(); } else if (valEntry.getKey().startsWith("value.")) { - value.put(valEntry.getKey().substring(6) /* Strips out the value prefix */, valEntry.getValue().toString()); + value.put(valEntry.getKey().substring(6) /* Strips out the value prefix */, + valEntry.getValue().toString()); } } return new ComplexTextTypeComponent(key, value); } - @Override - public String getKey() { + @Override public String getKey() { return key; } public void setKey(String key) { - Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified."); + Preconditions + .checkArgument(key != null && !key.isEmpty(), "The key must be specified."); this.key = key; } @@ -280,14 +281,12 @@ public abstract class TextualComponent implements Cloneable { this.value = value; } - @Override - public TextualComponent clone() { + @Override public TextualComponent clone() { // Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone return new ComplexTextTypeComponent(getKey(), getValue()); } - @Override - public void writeJson(JsonWriter writer) throws IOException { + @Override public void writeJson(JsonWriter writer) throws IOException { writer.name(getKey()); writer.beginObject(); for (Map.Entry jsonPair : value.entrySet()) { @@ -296,9 +295,7 @@ public abstract class TextualComponent implements Cloneable { writer.endObject(); } - @Override - @SuppressWarnings("serial") - public Map serialize() { + @Override @SuppressWarnings("serial") public Map serialize() { return new java.util.HashMap() { { put("key", getKey()); @@ -309,8 +306,7 @@ public abstract class TextualComponent implements Cloneable { }; } - @Override - public String getReadableString() { + @Override public String getReadableString() { return getKey(); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/commands/DebugUUID.java similarity index 68% rename from Bukkit/src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/commands/DebugUUID.java index b3934109a..e53c69b02 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/commands/DebugUUID.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/commands/DebugUUID.java @@ -1,54 +1,40 @@ -package com.plotsquared.bukkit.commands; +package com.github.intellectualsites.plotsquared.bukkit.commands; +import com.github.intellectualsites.plotsquared.bukkit.uuid.DatFileFilter; +import com.github.intellectualsites.plotsquared.bukkit.uuid.DefaultUUIDWrapper; +import com.github.intellectualsites.plotsquared.bukkit.uuid.LowerOfflineUUIDWrapper; +import com.github.intellectualsites.plotsquared.bukkit.uuid.OfflineUUIDWrapper; +import com.github.intellectualsites.plotsquared.commands.Argument; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.commands.CommandCategory; +import com.github.intellectualsites.plotsquared.plot.commands.RequiredType; +import com.github.intellectualsites.plotsquared.plot.commands.SubCommand; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.StringWrapper; +import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper; import com.google.common.collect.Sets; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.commands.CommandCategory; -import com.intellectualcrafters.plot.commands.RequiredType; -import com.intellectualcrafters.plot.commands.SubCommand; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.OfflinePlotPlayer; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.StringWrapper; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.WorldUtil; -import com.intellectualcrafters.plot.uuid.UUIDWrapper; -import com.plotsquared.bukkit.uuid.DatFileFilter; -import com.plotsquared.bukkit.uuid.DefaultUUIDWrapper; -import com.plotsquared.bukkit.uuid.LowerOfflineUUIDWrapper; -import com.plotsquared.bukkit.uuid.OfflineUUIDWrapper; -import com.plotsquared.general.commands.Argument; -import com.plotsquared.general.commands.CommandDeclaration; + import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; +import java.util.*; import java.util.Map.Entry; -import java.util.UUID; -@CommandDeclaration( - command = "uuidconvert", - permission = "plots.admin", - description = "Debug UUID conversion", - usage = "/plot uuidconvert ", - requiredType = RequiredType.CONSOLE, - category = CommandCategory.DEBUG) +@CommandDeclaration(command = "uuidconvert", permission = "plots.admin", description = "Debug UUID conversion", usage = "/plot uuidconvert ", requiredType = RequiredType.CONSOLE, category = CommandCategory.DEBUG) public class DebugUUID extends SubCommand { public DebugUUID() { super(Argument.String); } - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { final UUIDWrapper currentUUIDWrapper = UUIDHandler.getUUIDWrapper(); final UUIDWrapper newWrapper; @@ -67,7 +53,8 @@ public class DebugUUID extends SubCommand { Class clazz = Class.forName(args[0]); newWrapper = (UUIDWrapper) clazz.newInstance(); } catch (ClassNotFoundException | IllegalAccessException | InstantiationException ignored) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert "); + MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + "/plot uuidconvert "); return false; } } @@ -75,23 +62,29 @@ public class DebugUUID extends SubCommand { if (args.length != 2 || !"-o".equals(args[1])) { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert " + args[0] + " - o"); MainUtil.sendMessage(player, "&cBe aware of the following!"); - MainUtil.sendMessage(player, "&8 - &cUse the database command or another method to backup your plots beforehand"); - MainUtil.sendMessage(player, "&8 - &cIf the process is interrupted, all plots could be deleted"); + MainUtil.sendMessage(player, + "&8 - &cUse the database command or another method to backup your plots beforehand"); + MainUtil.sendMessage(player, + "&8 - &cIf the process is interrupted, all plots could be deleted"); MainUtil.sendMessage(player, "&8 - &cIf an error occurs, all plots could be deleted"); MainUtil.sendMessage(player, "&8 - &cPlot settings WILL be lost upon conversion"); - MainUtil.sendMessage(player, "&cTO REITERATE: BACK UP YOUR DATABASE BEFORE USING THIS!!!"); - MainUtil.sendMessage(player, "&7Retype the command with the override parameter when ready :)"); + MainUtil + .sendMessage(player, "&cTO REITERATE: BACK UP YOUR DATABASE BEFORE USING THIS!!!"); + MainUtil.sendMessage(player, + "&7Retype the command with the override parameter when ready :)"); return false; } - if (currentUUIDWrapper.getClass().getCanonicalName().equals(newWrapper.getClass().getCanonicalName())) { + if (currentUUIDWrapper.getClass().getCanonicalName() + .equals(newWrapper.getClass().getCanonicalName())) { MainUtil.sendMessage(player, "&cUUID mode already in use!"); return false; } MainUtil.sendMessage(player, "&6Beginning UUID mode conversion"); MainUtil.sendMessage(player, "&7 - Disconnecting players"); for (Entry entry : UUIDHandler.getPlayers().entrySet()) { - entry.getValue().kick("UUID conversion has been initiated. You may reconnect when finished."); + entry.getValue() + .kick("UUID conversion has been initiated. You may reconnect when finished."); } MainUtil.sendMessage(player, "&7 - Initializing map"); @@ -135,12 +128,14 @@ public class DebugUUID extends SubCommand { OfflinePlotPlayer op = wrapper.getOfflinePlayer(uuid); uuid = currentUUIDWrapper.getUUID(op); uuid2 = newWrapper.getUUID(op); - if (!uuid.equals(uuid2) && !uCMap.containsKey(uuid) && !uCReverse.containsKey(uuid2)) { + if (!uuid.equals(uuid2) && !uCMap.containsKey(uuid) && !uCReverse + .containsKey(uuid2)) { uCMap.put(uuid, uuid2); uCReverse.put(uuid2, uuid); } } catch (Throwable ignored) { - MainUtil.sendMessage(player, C.PREFIX + "&6Invalid playerdata: " + uuid.toString() + ".dat"); + MainUtil.sendMessage(player, + C.PREFIX + "&6Invalid playerdata: " + uuid.toString() + ".dat"); } } for (String name : names) { @@ -175,8 +170,7 @@ public class DebugUUID extends SubCommand { MainUtil.sendMessage(player, "&7 - Replacing cache"); TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { for (Entry entry : uCMap.entrySet()) { String name = UUIDHandler.getName(entry.getKey()); if (name != null) { @@ -186,10 +180,11 @@ public class DebugUUID extends SubCommand { MainUtil.sendMessage(player, "&7 - Scanning for applicable files (uuids.txt)"); - File file = new File(PS.get().IMP.getDirectory(), "uuids.txt"); + File file = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt"); if (file.exists()) { try { - List lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); + List lines = + Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); for (String line : lines) { try { line = line.trim(); @@ -199,7 +194,8 @@ public class DebugUUID extends SubCommand { line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); String[] split = line.split("\\|"); String name = split[0]; - if (name.isEmpty() || name.length() > 16 || !StringMan.isAlphanumericUnd(name)) { + if (name.isEmpty() || name.length() > 16 || !StringMan + .isAlphanumericUnd(name)) { continue; } UUID old = currentUUIDWrapper.getUUID(name); @@ -224,7 +220,7 @@ public class DebugUUID extends SubCommand { MainUtil.sendMessage(player, "&7 - Updating plot objects"); - for (Plot plot : PS.get().getPlots()) { + for (Plot plot : PlotSquared.get().getPlots()) { UUID value = uCMap.get(plot.owner); if (value != null) { plot.owner = value; @@ -243,18 +239,18 @@ public class DebugUUID extends SubCommand { DBFunc.createTables(); if (!result) { MainUtil.sendMessage(player, "&cConversion failed! Attempting recovery"); - for (Plot plot : PS.get().getPlots()) { + for (Plot plot : PlotSquared.get().getPlots()) { UUID value = uCReverse.get(plot.owner); if (value != null) { plot.owner = value; } } - DBFunc.createPlotsAndData(new ArrayList<>(PS.get().getPlots()), new Runnable() { - @Override - public void run() { - MainUtil.sendMessage(player, "&6Recovery was successful!"); - } - }); + DBFunc.createPlotsAndData(new ArrayList<>(PlotSquared.get().getPlots()), + new Runnable() { + @Override public void run() { + MainUtil.sendMessage(player, "&6Recovery was successful!"); + } + }); return; } } catch (Exception e) { @@ -263,27 +259,26 @@ public class DebugUUID extends SubCommand { } if (newWrapper instanceof OfflineUUIDWrapper) { - PS.get().worlds.set("UUID.force-lowercase", false); - PS.get().worlds.set("UUID.offline", true); + PlotSquared.get().worlds.set("UUID.force-lowercase", false); + PlotSquared.get().worlds.set("UUID.offline", true); } else if (newWrapper instanceof DefaultUUIDWrapper) { - PS.get().worlds.set("UUID.force-lowercase", false); - PS.get().worlds.set("UUID.offline", false); + PlotSquared.get().worlds.set("UUID.force-lowercase", false); + PlotSquared.get().worlds.set("UUID.offline", false); } try { - PS.get().worlds.save(PS.get().worldsFile); + PlotSquared.get().worlds.save(PlotSquared.get().worldsFile); } catch (IOException ignored) { - MainUtil.sendMessage(player, "Could not save configuration. It will need to be manual set!"); + MainUtil.sendMessage(player, + "Could not save configuration. It will need to be manual set!"); } MainUtil.sendMessage(player, "&7 - Populating tables"); TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { - ArrayList plots = new ArrayList<>(PS.get().getPlots()); + @Override public void run() { + ArrayList plots = new ArrayList<>(PlotSquared.get().getPlots()); DBFunc.createPlotsAndData(plots, new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(player, "&aConversion complete!"); } }); @@ -291,7 +286,8 @@ public class DebugUUID extends SubCommand { }); MainUtil.sendMessage(player, "&aIt is now safe for players to join"); - MainUtil.sendMessage(player, "&cConversion is still in progress, you will be notified when it is complete"); + MainUtil.sendMessage(player, + "&cConversion is still in progress, you will be notified when it is complete"); } }); return true; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/APlotMeConnector.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/APlotMeConnector.java similarity index 59% rename from Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/APlotMeConnector.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/APlotMeConnector.java index 1ebae3a93..c55020080 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/APlotMeConnector.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/APlotMeConnector.java @@ -1,10 +1,10 @@ -package com.plotsquared.bukkit.database.plotme; +package com.github.intellectualsites.plotsquared.bukkit.database.plotme; -import com.intellectualcrafters.configuration.file.FileConfiguration; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.configuration.file.FileConfiguration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; import java.sql.Connection; import java.sql.SQLException; @@ -13,9 +13,11 @@ import java.util.HashMap; public abstract class APlotMeConnector { - public abstract Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder); + public abstract Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, + String dataFolder); - public abstract HashMap> getPlotMePlots(Connection connection) throws SQLException; + public abstract HashMap> getPlotMePlots(Connection connection) + throws SQLException; public abstract boolean accepts(String version); @@ -25,21 +27,23 @@ public abstract class APlotMeConnector { public void copyConfig(FileConfiguration plotConfig, String world, String actualWorldName) { int pathWidth = plotConfig.getInt("worlds." + world + ".PathWidth"); // - PS.get().worlds.set("worlds." + actualWorldName + ".road.width", pathWidth); + PlotSquared.get().worlds.set("worlds." + actualWorldName + ".road.width", pathWidth); int plotSize = plotConfig.getInt("worlds." + world + ".PlotSize"); // - PS.get().worlds.set("worlds." + actualWorldName + ".plot.size", plotSize); + PlotSquared.get().worlds.set("worlds." + actualWorldName + ".plot.size", plotSize); String wallBlock = plotConfig.getString("worlds." + world + ".WallBlockId"); // - PS.get().worlds.set("worlds." + actualWorldName + ".wall.block", wallBlock); + PlotSquared.get().worlds.set("worlds." + actualWorldName + ".wall.block", wallBlock); String floor = plotConfig.getString("worlds." + world + ".PlotFloorBlockId"); // - PS.get().worlds.set("worlds." + actualWorldName + ".plot.floor", Collections.singletonList(floor)); + PlotSquared.get().worlds + .set("worlds." + actualWorldName + ".plot.floor", Collections.singletonList(floor)); String filling = plotConfig.getString("worlds." + world + ".PlotFillingBlockId"); // - PS.get().worlds.set("worlds." + actualWorldName + ".plot.filling", Collections.singletonList(filling)); + PlotSquared.get().worlds + .set("worlds." + actualWorldName + ".plot.filling", Collections.singletonList(filling)); String road = plotConfig.getString("worlds." + world + ".RoadMainBlockId"); - PS.get().worlds.set("worlds." + actualWorldName + ".road.block", road); + PlotSquared.get().worlds.set("worlds." + actualWorldName + ".road.block", road); int height = plotConfig.getInt("worlds." + world + ".RoadHeight"); // - PS.get().worlds.set("worlds." + actualWorldName + ".road.height", height); - PS.get().worlds.set("worlds." + actualWorldName + ".plot.height", height); - PS.get().worlds.set("worlds." + actualWorldName + ".wall.height", height); + PlotSquared.get().worlds.set("worlds." + actualWorldName + ".road.height", height); + PlotSquared.get().worlds.set("worlds." + actualWorldName + ".plot.height", height); + PlotSquared.get().worlds.set("worlds." + actualWorldName + ".wall.height", height); } public Location getPlotTopLocAbs(int path, int plot, PlotId plotId) { @@ -58,25 +62,26 @@ public abstract class APlotMeConnector { return new Location(null, x, 1, z); } - public void setMerged(HashMap> merges, String world, PlotId id, int direction) { + public void setMerged(HashMap> merges, String world, + PlotId id, int direction) { HashMap plots = merges.get(world); PlotId id2 = new PlotId(id.x, id.y); boolean[] merge1; if (plots.containsKey(id)) { merge1 = plots.get(id); } else { - merge1 = new boolean[] { false, false, false, false }; + merge1 = new boolean[] {false, false, false, false}; } boolean[] merge2; if (plots.containsKey(id2)) { merge2 = plots.get(id2); } else { - merge2 = new boolean[] { false, false, false, false }; + merge2 = new boolean[] {false, false, false, false}; } merge1[direction] = true; merge2[(direction + 2) % 4] = true; plots.put(id, merge1); plots.put(id2, merge1); } - + } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java similarity index 74% rename from Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java index 11cea6ddb..929360555 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/ClassicPlotMeConnector.java @@ -1,25 +1,17 @@ -package com.plotsquared.bukkit.database.plotme; +package com.github.intellectualsites.plotsquared.bukkit.database.plotme; +import com.github.intellectualsites.plotsquared.configuration.file.FileConfiguration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.database.SQLite; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; import com.google.common.base.Charsets; -import com.intellectualcrafters.configuration.file.FileConfiguration; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.database.SQLite; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.StringWrapper; -import com.intellectualcrafters.plot.util.UUIDHandler; import java.io.File; import java.nio.ByteBuffer; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import java.util.HashMap; import java.util.Map.Entry; import java.util.UUID; @@ -29,8 +21,8 @@ public class ClassicPlotMeConnector extends APlotMeConnector { private String plugin = "PlotMe"; private String prefix; - @Override - public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) { + @Override public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, + String dataFolder) { this.plugin = plugin.toLowerCase(); this.prefix = plotConfig.getString("mySQLprefix", this.plugin.toLowerCase()); try { @@ -40,7 +32,8 @@ public class ClassicPlotMeConnector extends APlotMeConnector { String con = plotConfig.getString("mySQLconn"); return DriverManager.getConnection(con, user, password); } else { - return new SQLite(new File(dataFolder + File.separator + "plots.db")).openConnection(); + return new SQLite(new File(dataFolder + File.separator + "plots.db")) + .openConnection(); } } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); @@ -48,13 +41,14 @@ public class ClassicPlotMeConnector extends APlotMeConnector { return null; } - @Override - public HashMap> getPlotMePlots(Connection connection) throws SQLException { + @Override public HashMap> getPlotMePlots(Connection connection) + throws SQLException { HashMap plotWidth = new HashMap<>(); HashMap roadWidth = new HashMap<>(); HashMap> plots = new HashMap<>(); HashMap> merges = new HashMap<>(); - PreparedStatement statement = connection.prepareStatement("SELECT * FROM `" + this.prefix + "Plots`"); + PreparedStatement statement = + connection.prepareStatement("SELECT * FROM `" + this.prefix + "Plots`"); ResultSet resultSet = statement.executeQuery(); String column = null; boolean checkUUID = DBFunc.hasColumn(resultSet, "ownerid"); @@ -64,7 +58,8 @@ public class ClassicPlotMeConnector extends APlotMeConnector { } else if (checkUUID2) { column = "ownerId"; } - boolean merge = !"plotme".equalsIgnoreCase(this.plugin) && Settings.Enabled_Components.PLOTME_CONVERTER; + boolean merge = + !"plotme".equalsIgnoreCase(this.plugin) && Settings.Enabled_Components.PLOTME_CONVERTER; int missing = 0; while (resultSet.next()) { PlotId id = new PlotId(resultSet.getInt("idX"), resultSet.getInt("idZ")); @@ -73,8 +68,8 @@ public class ClassicPlotMeConnector extends APlotMeConnector { if (!plots.containsKey(world)) { plots.put(world, new HashMap()); if (merge) { - int plot = PS.get().worlds.getInt("worlds." + world + ".plot.size"); - int path = PS.get().worlds.getInt("worlds." + world + ".road.width"); + int plot = PlotSquared.get().worlds.getInt("worlds." + world + ".plot.size"); + int path = PlotSquared.get().worlds.getInt("worlds." + world + ".road.width"); plotWidth.put(world, plot); roadWidth.put(world, path); merges.put(world, new HashMap()); @@ -105,7 +100,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector { UUID owner = UUIDHandler.getUUID(name, null); if (owner == null) { if ("*".equals(name)) { - owner = DBFunc.everyone; + owner = DBFunc.EVERYONE; } else { if (checkUUID || checkUUID2) { byte[] bytes = resultSet.getBytes(column); @@ -118,11 +113,13 @@ public class ClassicPlotMeConnector extends APlotMeConnector { } } if (name.isEmpty()) { - PS.log("&cCould not identify owner for plot: " + id + " -> '" + name + "'"); + PlotSquared.log( + "&cCould not identify owner for plot: " + id + " -> '" + name + "'"); missing++; continue; } - owner = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8)); + owner = UUID.nameUUIDFromBytes( + ("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8)); } } else { UUIDHandler.add(new StringWrapper(name), owner); @@ -131,10 +128,13 @@ public class ClassicPlotMeConnector extends APlotMeConnector { plots.get(world).put(id, plot); } if (missing > 0) { - PS.log("&cSome names could not be identified:"); - PS.log("&7 - Empty quotes mean PlotMe just stored an unowned plot in the database"); - PS.log("&7 - Names you have never seen before could be from people mistyping commands"); - PS.log("&7 - Converting from a non-uuid version of PlotMe can't identify owners if the playerdata files are deleted (these plots will " + PlotSquared.log("&cSome names could not be identified:"); + PlotSquared + .log("&7 - Empty quotes mean PlotMe just stored an unowned plot in the database"); + PlotSquared.log( + "&7 - Names you have never seen before could be from people mistyping commands"); + PlotSquared.log( + "&7 - Converting from a non-uuid version of PlotMe can't identify owners if the playerdata files are deleted (these plots will " + "remain unknown until the player connects)"); } @@ -154,7 +154,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector { try { - PS.log(" - " + this.prefix + "Denied"); + PlotSquared.log(" - " + this.prefix + "Denied"); statement = connection.prepareStatement("SELECT * FROM `" + this.prefix + "Denied`"); resultSet = statement.executeQuery(); @@ -165,7 +165,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector { UUID denied = UUIDHandler.getUUID(name, null); if (denied == null) { if ("*".equals(name)) { - denied = DBFunc.everyone; + denied = DBFunc.EVERYONE; } else if (DBFunc.hasColumn(resultSet, "playerid")) { byte[] bytes = resultSet.getBytes("playerid"); if (bytes != null) { @@ -177,7 +177,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector { } } if (denied == null) { - PS.log("&6Could not identify denied for plot: " + id); + PlotSquared.log("&6Could not identify denied for plot: " + id); continue; } } @@ -200,7 +200,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector { UUID helper = UUIDHandler.getUUID(name, null); if (helper == null) { if ("*".equals(name)) { - helper = DBFunc.everyone; + helper = DBFunc.EVERYONE; } else if (DBFunc.hasColumn(resultSet, "playerid")) { byte[] bytes = resultSet.getBytes("playerid"); if (bytes != null) { @@ -212,7 +212,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector { } } if (helper == null) { - PS.log("&6Could not identify helper for plot: " + id); + PlotSquared.log("&6Could not identify helper for plot: " + id); continue; } } @@ -228,12 +228,13 @@ public class ClassicPlotMeConnector extends APlotMeConnector { resultSet.close(); statement.close(); - } catch (SQLException ignored) {} + } catch (SQLException ignored) { + } return plots; } - @Override - public boolean accepts(String version) { - return version == null || PS.get().canUpdate(version, "0.17.0") || PS.get().canUpdate("0.999.999", version); + @Override public boolean accepts(String version) { + return version == null || PlotSquared.get().canUpdate(version, "0.17.0") || PlotSquared + .get().canUpdate("0.999.999", version); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java similarity index 58% rename from Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java index 05d8f4a20..b17583107 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/LikePlotMeConverter.java @@ -1,17 +1,22 @@ -package com.plotsquared.bukkit.database.plotme; +package com.github.intellectualsites.plotsquared.bukkit.database.plotme; + +import com.github.intellectualsites.plotsquared.bukkit.generator.BukkitPlotGenerator; +import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection; +import com.github.intellectualsites.plotsquared.configuration.MemorySection; +import com.github.intellectualsites.plotsquared.configuration.file.FileConfiguration; +import com.github.intellectualsites.plotsquared.configuration.file.YamlConfiguration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.WorldCreator; +import org.bukkit.command.CommandException; -import com.intellectualcrafters.configuration.ConfigurationSection; -import com.intellectualcrafters.configuration.MemorySection; -import com.intellectualcrafters.configuration.file.FileConfiguration; -import com.intellectualcrafters.configuration.file.YamlConfiguration; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.util.TaskManager; -import com.plotsquared.bukkit.generator.BukkitPlotGenerator; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -20,17 +25,9 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.sql.Connection; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; +import java.util.*; import java.util.Map.Entry; -import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.WorldCreator; -import org.bukkit.command.CommandException; public class LikePlotMeConverter { @@ -50,11 +47,13 @@ public class LikePlotMeConverter { } private void sendMessage(String message) { - PS.debug("&3PlotMe&8->&3" + PS.imp().getPluginName() + "&8: &7" + message); + PlotSquared + .debug("&3PlotMe&8->&3" + PlotSquared.imp().getPluginName() + "&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 FileConfiguration getPlotMeConfig(String dataFolder) { @@ -71,8 +70,9 @@ public class LikePlotMeConverter { public void mergeWorldYml(FileConfiguration plotConfig) { try { - File genConfig = - new File("plugins" + File.separator + plugin + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml"); + File genConfig = new File( + "plugins" + File.separator + plugin + File.separator + "PlotMe-DefaultGenerator" + + File.separator + "config.yml"); if (genConfig.exists()) { YamlConfiguration yml = YamlConfiguration.loadConfiguration(genConfig); for (String key : yml.getKeys(true)) { @@ -97,40 +97,47 @@ public class LikePlotMeConverter { return; } String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); - String pluginName = PS.imp().getPluginName(); + String pluginName = PlotSquared.imp().getPluginName(); content = content.replace("PlotMe-DefaultGenerator", pluginName); content = content.replace("PlotMe", pluginName); content = content.replace("AthionPlots", pluginName); content = content.replace("PlotZWorld", pluginName); Files.write(path, content.getBytes(StandardCharsets.UTF_8)); - } catch (IOException ignored) {} + } catch (IOException ignored) { + } } private void copyConfig(ConfigurationSection plotmeDgYml, String world) throws IOException { String actualWorldName = getWorld(world); String plotMeWorldName = world.toLowerCase(); Integer pathWidth = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".PathWidth"); // - PS.get().worlds.set("worlds." + world + ".road.width", pathWidth); - int height = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".RoadHeight", plotmeDgYml.getInt("worlds." + plotMeWorldName + ".GroundHeight", 64)); // - PS.get().worlds.set("worlds." + world + ".road.height", height); - PS.get().worlds.set("worlds." + world + ".wall.height", height); - PS.get().worlds.set("worlds." + world + ".plot.height", height); + PlotSquared.get().worlds.set("worlds." + world + ".road.width", pathWidth); + int height = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".RoadHeight", + plotmeDgYml.getInt("worlds." + plotMeWorldName + ".GroundHeight", 64)); // + PlotSquared.get().worlds.set("worlds." + world + ".road.height", height); + PlotSquared.get().worlds.set("worlds." + world + ".wall.height", height); + PlotSquared.get().worlds.set("worlds." + world + ".plot.height", height); int plotSize = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".PlotSize", 32); // - PS.get().worlds.set("worlds." + world + ".plot.size", plotSize); - String wallblock = plotmeDgYml.getString("worlds." + plotMeWorldName + ".UnclaimedBorder", plotmeDgYml.getString("worlds." + plotMeWorldName + ".WallBlock", "44")); // - PS.get().worlds.set("worlds." + world + ".wall.block", wallblock); - String claimed = plotmeDgYml.getString("worlds." + plotMeWorldName + ".ProtectedWallBlock", "44:1"); // - PS.get().worlds.set("worlds." + world + ".wall.block_claimed", claimed); - String floor = plotmeDgYml.getString("worlds." + plotMeWorldName + ".PlotFloorBlock", "2"); // - PS.get().worlds.set("worlds." + world + ".plot.floor", Collections.singletonList(floor)); + PlotSquared.get().worlds.set("worlds." + world + ".plot.size", plotSize); + String wallblock = plotmeDgYml.getString("worlds." + plotMeWorldName + ".UnclaimedBorder", + plotmeDgYml.getString("worlds." + plotMeWorldName + ".WallBlock", "44")); // + PlotSquared.get().worlds.set("worlds." + world + ".wall.block", wallblock); + String claimed = + plotmeDgYml.getString("worlds." + plotMeWorldName + ".ProtectedWallBlock", "44:1"); // + PlotSquared.get().worlds.set("worlds." + world + ".wall.block_claimed", claimed); + String floor = + plotmeDgYml.getString("worlds." + plotMeWorldName + ".PlotFloorBlock", "2"); // + PlotSquared.get().worlds + .set("worlds." + world + ".plot.floor", Collections.singletonList(floor)); String filling = plotmeDgYml.getString("worlds." + plotMeWorldName + ".FillBlock", "3"); // - PS.get().worlds.set("worlds." + world + ".plot.filling", Collections.singletonList(filling)); + PlotSquared.get().worlds + .set("worlds." + world + ".plot.filling", Collections.singletonList(filling)); String road = plotmeDgYml.getString("worlds." + plotMeWorldName + ".RoadMainBlock", "5"); - PS.get().worlds.set("worlds." + world + ".road.block", road); - PS.get().worlds.set("worlds." + actualWorldName + ".road.height", height); - PS.get().worlds.set("worlds." + actualWorldName + ".plot.height", height); - PS.get().worlds.set("worlds." + actualWorldName + ".wall.height", height); - PS.get().worlds.save(PS.get().worldsFile); + PlotSquared.get().worlds.set("worlds." + world + ".road.block", road); + PlotSquared.get().worlds.set("worlds." + actualWorldName + ".road.height", height); + PlotSquared.get().worlds.set("worlds." + actualWorldName + ".plot.height", height); + PlotSquared.get().worlds.set("worlds." + actualWorldName + ".wall.height", height); + PlotSquared.get().worlds.save(PlotSquared.get().worldsFile); } public boolean run(APlotMeConnector connector) { @@ -149,16 +156,17 @@ public class LikePlotMeConverter { return false; } - PS.debug("&3Using connector: " + connector.getClass().getCanonicalName()); + PlotSquared.debug("&3Using connector: " + connector.getClass().getCanonicalName()); - Connection connection = connector.getPlotMeConnection(plugin,plotConfig, dataFolder); + Connection connection = connector.getPlotMeConnection(plugin, plotConfig, dataFolder); if (!connector.isValidConnection(connection)) { sendMessage("Cannot connect to PlotMe DB. Conversion process will not continue"); return false; } - sendMessage("PlotMe conversion has started. To disable this, please set 'enabled-components -> plotme-converter' to false in the 'settings.yml'"); + sendMessage( + "PlotMe conversion has started. To disable this, please set 'enabled-components -> plotme-converter' to false in the 'settings.yml'"); mergeWorldYml(plotConfig); @@ -181,11 +189,11 @@ public class LikePlotMeConverter { try { String actualWorldName = getWorld(world); connector.copyConfig(plotConfig, world, actualWorldName); - PS.get().worlds.save(PS.get().worldsFile); + PlotSquared.get().worlds.save(PlotSquared.get().worldsFile); } catch (IOException e) { e.printStackTrace(); sendMessage("&c-- &lFailed to save configuration for world '" + world - + "'\nThis will need to be done using the setup command, or manually"); + + "'\nThis will need to be done using the setup command, or manually"); } } } @@ -201,7 +209,9 @@ public class LikePlotMeConverter { sendMessage(" - " + dbPrefix + "Allowed"); sendMessage("Collected " + plotCount + " plots from PlotMe"); - File plotmeDgFile = new File(dataFolder + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml"); + File plotmeDgFile = new File( + dataFolder + File.separator + "PlotMe-DefaultGenerator" + File.separator + + "config.yml"); if (plotmeDgFile.exists()) { YamlConfiguration plotmeDgYml = YamlConfiguration.loadConfiguration(plotmeDgFile); try { @@ -216,7 +226,7 @@ public class LikePlotMeConverter { } for (Entry> entry : plots.entrySet()) { String world = entry.getKey(); - PlotArea area = PS.get().getPlotArea(world, null); + PlotArea area = PlotSquared.get().getPlotArea(world, null); int duplicate = 0; if (area != null) { for (Entry entry2 : entry.getValue().entrySet()) { @@ -227,12 +237,13 @@ public class LikePlotMeConverter { } } if (duplicate > 0) { - PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world - + "'. Have you run the converter already?"); + PlotSquared.debug("&c[WARNING] Found " + duplicate + + " duplicate plots already in DB for world: '" + world + + "'. Have you run the converter already?"); } } else { - if (PS.get().plots_tmp != null) { - HashMap map = PS.get().plots_tmp.get(world); + if (PlotSquared.get().plots_tmp != null) { + HashMap map = PlotSquared.get().plots_tmp.get(world); if (map != null) { for (Entry entry2 : entry.getValue().entrySet()) { if (map.containsKey(entry2.getKey())) { @@ -242,8 +253,9 @@ public class LikePlotMeConverter { } } if (duplicate > 0) { - PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world - + "'. Have you run the converter already?"); + PlotSquared.debug("&c[WARNING] Found " + duplicate + + " duplicate plots already in DB for world: '" + world + + "'. Have you run the converter already?"); } continue; } @@ -255,80 +267,96 @@ public class LikePlotMeConverter { Thread.sleep(1000); final AtomicBoolean done = new AtomicBoolean(false); DBFunc.createPlotsAndData(createdPlots, new Runnable() { - @Override - public void run() { + @Override public void run() { if (done.get()) { done(); sendMessage("&aDatabase conversion is now complete!"); - PS.debug("&c - Stop the server"); - PS.debug("&c - Disable 'plotme-converter' and 'plotme-convert.cache-uuids' in the settings.yml"); - PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly"); - PS.debug("&c - Start the server"); - PS.get().setPlots(DBFunc.getPlots()); + PlotSquared.debug("&c - Stop the server"); + PlotSquared.debug( + "&c - Disable 'plotme-converter' and 'plotme-convert.cache-uuids' in the settings.yml"); + PlotSquared.debug( + "&c - Correct any generator settings that haven't copied to 'settings.yml' properly"); + PlotSquared.debug("&c - Start the server"); + PlotSquared.get().setPlots(DBFunc.getPlots()); } else { - sendMessage("&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); + sendMessage( + "&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); done.set(true); } } }); sendMessage("Saving configuration..."); try { - PS.get().worlds.save(PS.get().worldsFile); + PlotSquared.get().worlds.save(PlotSquared.get().worldsFile); } catch (IOException ignored) { sendMessage(" - &cFailed to save configuration."); } TaskManager.runTask(new Runnable() { - @Override - public void run() { + @Override public void run() { try { boolean mv = false; boolean mw = false; - if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core") - .isEnabled()) { + if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) + && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { mv = true; - } else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld") - .isEnabled()) { + } else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) + && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) { mw = true; } for (String worldName : worlds) { World world = Bukkit.getWorld(getWorld(worldName)); if (world == null) { - sendMessage("&cInvalid world in PlotMe configuration: " + worldName); + sendMessage( + "&cInvalid world in PlotMe configuration: " + worldName); continue; } String actualWorldName = world.getName(); - sendMessage("Reloading generator for world: '" + actualWorldName + "'..."); - if (!Bukkit.getWorlds().isEmpty() && Bukkit.getWorlds().get(0).getName().equals(worldName)) { - sendMessage("&cYou need to stop the server to reload this world properly"); + sendMessage( + "Reloading generator for world: '" + actualWorldName + "'..."); + if (!Bukkit.getWorlds().isEmpty() && Bukkit.getWorlds().get(0).getName() + .equals(worldName)) { + sendMessage( + "&cYou need to stop the server to reload this world properly"); } else { - PS.get().removePlotAreas(actualWorldName); + PlotSquared.get().removePlotAreas(actualWorldName); if (mv) { // unload world with MV - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName); + Bukkit.getServer() + .dispatchCommand(Bukkit.getServer().getConsoleSender(), + "mv unload " + actualWorldName); try { Thread.sleep(1000); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } // load world with MV - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), - "mv import " + actualWorldName + " normal -g " + PS.imp().getPluginName()); + Bukkit.getServer() + .dispatchCommand(Bukkit.getServer().getConsoleSender(), + "mv import " + actualWorldName + " normal -g " + + PlotSquared.imp().getPluginName()); } else if (mw) { // unload world with MW - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw unload " + actualWorldName); + Bukkit.getServer() + .dispatchCommand(Bukkit.getServer().getConsoleSender(), + "mw unload " + actualWorldName); try { Thread.sleep(1000); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } // load world with MW - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), - "mw create " + actualWorldName + " plugin:" + PS.imp().getPluginName()); + Bukkit.getServer() + .dispatchCommand(Bukkit.getServer().getConsoleSender(), + "mw create " + actualWorldName + " plugin:" + + PlotSquared.imp().getPluginName()); } else { // Load using Bukkit API // - User must set generator manually Bukkit.getServer().unloadWorld(world, true); - World myWorld = WorldCreator.name(actualWorldName).generator(new BukkitPlotGenerator(PS.get().IMP.getDefaultGenerator())).createWorld(); + World myWorld = WorldCreator.name(actualWorldName).generator( + new BukkitPlotGenerator( + PlotSquared.get().IMP.getDefaultGenerator())) + .createWorld(); myWorld.save(); } } @@ -339,24 +367,27 @@ public class LikePlotMeConverter { if (done.get()) { done(); sendMessage("&aDatabase conversion is now complete!"); - PS.debug("&c - Stop the server"); - PS.debug("&c - Disable 'plotme-converter' and 'plotme-convert.cache-uuids' in the settings.yml"); - PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly"); - PS.debug("&c - Start the server"); + PlotSquared.debug("&c - Stop the server"); + PlotSquared.debug( + "&c - Disable 'plotme-converter' and 'plotme-convert.cache-uuids' in the settings.yml"); + PlotSquared.debug( + "&c - Correct any generator settings that haven't copied to 'settings.yml' properly"); + PlotSquared.debug("&c - Start the server"); } else { - sendMessage("&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); + sendMessage( + "&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); done.set(true); } } }); } catch (InterruptedException | SQLException e) { e.printStackTrace(); - PS.debug("&/end/"); + PlotSquared.debug("&/end/"); } return true; } public void done() { - PS.get().setPlots(DBFunc.getPlots()); + PlotSquared.get().setPlots(DBFunc.getPlots()); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java similarity index 66% rename from Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java index 9567ebb8f..0aa5afcd5 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/database/plotme/PlotMeConnector_017.java @@ -1,23 +1,15 @@ -package com.plotsquared.bukkit.database.plotme; +package com.github.intellectualsites.plotsquared.bukkit.database.plotme; -import com.intellectualcrafters.configuration.file.FileConfiguration; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.database.SQLite; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.StringWrapper; -import com.intellectualcrafters.plot.util.UUIDHandler; +import com.github.intellectualsites.plotsquared.configuration.file.FileConfiguration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.database.SQLite; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import java.util.HashMap; import java.util.UUID; @@ -25,8 +17,8 @@ public class PlotMeConnector_017 extends APlotMeConnector { private String plugin; - @Override - public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) { + @Override public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, + String dataFolder) { this.plugin = plugin.toLowerCase(); try { if (plotConfig.getBoolean("usemySQL")) { @@ -39,7 +31,8 @@ public class PlotMeConnector_017 extends APlotMeConnector { if (file.exists()) { return new SQLite(file).openConnection(); } - return new SQLite(new File(dataFolder + File.separator + "plots.db")).openConnection(); + return new SQLite(new File(dataFolder + File.separator + "plots.db")) + .openConnection(); } } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); @@ -47,8 +40,8 @@ public class PlotMeConnector_017 extends APlotMeConnector { return null; } - @Override - public HashMap> getPlotMePlots(Connection connection) throws SQLException { + @Override public HashMap> getPlotMePlots(Connection connection) + throws SQLException { ResultSet resultSet; PreparedStatement statement; HashMap plotWidth = new HashMap<>(); @@ -56,26 +49,30 @@ public class PlotMeConnector_017 extends APlotMeConnector { HashMap plots = new HashMap<>(); HashMap> merges = new HashMap<>(); try { - statement = connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_plots`"); + statement = + connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_plots`"); resultSet = statement.executeQuery(); } catch (SQLException e) { - PS.debug("========= Table does not exist ========="); + PlotSquared.debug("========= Table does not exist ========="); e.printStackTrace(); - PS.debug("======================================="); - PS.debug("&8 - &7The database does not match the version specified in the PlotMe config"); - PS.debug("&8 - &7Please correct this, or if you are unsure, the most common is 0.16.3"); + PlotSquared.debug("======================================="); + PlotSquared.debug( + "&8 - &7The database does not match the version specified in the PlotMe config"); + PlotSquared.debug( + "&8 - &7Please correct this, or if you are unsure, the most common is 0.16.3"); return null; } boolean checkUUID = DBFunc.hasColumn(resultSet, "ownerID"); - boolean merge = !"plotme".equals(this.plugin) && Settings.Enabled_Components.PLOTME_CONVERTER; + boolean merge = + !"plotme".equals(this.plugin) && Settings.Enabled_Components.PLOTME_CONVERTER; while (resultSet.next()) { int key = resultSet.getInt("plot_id"); PlotId id = new PlotId(resultSet.getInt("plotX"), resultSet.getInt("plotZ")); String name = resultSet.getString("owner"); String world = LikePlotMeConverter.getWorld(resultSet.getString("world")); if (!plots.containsKey(world) && merge) { - int plot = PS.get().worlds.getInt("worlds." + world + ".plot.size"); - int path = PS.get().worlds.getInt("worlds." + world + ".road.width"); + int plot = PlotSquared.get().worlds.getInt("worlds." + world + ".plot.size"); + int path = PlotSquared.get().worlds.getInt("worlds." + world + ".road.width"); plotWidth.put(world, plot); roadWidth.put(world, path); merges.put(world, new HashMap()); @@ -105,7 +102,7 @@ public class PlotMeConnector_017 extends APlotMeConnector { UUID owner = UUIDHandler.getUUID(name, null); if (owner == null) { if (name.equals("*")) { - owner = DBFunc.everyone; + owner = DBFunc.EVERYONE; } else { if (checkUUID) { byte[] bytes = resultSet.getBytes("ownerid"); @@ -115,7 +112,8 @@ public class PlotMeConnector_017 extends APlotMeConnector { } } if (owner == null) { - PS.log("&cCould not identify owner for plot: " + id + " -> '" + name + '\''); + PlotSquared.log( + "&cCould not identify owner for plot: " + id + " -> '" + name + '\''); continue; } } @@ -136,35 +134,39 @@ public class PlotMeConnector_017 extends APlotMeConnector { resultSet.close(); statement.close(); try { - PS.log(" - " + this.plugin + "core_denied"); - statement = connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_denied`"); + PlotSquared.log(" - " + this.plugin + "core_denied"); + statement = + connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_denied`"); resultSet = statement.executeQuery(); while (resultSet.next()) { int key = resultSet.getInt("plot_id"); Plot plot = plots.get(key); if (plot == null) { - PS.log("&6Denied (" + key + ") references deleted plot; ignoring entry."); + PlotSquared + .log("&6Denied (" + key + ") references deleted plot; ignoring entry."); continue; } String player = resultSet.getString("player"); - UUID denied = player.equals("*") ? DBFunc.everyone : UUID.fromString(player); + UUID denied = player.equals("*") ? DBFunc.EVERYONE : UUID.fromString(player); plot.getDenied().add(denied); } - PS.log(" - " + this.plugin + "core_allowed"); - statement = connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_allowed`"); + PlotSquared.log(" - " + this.plugin + "core_allowed"); + statement = + connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_allowed`"); resultSet = statement.executeQuery(); while (resultSet.next()) { int key = resultSet.getInt("plot_id"); Plot plot = plots.get(key); if (plot == null) { - PS.log("&6Allowed (" + key + ") references deleted plot; ignoring entry."); + PlotSquared + .log("&6Allowed (" + key + ") references deleted plot; ignoring entry."); continue; } String player = resultSet.getString("player"); - UUID allowed = player.equals("*") ? DBFunc.everyone : UUID.fromString(player); + UUID allowed = player.equals("*") ? DBFunc.EVERYONE : UUID.fromString(player); plot.getTrusted().add(allowed); } resultSet.close(); @@ -186,11 +188,10 @@ public class PlotMeConnector_017 extends APlotMeConnector { return processed; } - @Override - public boolean accepts(String version) { + @Override public boolean accepts(String version) { if (version == null) { return false; } - return !PS.get().canUpdate(version, "0.17"); + return !PlotSquared.get().canUpdate(version, "0.17"); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java similarity index 75% rename from Bukkit/src/main/java/com/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java index 40e4a4e43..40acef111 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java @@ -1,7 +1,7 @@ -package com.plotsquared.bukkit.events; +package com.github.intellectualsites.plotsquared.bukkit.events; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.object.PlotCluster; +import com.github.intellectualsites.plotsquared.plot.flag.Flag; +import com.github.intellectualsites.plotsquared.plot.object.PlotCluster; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; @@ -19,7 +19,7 @@ public class ClusterFlagRemoveEvent extends Event implements Cancellable { /** * PlotFlagRemoveEvent: Called when a flag is removed from a plot. * - * @param flag Flag that was removed + * @param flag Flag that was removed * @param cluster PlotCluster from which the flag was removed */ public ClusterFlagRemoveEvent(Flag flag, PlotCluster cluster) { @@ -49,18 +49,15 @@ public class ClusterFlagRemoveEvent extends Event implements Cancellable { return this.flag; } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } - @Override - public boolean isCancelled() { + @Override public boolean isCancelled() { return this.cancelled; } - @Override - public void setCancelled(boolean b) { + @Override public void setCancelled(boolean b) { this.cancelled = b; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerClaimPlotEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerClaimPlotEvent.java similarity index 79% rename from Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerClaimPlotEvent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerClaimPlotEvent.java index 6972e1b56..269b64296 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerClaimPlotEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerClaimPlotEvent.java @@ -1,62 +1,59 @@ -package com.plotsquared.bukkit.events; - -import com.intellectualcrafters.plot.object.Plot; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; - -public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private final Plot plot; - 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 - */ - public PlayerClaimPlotEvent(Player player, Plot plot, boolean auto) { - super(player); - this.plot = plot; - this.auto = auto; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * Get the plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } - - /** - * @return true if it was an automated claim, else false - */ - public boolean wasAuto() { - return this.auto; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - @Override - public boolean isCancelled() { - return this.cancelled; - } - - @Override - public void setCancelled(boolean b) { - this.cancelled = b; - } -} +package com.github.intellectualsites.plotsquared.bukkit.events; + +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; + +public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private final Plot plot; + 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 + */ + public PlayerClaimPlotEvent(Player player, Plot plot, boolean auto) { + super(player); + this.plot = plot; + this.auto = auto; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Get the plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } + + /** + * @return true if it was an automated claim, else false + */ + public boolean wasAuto() { + return this.auto; + } + + @Override public HandlerList getHandlers() { + return handlers; + } + + @Override public boolean isCancelled() { + return this.cancelled; + } + + @Override public void setCancelled(boolean b) { + this.cancelled = b; + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerEnterPlotEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerEnterPlotEvent.java similarity index 81% rename from Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerEnterPlotEvent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerEnterPlotEvent.java index db860f35a..a40365b40 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerEnterPlotEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerEnterPlotEvent.java @@ -1,41 +1,40 @@ -package com.plotsquared.bukkit.events; - -import com.intellectualcrafters.plot.object.Plot; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; - -public class PlayerEnterPlotEvent extends PlayerEvent { - - private static final HandlerList handlers = new HandlerList(); - private final Plot plot; - - /** - * Called when a player leaves a plot. - * - * @param player Player that entered the plot - * @param plot Plot that was entered - */ - public PlayerEnterPlotEvent(Player player, Plot plot) { - super(player); - this.plot = plot; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * Get the plot involved. - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } -} +package com.github.intellectualsites.plotsquared.bukkit.events; + +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; + +public class PlayerEnterPlotEvent extends PlayerEvent { + + private static final HandlerList handlers = new HandlerList(); + private final Plot plot; + + /** + * Called when a player leaves a plot. + * + * @param player Player that entered the plot + * @param plot Plot that was entered + */ + public PlayerEnterPlotEvent(Player player, Plot plot) { + super(player); + this.plot = plot; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Get the plot involved. + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } + + @Override public HandlerList getHandlers() { + return handlers; + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerLeavePlotEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerLeavePlotEvent.java similarity index 81% rename from Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerLeavePlotEvent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerLeavePlotEvent.java index 225d89042..465e8cee9 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerLeavePlotEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerLeavePlotEvent.java @@ -1,45 +1,44 @@ -package com.plotsquared.bukkit.events; - -import com.intellectualcrafters.plot.object.Plot; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; - -/** - - - */ -public class PlayerLeavePlotEvent extends PlayerEvent { - - private static final 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 - */ - public PlayerLeavePlotEvent(Player player, Plot plot) { - super(player); - this.plot = plot; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * Get the plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } -} +package com.github.intellectualsites.plotsquared.bukkit.events; + +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; + +/** + + + */ +public class PlayerLeavePlotEvent extends PlayerEvent { + + private static final 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 + */ + public PlayerLeavePlotEvent(Player player, Plot plot) { + super(player); + this.plot = plot; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Get the plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } + + @Override public HandlerList getHandlers() { + return handlers; + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotDeniedEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerPlotDeniedEvent.java similarity index 87% rename from Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotDeniedEvent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerPlotDeniedEvent.java index ab9b43b8b..c9c4d56b9 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotDeniedEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerPlotDeniedEvent.java @@ -1,66 +1,65 @@ -package com.plotsquared.bukkit.events; - -import com.intellectualcrafters.plot.object.Plot; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; - -import java.util.UUID; - -public class PlayerPlotDeniedEvent extends PlotEvent { - - private static final HandlerList handlers = new HandlerList(); - private final Player initiator; - private final boolean added; - private final UUID player; - - /** - * PlayerPlotDeniedEvent: Called when the denied UUID list is modified for a plot. - * - * @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 - */ - public PlayerPlotDeniedEvent(Player initiator, Plot plot, UUID player, boolean added) { - super(plot); - this.initiator = initiator; - this.added = added; - this.player = player; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * If a user was added. - * - * @return boolean - */ - public boolean wasAdded() { - return this.added; - } - - /** - * The player added/removed. - * - * @return UUID - */ - public UUID getPlayer() { - return this.player; - } - - /** - * The player initiating the action. - * - * @return Player - */ - public Player getInitiator() { - return this.initiator; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } -} +package com.github.intellectualsites.plotsquared.bukkit.events; + +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +import java.util.UUID; + +public class PlayerPlotDeniedEvent extends PlotEvent { + + private static final HandlerList handlers = new HandlerList(); + private final Player initiator; + private final boolean added; + private final UUID player; + + /** + * PlayerPlotDeniedEvent: Called when the denied UUID list is modified for a plot. + * + * @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 + */ + public PlayerPlotDeniedEvent(Player initiator, Plot plot, UUID player, boolean added) { + super(plot); + this.initiator = initiator; + this.added = added; + this.player = player; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * If a user was added. + * + * @return boolean + */ + public boolean wasAdded() { + return this.added; + } + + /** + * The player added/removed. + * + * @return UUID + */ + public UUID getPlayer() { + return this.player; + } + + /** + * The player initiating the action. + * + * @return Player + */ + public Player getInitiator() { + return this.initiator; + } + + @Override public HandlerList getHandlers() { + return handlers; + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotHelperEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerPlotHelperEvent.java similarity index 87% rename from Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotHelperEvent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerPlotHelperEvent.java index 8fc635494..2773f9b73 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotHelperEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerPlotHelperEvent.java @@ -1,70 +1,69 @@ -package com.plotsquared.bukkit.events; - -import com.intellectualcrafters.plot.object.Plot; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; - -import java.util.UUID; - -/** - - - */ -public class PlayerPlotHelperEvent extends PlotEvent { - - private static final HandlerList handlers = new HandlerList(); - private final Player initiator; - private final boolean added; - private final UUID player; - - /** - * PlayerPlotHelperEvent: Called when a plot helper is added/removed - * - * @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 - */ - public PlayerPlotHelperEvent(Player initiator, Plot plot, UUID player, boolean added) { - super(plot); - this.initiator = initiator; - this.added = added; - this.player = player; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * If a player was added - * - * @return boolean - */ - public boolean wasAdded() { - return this.added; - } - - /** - * The UUID added/removed - * - * @return UUID - */ - public UUID getPlayer() { - return this.player; - } - - /** - * The player initiating the action - * - * @return Player - */ - public Player getInitiator() { - return this.initiator; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } -} +package com.github.intellectualsites.plotsquared.bukkit.events; + +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +import java.util.UUID; + +/** + + + */ +public class PlayerPlotHelperEvent extends PlotEvent { + + private static final HandlerList handlers = new HandlerList(); + private final Player initiator; + private final boolean added; + private final UUID player; + + /** + * PlayerPlotHelperEvent: Called when a plot helper is added/removed + * + * @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 + */ + public PlayerPlotHelperEvent(Player initiator, Plot plot, UUID player, boolean added) { + super(plot); + this.initiator = initiator; + this.added = added; + this.player = player; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * If a player was added + * + * @return boolean + */ + public boolean wasAdded() { + return this.added; + } + + /** + * The UUID added/removed + * + * @return UUID + */ + public UUID getPlayer() { + return this.player; + } + + /** + * The player initiating the action + * + * @return Player + */ + public Player getInitiator() { + return this.initiator; + } + + @Override public HandlerList getHandlers() { + return handlers; + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java similarity index 87% rename from Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java index 2af07a33a..95440056f 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerPlotTrustedEvent.java @@ -1,70 +1,69 @@ -package com.plotsquared.bukkit.events; - -import com.intellectualcrafters.plot.object.Plot; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; - -import java.util.UUID; - -/** - - - */ -public class PlayerPlotTrustedEvent extends PlotEvent { - - private static final HandlerList handlers = new HandlerList(); - private final Player initiator; - private final boolean added; - private final UUID player; - - /** - * PlayerPlotTrustedEvent: Called when a plot trusted user is added/removed - * - * @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 - */ - public PlayerPlotTrustedEvent(Player initiator, Plot plot, UUID player, boolean added) { - super(plot); - this.initiator = initiator; - this.added = added; - this.player = player; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * If a player was added - * - * @return boolean - */ - public boolean wasAdded() { - return this.added; - } - - /** - * The UUID added/removed - * - * @return UUID - */ - public UUID getPlayer() { - return this.player; - } - - /** - * The player initiating the action - * - * @return Player - */ - public Player getInitiator() { - return this.initiator; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } -} +package com.github.intellectualsites.plotsquared.bukkit.events; + +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +import java.util.UUID; + +/** + + + */ +public class PlayerPlotTrustedEvent extends PlotEvent { + + private static final HandlerList handlers = new HandlerList(); + private final Player initiator; + private final boolean added; + private final UUID player; + + /** + * PlayerPlotTrustedEvent: Called when a plot trusted user is added/removed + * + * @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 + */ + public PlayerPlotTrustedEvent(Player initiator, Plot plot, UUID player, boolean added) { + super(plot); + this.initiator = initiator; + this.added = added; + this.player = player; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * If a player was added + * + * @return boolean + */ + public boolean wasAdded() { + return this.added; + } + + /** + * The UUID added/removed + * + * @return UUID + */ + public UUID getPlayer() { + return this.player; + } + + /** + * The player initiating the action + * + * @return Player + */ + public Player getInitiator() { + return this.initiator; + } + + @Override public HandlerList getHandlers() { + return handlers; + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerTeleportToPlotEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerTeleportToPlotEvent.java similarity index 77% rename from Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerTeleportToPlotEvent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerTeleportToPlotEvent.java index 069ade2ca..79d43391e 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlayerTeleportToPlotEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerTeleportToPlotEvent.java @@ -1,72 +1,66 @@ -package com.plotsquared.bukkit.events; - -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; - -/** - * 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 boolean cancelled; - - /** - * PlayerTeleportToPlotEvent: Called when a player teleports to a plot - * - * @param player That was teleported - * @param from Start location - * @param plot Plot to which the player was teleported - */ - public PlayerTeleportToPlotEvent(Player player, Location from, Plot plot) { - super(player); - this.from = from; - this.plot = plot; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - /** - * Get the from location - * - * @return Location - */ - public Location getFrom() { - return this.from; - } - - /** - * Get the plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } - - @Override - public boolean isCancelled() { - return this.cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } -} +package com.github.intellectualsites.plotsquared.bukkit.events; + +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerEvent; + +/** + * 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 boolean cancelled; + + /** + * PlayerTeleportToPlotEvent: Called when a player teleports to a plot + * + * @param player That was teleported + * @param from Start location + * @param plot Plot to which the player was teleported + */ + public PlayerTeleportToPlotEvent(Player player, Location from, Plot plot) { + super(player); + this.from = from; + this.plot = plot; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override public HandlerList getHandlers() { + return handlers; + } + + /** + * Get the from location + * + * @return Location + */ + public Location getFrom() { + return this.from; + } + + /** + * Get the plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } + + @Override public boolean isCancelled() { + return this.cancelled; + } + + @Override public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotChangeOwnerEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotChangeOwnerEvent.java similarity index 83% rename from Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotChangeOwnerEvent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotChangeOwnerEvent.java index 81dea45a3..3fba03284 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotChangeOwnerEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotChangeOwnerEvent.java @@ -1,7 +1,7 @@ -package com.plotsquared.bukkit.events; +package com.github.intellectualsites.plotsquared.bukkit.events; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; @@ -24,7 +24,8 @@ public class PlotChangeOwnerEvent extends PlotEvent implements Cancellable { * @param oldOwner The old owner of the plot * @param plot The plot having its owner changed */ - public PlotChangeOwnerEvent(Player initiator, Plot plot, UUID oldOwner, UUID newOwner, boolean hasOldOwner) { + public PlotChangeOwnerEvent(Player initiator, Plot plot, UUID oldOwner, UUID newOwner, + boolean hasOldOwner) { super(plot); this.initiator = initiator; this.newOwner = newOwner; @@ -90,18 +91,15 @@ public class PlotChangeOwnerEvent extends PlotEvent implements Cancellable { return this.hasOldOwner; } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } - @Override - public boolean isCancelled() { + @Override public boolean isCancelled() { return this.cancelled; } - @Override - public void setCancelled(boolean b) { + @Override public void setCancelled(boolean b) { this.cancelled = b; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotClearEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotClearEvent.java similarity index 69% rename from Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotClearEvent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotClearEvent.java index 20ab1d519..b4ab469a2 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotClearEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotClearEvent.java @@ -1,56 +1,53 @@ -package com.plotsquared.bukkit.events; - -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotId; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; - -/** - * Called when a plot is cleared - * - */ -public class PlotClearEvent extends PlotEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled; - public PlotClearEvent(Plot plot) { - super(plot); - } - - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * Get the PlotId. - * - * @return PlotId - */ - public PlotId getPlotId() { - return getPlot().getId(); - } - - /** - * Get the world name. - * - * @return String - */ - public String getWorld() { - return getPlot().getWorldName(); - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - @Override - public boolean isCancelled() { - return this.cancelled; - } - - @Override - public void setCancelled(boolean b) { - this.cancelled = b; - } -} +package com.github.intellectualsites.plotsquared.bukkit.events; + +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a plot is cleared + */ +public class PlotClearEvent extends PlotEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled; + + public PlotClearEvent(Plot plot) { + super(plot); + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Get the PlotId. + * + * @return PlotId + */ + public PlotId getPlotId() { + return getPlot().getId(); + } + + /** + * Get the world name. + * + * @return String + */ + public String getWorld() { + return getPlot().getWorldName(); + } + + @Override public HandlerList getHandlers() { + return handlers; + } + + @Override public boolean isCancelled() { + return this.cancelled; + } + + @Override public void setCancelled(boolean b) { + this.cancelled = b; + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotComponentSetEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotComponentSetEvent.java similarity index 79% rename from Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotComponentSetEvent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotComponentSetEvent.java index d7b33a06b..6911ccdd4 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotComponentSetEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotComponentSetEvent.java @@ -1,12 +1,11 @@ -package com.plotsquared.bukkit.events; +package com.github.intellectualsites.plotsquared.bukkit.events; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; import org.bukkit.event.HandlerList; /** * Called when a plot component is set - * */ public class PlotComponentSetEvent extends PlotEvent { @@ -49,8 +48,7 @@ public class PlotComponentSetEvent extends PlotEvent { return this.component; } - @Override - public HandlerList getHandlers() { + @Override public HandlerList getHandlers() { return handlers; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotDeleteEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotDeleteEvent.java similarity index 73% rename from Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotDeleteEvent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotDeleteEvent.java index 126b735d7..d8669279d 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotDeleteEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotDeleteEvent.java @@ -1,45 +1,43 @@ -package com.plotsquared.bukkit.events; - -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotId; -import org.bukkit.event.HandlerList; - -/** - * Called when a plot is deleted - * - */ -public class PlotDeleteEvent extends PlotEvent { - - private static final HandlerList handlers = new HandlerList(); - - public PlotDeleteEvent(Plot plot) { - super(plot); - } - - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * Get the PlotId - * - * @return PlotId - */ - public PlotId getPlotId() { - return getPlot().getId(); - } - - /** - * Get the world name - * - * @return String - */ - public String getWorld() { - return getPlot().getWorldName(); - } - - @Override - public HandlerList getHandlers() { - return handlers; - } -} +package com.github.intellectualsites.plotsquared.bukkit.events; + +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import org.bukkit.event.HandlerList; + +/** + * Called when a plot is deleted + */ +public class PlotDeleteEvent extends PlotEvent { + + private static final HandlerList handlers = new HandlerList(); + + public PlotDeleteEvent(Plot plot) { + super(plot); + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Get the PlotId + * + * @return PlotId + */ + public PlotId getPlotId() { + return getPlot().getId(); + } + + /** + * Get the world name + * + * @return String + */ + public String getWorld() { + return getPlot().getWorldName(); + } + + @Override public HandlerList getHandlers() { + return handlers; + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotEvent.java similarity index 65% rename from Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotEvent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotEvent.java index 94e2dc4cc..ae4b0c1d7 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotEvent.java @@ -1,6 +1,6 @@ -package com.plotsquared.bukkit.events; +package com.github.intellectualsites.plotsquared.bukkit.events; -import com.intellectualcrafters.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.Plot; import org.bukkit.event.Event; public abstract class PlotEvent extends Event { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagAddEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotFlagAddEvent.java similarity index 71% rename from Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagAddEvent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotFlagAddEvent.java index 3ab3fc822..e8c4ac63c 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagAddEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotFlagAddEvent.java @@ -1,56 +1,52 @@ -package com.plotsquared.bukkit.events; - -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.object.Plot; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; - -/** - * Called when a Flag is added to a plot. - * - */ -public class PlotFlagAddEvent extends PlotEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - 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 - */ - public PlotFlagAddEvent(Flag flag, Plot plot) { - super(plot); - this.flag = flag; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * Get the flag involved. - * - * @return Flag - */ - public Flag getFlag() { - return this.flag; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - @Override - public final boolean isCancelled() { - return this.cancelled; - } - - @Override - public final void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } -} +package com.github.intellectualsites.plotsquared.bukkit.events; + +import com.github.intellectualsites.plotsquared.plot.flag.Flag; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a Flag is added to a plot. + */ +public class PlotFlagAddEvent extends PlotEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + 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 + */ + public PlotFlagAddEvent(Flag flag, Plot plot) { + super(plot); + this.flag = flag; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Get the flag involved. + * + * @return Flag + */ + public Flag getFlag() { + return this.flag; + } + + @Override public HandlerList getHandlers() { + return handlers; + } + + @Override public final boolean isCancelled() { + return this.cancelled; + } + + @Override public final void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagRemoveEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotFlagRemoveEvent.java similarity index 71% rename from Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagRemoveEvent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotFlagRemoveEvent.java index 0a8e9679b..3e3e48b55 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotFlagRemoveEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotFlagRemoveEvent.java @@ -1,56 +1,52 @@ -package com.plotsquared.bukkit.events; - -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.object.Plot; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; - -/** - * Called when a flag is removed from a plot - * - */ -public class PlotFlagRemoveEvent extends PlotEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - 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 - */ - public PlotFlagRemoveEvent(Flag flag, Plot plot) { - super(plot); - this.flag = flag; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * Get the flag involved - * - * @return Flag - */ - public Flag getFlag() { - return this.flag; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - @Override - public final boolean isCancelled() { - return this.cancelled; - } - - @Override - public final void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } -} +package com.github.intellectualsites.plotsquared.bukkit.events; + +import com.github.intellectualsites.plotsquared.plot.flag.Flag; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +/** + * Called when a flag is removed from a plot + */ +public class PlotFlagRemoveEvent extends PlotEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + 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 + */ + public PlotFlagRemoveEvent(Flag flag, Plot plot) { + super(plot); + this.flag = flag; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Get the flag involved + * + * @return Flag + */ + public Flag getFlag() { + return this.flag; + } + + @Override public HandlerList getHandlers() { + return handlers; + } + + @Override public final boolean isCancelled() { + return this.cancelled; + } + + @Override public final void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotMergeEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotMergeEvent.java similarity index 76% rename from Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotMergeEvent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotMergeEvent.java index c03733ef8..20e88f90a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotMergeEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotMergeEvent.java @@ -1,62 +1,59 @@ -package com.plotsquared.bukkit.events; - -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotId; -import org.bukkit.World; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; - -import java.util.ArrayList; - -public class PlotMergeEvent extends PlotEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private final ArrayList plots; - private final World world; - private boolean cancelled; - - /** - * PlotMergeEvent: Called when plots are merged - * - * @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(World world, Plot plot, ArrayList plots) { - super(plot); - this.world = world; - this.plots = plots; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * Get the plots being added. - * - * @return Plot - */ - public ArrayList getPlots() { - return this.plots; - } - - public World getWorld() { - return this.world; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - @Override - public boolean isCancelled() { - return this.cancelled; - } - - @Override - public void setCancelled(boolean b) { - this.cancelled = b; - } -} +package com.github.intellectualsites.plotsquared.bukkit.events; + +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import org.bukkit.World; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +import java.util.ArrayList; + +public class PlotMergeEvent extends PlotEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private final ArrayList plots; + private final World world; + private boolean cancelled; + + /** + * PlotMergeEvent: Called when plots are merged + * + * @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(World world, Plot plot, ArrayList plots) { + super(plot); + this.world = world; + this.plots = plots; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Get the plots being added. + * + * @return Plot + */ + public ArrayList getPlots() { + return this.plots; + } + + public World getWorld() { + return this.world; + } + + @Override public HandlerList getHandlers() { + return handlers; + } + + @Override public boolean isCancelled() { + return this.cancelled; + } + + @Override public void setCancelled(boolean b) { + this.cancelled = b; + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotRateEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotRateEvent.java similarity index 67% rename from Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotRateEvent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotRateEvent.java index 2c7bcb230..b6ca46593 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotRateEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotRateEvent.java @@ -1,52 +1,49 @@ -package com.plotsquared.bukkit.events; - -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.Rating; -import org.bukkit.event.Cancellable; -import org.bukkit.event.HandlerList; - -public class PlotRateEvent extends PlotEvent implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private final PlotPlayer rater; - private Rating rating; - private boolean cancelled = false; - - public PlotRateEvent(PlotPlayer rater, Rating rating, Plot plot) { - super(plot); - this.rater = rater; - this.rating = rating; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - public PlotPlayer getRater() { - return this.rater; - } - - public Rating getRating() { - return this.rating; - } - - public void setRating(Rating rating) { - this.rating = rating; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - @Override - public boolean isCancelled() { - return this.cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } -} +package com.github.intellectualsites.plotsquared.bukkit.events; + +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.Rating; +import org.bukkit.event.Cancellable; +import org.bukkit.event.HandlerList; + +public class PlotRateEvent extends PlotEvent implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private final PlotPlayer rater; + private Rating rating; + private boolean cancelled = false; + + public PlotRateEvent(PlotPlayer rater, Rating rating, Plot plot) { + super(plot); + this.rater = rater; + this.rating = rating; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public PlotPlayer getRater() { + return this.rater; + } + + public Rating getRating() { + return this.rating; + } + + public void setRating(Rating rating) { + this.rating = rating; + } + + @Override public HandlerList getHandlers() { + return handlers; + } + + @Override public boolean isCancelled() { + return this.cancelled; + } + + @Override public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotUnlinkEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotUnlinkEvent.java similarity index 77% rename from Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotUnlinkEvent.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotUnlinkEvent.java index fb37b3a39..914f394fd 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/events/PlotUnlinkEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlotUnlinkEvent.java @@ -1,67 +1,64 @@ -package com.plotsquared.bukkit.events; - -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import org.bukkit.World; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -import java.util.ArrayList; - -public class PlotUnlinkEvent extends Event implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private final ArrayList plots; - private final World world; - private final PlotArea area; - 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(World world, PlotArea area, ArrayList plots) { - this.plots = plots; - this.world = world; - this.area = area; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * Get the plots involved. - * - * @return The {@link PlotId}'s of the plots involved - */ - public ArrayList getPlots() { - return this.plots; - } - - public World getWorld() { - return this.world; - } - - public PlotArea getArea() { - return this.area; - } - - @Override - public HandlerList getHandlers() { - return handlers; - } - - @Override - public boolean isCancelled() { - return this.cancelled; - } - - @Override - public void setCancelled(boolean b) { - this.cancelled = b; - } -} +package com.github.intellectualsites.plotsquared.bukkit.events; + +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import org.bukkit.World; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import java.util.ArrayList; + +public class PlotUnlinkEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private final ArrayList plots; + private final World world; + private final PlotArea area; + 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(World world, PlotArea area, ArrayList plots) { + this.plots = plots; + this.world = world; + this.area = area; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Get the plots involved. + * + * @return The {@link PlotId}'s of the plots involved + */ + public ArrayList getPlots() { + return this.plots; + } + + public World getWorld() { + return this.world; + } + + public PlotArea getArea() { + return this.area; + } + + @Override public HandlerList getHandlers() { + return handlers; + } + + @Override public boolean isCancelled() { + return this.cancelled; + } + + @Override public void setCancelled(boolean b) { + this.cancelled = b; + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java similarity index 78% rename from Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java index 231d9c51c..6022632eb 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java @@ -1,6 +1,6 @@ -package com.plotsquared.bukkit.generator; +package com.github.intellectualsites.plotsquared.bukkit.generator; -import com.intellectualcrafters.plot.generator.AugmentedUtils; +import com.github.intellectualsites.plotsquared.plot.generator.AugmentedUtils; import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.generator.BlockPopulator; @@ -8,7 +8,7 @@ import org.bukkit.generator.BlockPopulator; import java.util.Random; public class BukkitAugmentedGenerator extends BlockPopulator { - + private static BukkitAugmentedGenerator generator; public static BukkitAugmentedGenerator get(World world) { @@ -24,8 +24,7 @@ public class BukkitAugmentedGenerator extends BlockPopulator { return generator; } - @Override - public void populate(World world, Random r, Chunk chunk) { + @Override public void populate(World world, Random r, Chunk chunk) { AugmentedUtils.generate(world.getName(), chunk.getX(), chunk.getZ(), null); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitPlotGenerator.java similarity index 75% rename from Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitPlotGenerator.java index c9b7c3169..0d1128fc9 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/generator/BukkitPlotGenerator.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitPlotGenerator.java @@ -1,45 +1,36 @@ -package com.plotsquared.bukkit.generator; +package com.github.intellectualsites.plotsquared.bukkit.generator; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.generator.GeneratorWrapper; -import com.intellectualcrafters.plot.generator.IndependentPlotGenerator; -import com.intellectualcrafters.plot.object.ChunkLoc; -import com.intellectualcrafters.plot.object.ChunkWrapper; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotManager; -import com.intellectualcrafters.plot.object.PseudoRandom; -import com.intellectualcrafters.plot.object.SetupObject; -import com.intellectualcrafters.plot.object.worlds.SingleWorldGenerator; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.block.GlobalBlockQueue; -import com.intellectualcrafters.plot.util.block.LocalBlockQueue; -import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue; -import com.plotsquared.bukkit.util.BukkitUtil; -import com.plotsquared.bukkit.util.block.GenChunk; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Random; -import java.util.Set; +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil; +import com.github.intellectualsites.plotsquared.bukkit.util.block.GenChunk; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; +import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.worlds.SingleWorldGenerator; +import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue; import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.ChunkGenerator; -public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrapper { - +import java.util.*; + +public class BukkitPlotGenerator extends ChunkGenerator + implements GeneratorWrapper { + private final GenChunk chunkSetter; private final PseudoRandom random = new PseudoRandom(); private final IndependentPlotGenerator plotGenerator; - private List populators; private final ChunkGenerator platformGenerator; private final boolean full; private final HashMap dataMap = new HashMap<>(); + private List populators; private boolean loaded = false; public BukkitPlotGenerator(IndependentPlotGenerator generator) { @@ -53,12 +44,12 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap private LocalBlockQueue queue; - @Override - public void populate(World world, Random r, Chunk c) { + @Override public void populate(World world, Random r, Chunk c) { if (queue == null) { queue = GlobalBlockQueue.IMP.getNewQueue(world.getName(), false); } - byte[][] resultData = dataMap.isEmpty() ? null : dataMap.remove(new ChunkLoc(c.getX(), c.getZ())); + byte[][] resultData = + dataMap.isEmpty() ? null : dataMap.remove(new ChunkLoc(c.getX(), c.getZ())); if (resultData == null) { GenChunk result = BukkitPlotGenerator.this.chunkSetter; // Set the chunk location @@ -87,10 +78,11 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap } } BukkitPlotGenerator.this.random.state = c.getX() << 16 | c.getZ() & 0xFFFF; - PlotArea area = PS.get().getPlotArea(world.getName(), null); + PlotArea area = PlotSquared.get().getPlotArea(world.getName(), null); ChunkWrapper wrap = new ChunkWrapper(area.worldname, c.getX(), c.getZ()); ScopedLocalBlockQueue chunk = queue.getForChunk(wrap.x, wrap.z); - if (BukkitPlotGenerator.this.plotGenerator.populateChunk(chunk, area, BukkitPlotGenerator.this.random)) { + if (BukkitPlotGenerator.this.plotGenerator + .populateChunk(chunk, area, BukkitPlotGenerator.this.random)) { queue.flush(); } } @@ -99,51 +91,50 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap this.full = true; MainUtil.initCache(); } - + public BukkitPlotGenerator(final String world, final ChunkGenerator cg) { if (cg instanceof BukkitPlotGenerator) { - throw new IllegalArgumentException("ChunkGenerator: " + cg.getClass().getName() + " is already a BukkitPlotGenerator!"); + throw new IllegalArgumentException("ChunkGenerator: " + cg.getClass().getName() + + " is already a BukkitPlotGenerator!"); } this.full = false; - PS.debug("BukkitPlotGenerator does not fully support: " + cg); + PlotSquared.debug("BukkitPlotGenerator does not fully support: " + cg); this.platformGenerator = cg; this.plotGenerator = new IndependentPlotGenerator() { - @Override - public void processSetup(SetupObject setup) {} - - @Override - public void initialize(PlotArea area) {} - - @Override - public PlotManager getNewPlotManager() { - return PS.get().IMP.getDefaultGenerator().getNewPlotManager(); + @Override public void processSetup(SetupObject setup) { } - - @Override - public String getName() { + + @Override public void initialize(PlotArea area) { + } + + @Override public PlotManager getNewPlotManager() { + return PlotSquared.get().IMP.getDefaultGenerator().getNewPlotManager(); + } + + @Override public String getName() { return cg.getClass().getName(); } - + @Override public PlotArea getNewPlotArea(String world, String id, PlotId min, PlotId max) { - return PS.get().IMP.getDefaultGenerator().getNewPlotArea(world, id, min, max); + return PlotSquared.get().IMP.getDefaultGenerator() + .getNewPlotArea(world, id, min, max); } - + @Override - public void generateChunk(final ScopedLocalBlockQueue result, PlotArea settings, PseudoRandom random) { + public void generateChunk(final ScopedLocalBlockQueue result, PlotArea settings, + PseudoRandom random) { World w = BukkitUtil.getWorld(world); Location min = result.getMin(); int cx = min.getX() >> 4; int cz = min.getZ() >> 4; Random r = new Random(MathMan.pair((short) cx, (short) cz)); BiomeGrid grid = new BiomeGrid() { - @Override - public void setBiome(int x, int z, Biome biome) { + @Override public void setBiome(int x, int z, Biome biome) { result.setBiome(x, z, biome.name()); } - - @Override - public Biome getBiome(int arg0, int arg1) { + + @Override public Biome getBiome(int arg0, int arg1) { return Biome.FOREST; } }; @@ -153,7 +144,8 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap if (data != null) { return; } - } catch (Throwable ignored) {} + } catch (Throwable ignored) { + } // Populator spillage short[][] tmp = cg.generateExtBlockSections(w, r, cx, cz, grid); if (tmp != null) { @@ -187,34 +179,29 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap this.chunkSetter = new GenChunk(null, new ChunkWrapper(world, 0, 0)); MainUtil.initCache(); } - - @Override - public void augment(PlotArea area) { + + @Override public void augment(PlotArea area) { BukkitAugmentedGenerator.get(BukkitUtil.getWorld(area.worldname)); } - - @Override - public boolean isFull() { + + @Override public boolean isFull() { return this.full; } - - @Override - public IndependentPlotGenerator getPlotGenerator() { + + @Override public IndependentPlotGenerator getPlotGenerator() { return this.plotGenerator; } - - @Override - public ChunkGenerator getPlatformGenerator() { + + @Override public ChunkGenerator getPlatformGenerator() { return this.platformGenerator; } - @Override - public List getDefaultPopulators(World world) { + @Override public List getDefaultPopulators(World world) { try { if (!this.loaded) { String name = world.getName(); - PS.get().loadWorld(name, this); - Set areas = PS.get().getPlotAreas(name); + PlotSquared.get().loadWorld(name, this); + Set areas = PlotSquared.get().getPlotAreas(name); if (!areas.isEmpty()) { PlotArea area = areas.iterator().next(); if (!area.MOB_SPAWNING) { @@ -290,7 +277,7 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap // Load if improperly loaded if (!this.loaded) { String name = world.getName(); - PS.get().loadWorld(name, this); + PlotSquared.get().loadWorld(name, this); this.loaded = true; } // Set random seed @@ -299,7 +286,7 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap if (ChunkManager.preProcessChunk(result)) { return; } - PlotArea area = PS.get().getPlotArea(world.getName(), null); + PlotArea area = PlotSquared.get().getPlotArea(world.getName(), null); try { this.plotGenerator.generateChunk(this.chunkSetter, area, this.random); } catch (Throwable e) { @@ -308,9 +295,9 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap } ChunkManager.postProcessChunk(result); } - - @Override - public short[][] generateExtBlockSections(World world, Random r, int cx, int cz, BiomeGrid grid) { + + public short[][] generateExtBlockSections(World world, Random r, int cx, int cz, + BiomeGrid grid) { GenChunk result = this.chunkSetter; // Set the chunk location result.setChunk(new ChunkWrapper(world.getName(), cx, cz)); @@ -339,21 +326,20 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap // Return the result data return result.result; } - + /** * Allow spawning everywhere. + * * @param world Ignored - * @param x Ignored - * @param z Ignored + * @param x Ignored + * @param z Ignored * @return always true */ - @Override - public boolean canSpawn(World world, int x, int z) { + @Override public boolean canSpawn(World world, int x, int z) { return true; } - - @Override - public String toString() { + + @Override public String toString() { if (this.platformGenerator == this) { return this.plotGenerator.getName(); } @@ -363,9 +349,8 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap return this.platformGenerator.getClass().getName(); } } - - @Override - public boolean equals(Object obj) { + + @Override public boolean equals(Object obj) { if (obj == null) { return false; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ChunkListener.java similarity index 75% rename from Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ChunkListener.java index ca0dc871e..4fdfd28ed 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ChunkListener.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ChunkListener.java @@ -1,16 +1,14 @@ -package com.plotsquared.bukkit.listeners; +package com.github.intellectualsites.plotsquared.bukkit.listeners; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass; -import com.intellectualcrafters.plot.util.ReflectionUtils.RefField; -import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod; -import com.intellectualcrafters.plot.util.TaskManager; -import java.lang.reflect.Method; -import java.util.HashSet; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefClass; +import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefField; +import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefMethod; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Material; @@ -29,14 +27,17 @@ import org.bukkit.event.entity.ItemSpawnEvent; import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.world.ChunkUnloadEvent; +import java.lang.reflect.Method; +import java.util.HashSet; -import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; +import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass; -public class ChunkListener implements Listener { +@SuppressWarnings("unused") public class ChunkListener implements Listener { private RefMethod methodGetHandleChunk; private RefField mustSave; private Chunk lastChunk; + private boolean ignoreUnload = false; public ChunkListener() { if (Settings.Chunk_Processor.AUTO_TRIM) { @@ -46,7 +47,8 @@ public class ChunkListener implements Listener { this.mustSave = classChunk.getField("mustSave"); this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); } catch (Throwable ignored) { - PS.debug(PS.imp().getPluginName() + "/Server not compatible for chunk processor trim/gc"); + PlotSquared.debug(PlotSquared.imp().getPluginName() + + "/Server not compatible for chunk processor trim/gc"); Settings.Chunk_Processor.AUTO_TRIM = false; } } @@ -57,21 +59,23 @@ public class ChunkListener implements Listener { world.setAutoSave(false); } TaskManager.runTaskRepeat(new Runnable() { - @Override - public void run() { + @Override public void run() { try { HashSet toUnload = new HashSet<>(); for (World world : Bukkit.getWorlds()) { String worldName = world.getName(); - if (!PS.get().hasPlotArea(worldName)) { + if (!PlotSquared.get().hasPlotArea(worldName)) { continue; } Object w = world.getClass().getDeclaredMethod("getHandle").invoke(world); - Object chunkMap = w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w); - Method methodIsChunkInUse = chunkMap.getClass().getDeclaredMethod("isChunkInUse", int.class, int.class); + Object chunkMap = + w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w); + Method methodIsChunkInUse = chunkMap.getClass() + .getDeclaredMethod("isChunkInUse", int.class, int.class); Chunk[] chunks = world.getLoadedChunks(); for (Chunk chunk : chunks) { - if ((boolean) methodIsChunkInUse.invoke(chunkMap, chunk.getX(), chunk.getZ())) { + if ((boolean) methodIsChunkInUse + .invoke(chunkMap, chunk.getX(), chunk.getZ())) { continue; } int x = chunk.getX(); @@ -100,8 +104,6 @@ public class ChunkListener implements Listener { }, 1); } - private boolean ignoreUnload = false; - public boolean unloadChunk(String world, Chunk chunk, boolean safe) { if (safe && shouldSave(world, chunk.getX(), chunk.getZ())) { return false; @@ -144,15 +146,14 @@ public class ChunkListener implements Listener { return plot != null && plot.hasOwner(); } - @EventHandler - public void onChunkUnload(ChunkUnloadEvent event) { + @EventHandler public void onChunkUnload(ChunkUnloadEvent event) { if (ignoreUnload) { return; } if (Settings.Chunk_Processor.AUTO_TRIM) { Chunk chunk = event.getChunk(); String world = chunk.getWorld().getName(); - if (PS.get().hasPlotArea(world)) { + if (PlotSquared.get().hasPlotArea(world)) { if (unloadChunk(world, chunk, true)) { return; } @@ -162,14 +163,12 @@ public class ChunkListener implements Listener { event.setCancelled(true); } } - - @EventHandler - public void onChunkLoad(ChunkLoadEvent event) { + + @EventHandler public void onChunkLoad(ChunkLoadEvent event) { processChunk(event.getChunk(), false); } - - @EventHandler(priority = EventPriority.LOWEST) - public void onItemSpawn(ItemSpawnEvent event) { + + @EventHandler(priority = EventPriority.LOWEST) public void onItemSpawn(ItemSpawnEvent event) { Item entity = event.getEntity(); Chunk chunk = entity.getLocation().getChunk(); if (chunk == this.lastChunk) { @@ -177,7 +176,7 @@ public class ChunkListener implements Listener { event.setCancelled(true); return; } - if (!PS.get().hasPlotArea(chunk.getWorld().getName())) { + if (!PlotSquared.get().hasPlotArea(chunk.getWorld().getName())) { return; } Entity[] entities = chunk.getEntities(); @@ -189,14 +188,14 @@ public class ChunkListener implements Listener { this.lastChunk = null; } } - + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockPhysics(BlockPhysicsEvent event) { if (Settings.Chunk_Processor.DISABLE_PHYSICS) { event.setCancelled(true); } } - + @EventHandler(priority = EventPriority.LOWEST) public void onEntitySpawn(CreatureSpawnEvent event) { LivingEntity entity = event.getEntity(); @@ -206,7 +205,7 @@ public class ChunkListener implements Listener { event.setCancelled(true); return; } - if (!PS.get().hasPlotArea(chunk.getWorld().getName())) { + if (!PlotSquared.get().hasPlotArea(chunk.getWorld().getName())) { return; } Entity[] entities = chunk.getEntities(); @@ -223,12 +222,12 @@ public class ChunkListener implements Listener { TaskManager.index.incrementAndGet(); final Integer currentIndex = TaskManager.index.get(); Integer task = TaskManager.runTaskRepeat(new Runnable() { - @Override - public void run() { + @Override public void run() { if (!chunk.isLoaded()) { Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); TaskManager.tasks.remove(currentIndex); - PS.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); + PlotSquared + .debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); chunk.unload(true, true); return; } @@ -236,7 +235,8 @@ public class ChunkListener implements Listener { if (tiles.length == 0) { Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); TaskManager.tasks.remove(currentIndex); - PS.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); + PlotSquared + .debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); chunk.unload(true, true); return; } @@ -246,7 +246,8 @@ public class ChunkListener implements Listener { if (i >= tiles.length) { Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); TaskManager.tasks.remove(currentIndex); - PS.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); + PlotSquared + .debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); chunk.unload(true, true); return; } @@ -259,7 +260,7 @@ public class ChunkListener implements Listener { } public boolean processChunk(Chunk chunk, boolean unload) { - if (!PS.get().hasPlotArea(chunk.getWorld().getName())) { + if (!PlotSquared.get().hasPlotArea(chunk.getWorld().getName())) { return false; } Entity[] entities = chunk.getEntities(); @@ -270,11 +271,15 @@ public class ChunkListener implements Listener { ent.remove(); } } - PS.debug(C.PREFIX.s() + "&a detected unsafe chunk and processed: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4)); + PlotSquared.debug( + C.PREFIX.s() + "&a detected unsafe chunk and processed: " + (chunk.getX() << 4) + + "," + (chunk.getX() << 4)); } if (tiles.length > Settings.Chunk_Processor.MAX_TILES) { if (unload) { - PS.debug(C.PREFIX.s() + "&c detected unsafe chunk: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4)); + PlotSquared.debug( + C.PREFIX.s() + "&c detected unsafe chunk: " + (chunk.getX() << 4) + "," + ( + chunk.getX() << 4)); cleanChunk(chunk); return true; } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/EntitySpawnListener.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/EntitySpawnListener.java new file mode 100644 index 000000000..9f787297d --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/EntitySpawnListener.java @@ -0,0 +1,142 @@ +package com.github.intellectualsites.plotsquared.bukkit.listeners; + +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.flag.Flags; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import org.bukkit.World; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Vehicle; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.entity.EntitySpawnEvent; +import org.bukkit.event.entity.EntityTeleportEvent; +import org.bukkit.event.vehicle.*; +import org.bukkit.metadata.FixedMetadataValue; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; + +import java.util.List; + +@SuppressWarnings("unused") public class EntitySpawnListener implements Listener { + + private static boolean ignoreTP = false; + + public static void test(Entity entity) { + List meta = entity.getMetadata("plotworld"); + World world = entity.getLocation().getWorld(); + if (meta == null || meta.isEmpty()) { + if (PlotSquared.get().hasPlotArea(world.getName())) { + entity.setMetadata("plotworld", + new FixedMetadataValue((Plugin) PlotSquared.get().IMP, entity.getLocation())); + } + } else { + org.bukkit.Location origin = (org.bukkit.Location) meta.get(0).value(); + World originWorld = origin.getWorld(); + if (!originWorld.equals(world)) { + if (!ignoreTP) { + if (!world.getName().equalsIgnoreCase(originWorld + "_the_end")) { + try { + ignoreTP = true; + entity.teleport(origin); + } finally { + ignoreTP = false; + } + if (entity.getLocation().getWorld().equals(world)) { + entity.remove(); + } + } + } else { + entity.remove(); + } + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void creatureSpawnEvent(EntitySpawnEvent event) { + Entity entity = event.getEntity(); + Location location = BukkitUtil.getLocation(entity.getLocation()); + PlotArea area = location.getPlotArea(); + if (area == null) { + return; + } + Plot plot = area.getOwnedPlotAbs(location); + if (plot == null) { + if (!area.MOB_SPAWNING) { + EntityType type = entity.getType(); + switch (type) { + case DROPPED_ITEM: + if (Settings.Enabled_Components.KILL_ROAD_ITEMS) { + break; + } + case PLAYER: + return; + } + if (type.isAlive() || !area.MISC_SPAWN_UNOWNED) { + event.setCancelled(true); + } + } + return; + } + if (Settings.Done.RESTRICT_BUILDING && plot.hasFlag(Flags.DONE)) { + event.setCancelled(true); + } + switch (entity.getType()) { + case ENDER_CRYSTAL: + if (PlayerEvents.checkEntity(entity, plot)) { + event.setCancelled(true); + } + case SHULKER: + if (!entity.hasMetadata("plot")) { + entity.setMetadata("plot", + new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot.getId())); + } + } + } + + @EventHandler public void onVehicle(VehicleUpdateEvent event) { + test(event.getVehicle()); + } + + @EventHandler public void onVehicle(VehicleDestroyEvent event) { + test(event.getVehicle()); + } + + @EventHandler public void onVehicle(VehicleEntityCollisionEvent event) { + test(event.getVehicle()); + } + + @EventHandler public void onVehicle(VehicleCreateEvent event) { + test(event.getVehicle()); + } + + @EventHandler public void onVehicle(VehicleBlockCollisionEvent event) { + test(event.getVehicle()); + } + + @EventHandler public void onTeleport(EntityTeleportEvent event) { + Entity ent = event.getEntity(); + if (ent instanceof Vehicle || ent instanceof ArmorStand) + test(event.getEntity()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void vehicleMove(VehicleMoveEvent event) throws IllegalAccessException { + test(event.getVehicle()); + } + + @EventHandler public void spawn(CreatureSpawnEvent event) { + switch (event.getEntityType()) { + case ARMOR_STAND: + test(event.getEntity()); + } + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ForceFieldListener.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ForceFieldListener.java similarity index 70% rename from Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ForceFieldListener.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ForceFieldListener.java index 32b421a56..97d1bb7d7 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/ForceFieldListener.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ForceFieldListener.java @@ -1,98 +1,104 @@ -package com.plotsquared.bukkit.listeners; - -import com.google.common.collect.Iterables; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.Permissions; -import com.plotsquared.bukkit.object.BukkitPlayer; -import com.plotsquared.bukkit.util.BukkitUtil; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - -public class ForceFieldListener { - - private static Set getNearbyPlayers(Player player, Plot plot) { - Set players = new HashSet<>(); - for (Player nearPlayer : Iterables.filter(player.getNearbyEntities(5d, 5d, 5d),Player.class)) { - PlotPlayer plotPlayer; - if ((plotPlayer = BukkitUtil.getPlayer(nearPlayer)) == null || !plot.equals(plotPlayer.getCurrentPlot())) { - continue; - } - if (!plot.isAdded(plotPlayer.getUUID())) { - players.add(plotPlayer); - } - } - return players; - } - - private static PlotPlayer hasNearbyPermitted(Player player, Plot plot) { - for (Player nearPlayer : Iterables.filter(player.getNearbyEntities(5d, 5d, 5d),Player.class)) { - PlotPlayer plotPlayer; - if ((plotPlayer = BukkitUtil.getPlayer(nearPlayer)) == null || !plot.equals(plotPlayer.getCurrentPlot())) { - continue; - } - if (plot.isAdded(plotPlayer.getUUID())) { - return plotPlayer; - } - } - return null; - } - - private static Vector calculateVelocity(PlotPlayer player, PlotPlayer e) { - Location playerLocation = player.getLocationFull(); - Location oPlayerLocation = e.getLocation(); - double playerX = playerLocation.getX(); - double playerY = playerLocation.getY(); - double playerZ = playerLocation.getZ(); - double oPlayerX = oPlayerLocation.getX(); - double oPlayerY = oPlayerLocation.getY(); - double oPlayerZ = oPlayerLocation.getZ(); - double x = 0d; - if (playerX < oPlayerX) { - x = 1.0d; - } else if (playerX > oPlayerX) { - x = -1.0d; - } - double y = 0d; - if (playerY < oPlayerY) { - y = 0.5d; - } else if (playerY > oPlayerY) { - y = -0.5d; - } - double z = 0d; - if (playerZ < oPlayerZ) { - z = 1.0d; - } else if (playerZ > oPlayerZ) { - z = -1.0d; - } - return new Vector(x, y, z); - } - - public static void handleForcefield(Player player, PlotPlayer plotPlayer, Plot plot) { - if (Flags.FORCEFIELD.isTrue(plot)) { - UUID uuid = plotPlayer.getUUID(); - if (plot.isAdded(uuid)) { - Set players = getNearbyPlayers(player, plot); - for (PlotPlayer oPlayer : players) { - if (!Permissions.hasPermission(oPlayer, C.PERMISSION_ADMIN_ENTRY_FORCEFIELD)) { - ((BukkitPlayer) oPlayer).player.setVelocity(calculateVelocity(plotPlayer, oPlayer)); - } - } - } else { - PlotPlayer oPlayer = hasNearbyPermitted(player, plot); - if (oPlayer == null) { - return; - } - if (!Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_ENTRY_FORCEFIELD)) { - player.setVelocity(calculateVelocity(oPlayer, plotPlayer)); - } - } - } - } -} +package com.github.intellectualsites.plotsquared.bukkit.listeners; + +import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer; +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.flag.Flags; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.google.common.collect.Iterables; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +@SuppressWarnings("unused") public class ForceFieldListener { + + private static Set getNearbyPlayers(Player player, Plot plot) { + Set players = new HashSet<>(); + for (Player nearPlayer : Iterables + .filter(player.getNearbyEntities(5d, 5d, 5d), Player.class)) { + PlotPlayer plotPlayer; + if ((plotPlayer = BukkitUtil.getPlayer(nearPlayer)) == null || !plot + .equals(plotPlayer.getCurrentPlot())) { + continue; + } + if (!plot.isAdded(plotPlayer.getUUID())) { + players.add(plotPlayer); + } + } + return players; + } + + private static PlotPlayer hasNearbyPermitted(Player player, Plot plot) { + for (Player nearPlayer : Iterables + .filter(player.getNearbyEntities(5d, 5d, 5d), Player.class)) { + PlotPlayer plotPlayer; + if ((plotPlayer = BukkitUtil.getPlayer(nearPlayer)) == null || !plot + .equals(plotPlayer.getCurrentPlot())) { + continue; + } + if (plot.isAdded(plotPlayer.getUUID())) { + return plotPlayer; + } + } + return null; + } + + private static Vector calculateVelocity(PlotPlayer player, PlotPlayer e) { + Location playerLocation = player.getLocationFull(); + Location oPlayerLocation = e.getLocation(); + double playerX = playerLocation.getX(); + double playerY = playerLocation.getY(); + double playerZ = playerLocation.getZ(); + double oPlayerX = oPlayerLocation.getX(); + double oPlayerY = oPlayerLocation.getY(); + double oPlayerZ = oPlayerLocation.getZ(); + double x = 0d; + if (playerX < oPlayerX) { + x = 1.0d; + } else if (playerX > oPlayerX) { + x = -1.0d; + } + double y = 0d; + if (playerY < oPlayerY) { + y = 0.5d; + } else if (playerY > oPlayerY) { + y = -0.5d; + } + double z = 0d; + if (playerZ < oPlayerZ) { + z = 1.0d; + } else if (playerZ > oPlayerZ) { + z = -1.0d; + } + return new Vector(x, y, z); + } + + public static void handleForcefield(Player player, PlotPlayer plotPlayer, Plot plot) { + if (Flags.FORCEFIELD.isTrue(plot)) { + UUID uuid = plotPlayer.getUUID(); + if (plot.isAdded(uuid)) { + Set players = getNearbyPlayers(player, plot); + for (PlotPlayer oPlayer : players) { + if (!Permissions.hasPermission(oPlayer, C.PERMISSION_ADMIN_ENTRY_FORCEFIELD)) { + ((BukkitPlayer) oPlayer).player + .setVelocity(calculateVelocity(plotPlayer, oPlayer)); + } + } + } else { + PlotPlayer oPlayer = hasNearbyPermitted(player, plot); + if (oPlayer == null) { + return; + } + if (!Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_ENTRY_FORCEFIELD)) { + player.setVelocity(calculateVelocity(oPlayer, plotPlayer)); + } + } + } + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlayerEvents.java similarity index 72% rename from Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlayerEvents.java index 972c26dfe..97c0fb1fa 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlayerEvents.java @@ -1,32 +1,18 @@ -package com.plotsquared.bukkit.listeners; +package com.github.intellectualsites.plotsquared.bukkit.listeners; +import com.github.intellectualsites.plotsquared.bukkit.BukkitMain; +import com.github.intellectualsites.plotsquared.bukkit.object.BukkitLazyBlock; +import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer; +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.flag.Flags; +import com.github.intellectualsites.plotsquared.plot.listener.PlayerBlockEventType; +import com.github.intellectualsites.plotsquared.plot.listener.PlotListener; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.*; import com.google.common.base.Optional; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.flag.IntegerFlag; -import com.intellectualcrafters.plot.object.*; -import com.intellectualcrafters.plot.util.*; -import com.plotsquared.bukkit.BukkitMain; -import com.plotsquared.bukkit.object.BukkitLazyBlock; -import com.plotsquared.bukkit.object.BukkitPlayer; -import com.plotsquared.bukkit.util.BukkitUtil; -import com.plotsquared.bukkit.util.BukkitVersion; -import com.plotsquared.listener.PlayerBlockEventType; -import com.plotsquared.listener.PlotListener; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; -import java.util.regex.Pattern; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; @@ -34,82 +20,29 @@ import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; +import org.bukkit.block.data.BlockData; +import org.bukkit.block.data.type.Piston; import org.bukkit.command.PluginCommand; -import org.bukkit.entity.Ageable; -import org.bukkit.entity.Animals; -import org.bukkit.entity.Arrow; -import org.bukkit.entity.Creature; -import org.bukkit.entity.EnderDragon; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.FallingBlock; -import org.bukkit.entity.Fireball; -import org.bukkit.entity.Hanging; -import org.bukkit.entity.HumanEntity; -import org.bukkit.entity.ItemFrame; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Monster; -import org.bukkit.entity.Player; -import org.bukkit.entity.Projectile; -import org.bukkit.entity.TNTPrimed; -import org.bukkit.entity.Tameable; -import org.bukkit.entity.ThrownPotion; -import org.bukkit.entity.Vehicle; -import org.bukkit.entity.Villager; +import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockBurnEvent; -import org.bukkit.event.block.BlockDamageEvent; -import org.bukkit.event.block.BlockDispenseEvent; -import org.bukkit.event.block.BlockFadeEvent; -import org.bukkit.event.block.BlockFormEvent; -import org.bukkit.event.block.BlockFromToEvent; -import org.bukkit.event.block.BlockGrowEvent; -import org.bukkit.event.block.BlockIgniteEvent; -import org.bukkit.event.block.BlockPhysicsEvent; -import org.bukkit.event.block.BlockPistonExtendEvent; -import org.bukkit.event.block.BlockPistonRetractEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.block.BlockRedstoneEvent; -import org.bukkit.event.block.BlockSpreadEvent; -import org.bukkit.event.block.EntityBlockFormEvent; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.event.entity.EntityChangeBlockEvent; -import org.bukkit.event.entity.EntityCombustByEntityEvent; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.entity.EntityExplodeEvent; -import org.bukkit.event.entity.ExplosionPrimeEvent; -import org.bukkit.event.entity.PotionSplashEvent; -import org.bukkit.event.entity.ProjectileHitEvent; -import org.bukkit.event.entity.ProjectileLaunchEvent; +import org.bukkit.event.block.*; +import org.bukkit.event.entity.*; import org.bukkit.event.hanging.HangingBreakByEntityEvent; import org.bukkit.event.hanging.HangingPlaceEvent; +import org.bukkit.event.inventory.InventoryAction; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.event.player.AsyncPlayerChatEvent; -import org.bukkit.event.player.PlayerBucketEmptyEvent; -import org.bukkit.event.player.PlayerBucketFillEvent; -import org.bukkit.event.player.PlayerChangedWorldEvent; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; -import org.bukkit.event.player.PlayerEggThrowEvent; -import org.bukkit.event.player.PlayerEvent; -import org.bukkit.event.player.PlayerInteractEntityEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.player.PlayerRespawnEvent; -import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.event.player.*; import org.bukkit.event.vehicle.VehicleCreateEvent; import org.bukkit.event.vehicle.VehicleDestroyEvent; import org.bukkit.event.vehicle.VehicleMoveEvent; import org.bukkit.event.world.StructureGrowEvent; import org.bukkit.help.HelpTopic; import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; @@ -117,70 +50,229 @@ import org.bukkit.projectiles.BlockProjectileSource; import org.bukkit.projectiles.ProjectileSource; import org.bukkit.util.Vector; +import java.lang.reflect.Field; +import java.util.*; +import java.util.Map.Entry; +import java.util.regex.Pattern; + /** * Player Events involving plots. - * */ -public class PlayerEvents extends PlotListener implements Listener { +@SuppressWarnings("unused") public class PlayerEvents extends PlotListener implements Listener { private boolean pistonBlocks = true; private float lastRadius; // To prevent recursion private boolean tmpTeleport = true; + private Field fieldPlayer; + private PlayerMoveEvent moveTmp; - public static void sendBlockChange(final org.bukkit.Location bloc, final Material type, final byte data) { - TaskManager.runTaskLater(new Runnable() { - @Override - public void run() { - String world = bloc.getWorld().getName(); - int x = bloc.getBlockX(); - int z = bloc.getBlockZ(); - int distance = Bukkit.getViewDistance() * 16; - for (Entry entry : UUIDHandler.getPlayers().entrySet()) { - PlotPlayer player = entry.getValue(); - Location loc = player.getLocation(); - if (loc.getWorld().equals(world)) { - if (16 * Math.abs(loc.getX() - x) / 16 > distance || 16 * Math.abs(loc.getZ() - z) / 16 > distance) { - continue; - } - ((BukkitPlayer) player).player.sendBlockChange(bloc, type, data); + { + try { + fieldPlayer = PlayerEvent.class.getDeclaredField("player"); + fieldPlayer.setAccessible(true); + } catch (NoSuchFieldException e) { + e.printStackTrace(); + } + } + + public static void sendBlockChange(final org.bukkit.Location bloc, final BlockData data) { + TaskManager.runTaskLater(() -> { + String world = bloc.getWorld().getName(); + int x = bloc.getBlockX(); + int z = bloc.getBlockZ(); + int distance = Bukkit.getViewDistance() * 16; + for (Entry entry : UUIDHandler.getPlayers().entrySet()) { + PlotPlayer player = entry.getValue(); + Location loc = player.getLocation(); + if (loc.getWorld().equals(world)) { + if (16 * Math.abs(loc.getX() - x) / 16 > distance + || 16 * Math.abs(loc.getZ() - z) / 16 > distance) { + continue; } + ((BukkitPlayer) player).player.sendBlockChange(bloc, data); } } }, 3); } - @EventHandler - public void onRedstoneEvent(BlockRedstoneEvent event) { + public static boolean checkEntity(Entity entity, Plot plot) { + if (plot == null || !plot.hasOwner() || plot.getFlags().isEmpty() && plot + .getArea().DEFAULT_FLAGS.isEmpty()) { + return false; + } + switch (entity.getType()) { + case PLAYER: + return false; + case LLAMA_SPIT: + case SMALL_FIREBALL: + case FIREBALL: + case DROPPED_ITEM: + case EGG: + case THROWN_EXP_BOTTLE: + case SPLASH_POTION: + case LINGERING_POTION: + case SNOWBALL: + case ENDER_PEARL: + case ARROW: + case TIPPED_ARROW: + case SPECTRAL_ARROW: + case SHULKER_BULLET: + case DRAGON_FIREBALL: + // projectile + case PRIMED_TNT: + case FALLING_BLOCK: + // Block entities + case ENDER_CRYSTAL: + case COMPLEX_PART: + case FISHING_HOOK: + case ENDER_SIGNAL: + case EXPERIENCE_ORB: + case LEASH_HITCH: + case FIREWORK: + case WEATHER: + case AREA_EFFECT_CLOUD: + case LIGHTNING: + case WITHER_SKULL: + case EVOKER_FANGS: + case UNKNOWN: + // non moving / unmovable + return EntityUtil.checkEntity(plot, Flags.ENTITY_CAP); + case ITEM_FRAME: + case PAINTING: + case ARMOR_STAND: + return EntityUtil.checkEntity(plot, Flags.ENTITY_CAP, Flags.MISC_CAP); + // misc + case MINECART: + case MINECART_CHEST: + case MINECART_COMMAND: + case MINECART_FURNACE: + case MINECART_HOPPER: + case MINECART_MOB_SPAWNER: + case MINECART_TNT: + case BOAT: + return EntityUtil.checkEntity(plot, Flags.ENTITY_CAP, Flags.VEHICLE_CAP); + case POLAR_BEAR: + case RABBIT: + case SHEEP: + case MUSHROOM_COW: + case OCELOT: + case PIG: + case SQUID: + case VILLAGER: + case IRON_GOLEM: + case WOLF: + case CHICKEN: + case COW: + case SNOWMAN: + case BAT: + case HORSE: + case DONKEY: + case LLAMA: + case MULE: + case ZOMBIE_HORSE: + case SKELETON_HORSE: + // animal + return EntityUtil + .checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP, Flags.ANIMAL_CAP); + case BLAZE: + case CAVE_SPIDER: + case CREEPER: + case ENDERMAN: + case ENDERMITE: + case ENDER_DRAGON: + case GHAST: + case GIANT: + case GUARDIAN: + case MAGMA_CUBE: + case PIG_ZOMBIE: + case SILVERFISH: + case SKELETON: + case SLIME: + case SPIDER: + case WITCH: + case WITHER: + case ZOMBIE: + case SHULKER: + case HUSK: + case STRAY: + case ELDER_GUARDIAN: + case WITHER_SKELETON: + case VINDICATOR: + case EVOKER: + case VEX: + case ZOMBIE_VILLAGER: + // monster + return EntityUtil + .checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP, Flags.HOSTILE_CAP); + default: + if (entity instanceof LivingEntity) { + if (entity instanceof Animals) { + return EntityUtil + .checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP, Flags.ANIMAL_CAP); + } else if (entity instanceof Monster) { + return EntityUtil + .checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP, Flags.HOSTILE_CAP); + } else { + return EntityUtil.checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP); + } + } + if (entity instanceof Vehicle) { + return EntityUtil.checkEntity(plot, Flags.ENTITY_CAP, Flags.VEHICLE_CAP); + } + if (entity instanceof Hanging) { + return EntityUtil.checkEntity(plot, Flags.ENTITY_CAP, Flags.MISC_CAP); + } + return EntityUtil.checkEntity(plot, Flags.ENTITY_CAP); + } + } + + @EventHandler public void onRedstoneEvent(BlockRedstoneEvent event) { Block block = event.getBlock(); switch (block.getType()) { case OBSERVER: - case REDSTONE_LAMP_OFF: + case REDSTONE: + case REDSTONE_ORE: + case REDSTONE_BLOCK: + case REDSTONE_TORCH: + case REDSTONE_WALL_TORCH: case REDSTONE_WIRE: - case REDSTONE_LAMP_ON: - case PISTON_BASE: - case PISTON_STICKY_BASE: - case IRON_DOOR_BLOCK: + case REDSTONE_LAMP: + case PISTON_HEAD: + case PISTON: + case STICKY_PISTON: + case MOVING_PISTON: case LEVER: - case WOODEN_DOOR: - case FENCE_GATE: - case WOOD_BUTTON: + case ACACIA_BUTTON: + case BIRCH_BUTTON: + case DARK_OAK_BUTTON: + case JUNGLE_BUTTON: + case OAK_BUTTON: + case SPRUCE_BUTTON: case STONE_BUTTON: - case IRON_PLATE: - case WOOD_PLATE: - case STONE_PLATE: - case GOLD_PLATE: + case STONE_PRESSURE_PLATE: + case ACACIA_PRESSURE_PLATE: + case BIRCH_PRESSURE_PLATE: + case DARK_OAK_PRESSURE_PLATE: + case HEAVY_WEIGHTED_PRESSURE_PLATE: + case JUNGLE_PRESSURE_PLATE: + case LIGHT_WEIGHTED_PRESSURE_PLATE: + case OAK_PRESSURE_PLATE: + case SPRUCE_PRESSURE_PLATE: case SPRUCE_DOOR: case BIRCH_DOOR: case JUNGLE_DOOR: case ACACIA_DOOR: case DARK_OAK_DOOR: + case IRON_DOOR: + case OAK_DOOR: case IRON_TRAPDOOR: case SPRUCE_FENCE_GATE: case BIRCH_FENCE_GATE: case JUNGLE_FENCE_GATE: case ACACIA_FENCE_GATE: case DARK_OAK_FENCE_GATE: + case OAK_FENCE_GATE: case POWERED_RAIL: return; default: @@ -208,7 +300,7 @@ public class PlayerEvents extends PlotListener implements Listener { } } } else { - disable = UUIDHandler.getPlayer(plot.owner) == null; + disable = UUIDHandler.getPlayer(plot.guessOwner()) == null; } if (disable) { for (UUID trusted : plot.getTrusted()) { @@ -237,8 +329,7 @@ public class PlayerEvents extends PlotListener implements Listener { @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void onPhysicsEvent(BlockPhysicsEvent event) { switch (event.getChangedType()) { - case REDSTONE_COMPARATOR_OFF: - case REDSTONE_COMPARATOR_ON: { + case COMPARATOR: { Block block = event.getBlock(); Location loc = BukkitUtil.getLocation(block.getLocation()); PlotArea area = loc.getPlotArea(); @@ -277,8 +368,9 @@ public class PlayerEvents extends PlotListener implements Listener { if (Settings.Redstone.DETECT_INVALID_EDGE_PISTONS) { Block block = event.getBlock(); switch (block.getType()) { - case PISTON_BASE: - case PISTON_STICKY_BASE: + case PISTON: + case STICKY_PISTON: + Piston piston = (Piston) block.getBlockData(); Location loc = BukkitUtil.getLocation(block.getLocation()); PlotArea area = loc.getPlotArea(); if (area == null) { @@ -288,22 +380,17 @@ public class PlayerEvents extends PlotListener implements Listener { if (plot == null) { return; } - int data = block.getData(); - switch (data) { - case 5: - case 13: + switch (piston.getFacing()) { + case EAST: loc.setX(loc.getX() + 1); break; - case 4: - case 12: + case SOUTH: loc.setX(loc.getX() - 1); break; - case 3: - case 11: + case WEST: loc.setZ(loc.getZ() + 1); break; - case 2: - case 10: + case NORTH: loc.setZ(loc.getZ() - 1); break; } @@ -312,14 +399,13 @@ public class PlayerEvents extends PlotListener implements Listener { event.setCancelled(true); return; } + } } - } - break; + break; } } - @EventHandler - public void onProjectileLaunch(ProjectileLaunchEvent event) { + @EventHandler public void onProjectileLaunch(ProjectileLaunchEvent event) { Projectile entity = event.getEntity(); if (!(entity instanceof ThrownPotion)) { return; @@ -329,7 +415,7 @@ public class PlayerEvents extends PlotListener implements Listener { return; } Location l = BukkitUtil.getLocation(entity); - if (!PS.get().hasPlotArea(l.getWorld())) { + if (!PlotSquared.get().hasPlotArea(l.getWorld())) { return; } PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter); @@ -340,11 +426,10 @@ public class PlayerEvents extends PlotListener implements Listener { } } - @EventHandler - public boolean onProjectileHit(ProjectileHitEvent event) { + @EventHandler public boolean onProjectileHit(ProjectileHitEvent event) { Projectile entity = event.getEntity(); Location loc = BukkitUtil.getLocation(entity); - if (!PS.get().hasPlotArea(loc.getWorld())) { + if (!PlotSquared.get().hasPlotArea(loc.getWorld())) { return true; } PlotArea area = loc.getPlotArea(); @@ -362,7 +447,8 @@ public class PlayerEvents extends PlotListener implements Listener { } return true; } - if (plot.isAdded(pp.getUUID()) || Permissions.hasPermission(pp, C.PERMISSION_PROJECTILE_OTHER)) { + if (plot.isAdded(pp.getUUID()) || Permissions + .hasPermission(pp, C.PERMISSION_PROJECTILE_OTHER)) { return true; } entity.remove(); @@ -373,7 +459,8 @@ public class PlayerEvents extends PlotListener implements Listener { entity.remove(); return false; } - Location sLoc = BukkitUtil.getLocation(((BlockProjectileSource) shooter).getBlock().getLocation()); + Location sLoc = + BukkitUtil.getLocation(((BlockProjectileSource) shooter).getBlock().getLocation()); if (!area.contains(sLoc.getX(), sLoc.getZ())) { entity.remove(); return false; @@ -402,13 +489,14 @@ public class PlayerEvents extends PlotListener implements Listener { } String[] parts = msg.split(" "); Plot plot = pp.getCurrentPlot(); - if (BukkitMain.worldEdit != null) { // Check WorldEdit + if (BukkitMain.getWorldEdit() != null) { // Check WorldEdit switch (parts[0].toLowerCase()) { case "up": case "/up": case "worldedit:up": case "worldedit:/up": - if (plot == null || (!plot.isAdded(pp.getUUID()) && !Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER, true))) { + if (plot == null || (!plot.isAdded(pp.getUUID()) && !Permissions + .hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER, true))) { event.setCancelled(true); return; } @@ -418,7 +506,8 @@ public class PlayerEvents extends PlotListener implements Listener { return; } Optional> flag = plot.getFlag(Flags.BLOCKED_CMDS); - if (flag.isPresent() && !Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_BLOCKED_CMDS)) { + if (flag.isPresent() && !Permissions + .hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_BLOCKED_CMDS)) { List blocked_cmds = flag.get(); String c = parts[0]; if (parts[0].contains(":")) { @@ -501,8 +590,7 @@ public class PlayerEvents extends PlotListener implements Listener { // Async TaskManager.runTaskLaterAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { if (!player.hasPlayedBefore() && player.isOnline()) { player.saveData(); } @@ -520,15 +608,16 @@ public class PlayerEvents extends PlotListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onTeleport(PlayerTeleportEvent event) { - if (event.getTo() == null || event.getFrom() == null || !event.getFrom().getWorld().equals(event.getTo().getWorld())) { - BukkitUtil.getPlayer(event.getPlayer()).deleteMeta("location"); - BukkitUtil.getPlayer(event.getPlayer()).deleteMeta("lastplot"); + if (event.getTo() == null || event.getFrom() == null || !event.getFrom().getWorld() + .equals(event.getTo().getWorld())) { + BukkitUtil.getPlayer(event.getPlayer()).deleteMeta(PlotPlayer.META_LOCATION); + BukkitUtil.getPlayer(event.getPlayer()).deleteMeta(PlotPlayer.META_LAST_PLOT); org.bukkit.Location to = event.getTo(); if (to != null) { Player player = event.getPlayer(); PlotPlayer pp = PlotPlayer.wrap(player); Location loc = BukkitUtil.getLocation(to); - PlotArea area = PS.get().getPlotAreaAbs(loc); + PlotArea area = PlotSquared.get().getPlotAreaAbs(loc); if (area == null) { return; } @@ -542,50 +631,39 @@ public class PlayerEvents extends PlotListener implements Listener { playerMove(event); } - private Field fieldPlayer; - { - try { - fieldPlayer = PlayerEvent.class.getDeclaredField("player"); - fieldPlayer.setAccessible(true); - } catch (NoSuchFieldException e) { - e.printStackTrace(); - } - } - private PlayerMoveEvent moveTmp; - private boolean v112 = PS.get().checkVersion(PS.imp().getServerVersion(), BukkitVersion.v1_12_0); - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void vehicleMove(VehicleMoveEvent event) throws IllegalAccessException { final org.bukkit.Location from = event.getFrom(); final org.bukkit.Location to = event.getTo(); int toX, toZ; - if ((toX = MathMan.roundInt(to.getX())) != MathMan.roundInt(from.getX()) | (toZ = MathMan.roundInt(to.getZ())) != MathMan.roundInt(from.getZ())) { + if ((toX = MathMan.roundInt(to.getX())) != MathMan.roundInt(from.getX()) + | (toZ = MathMan.roundInt(to.getZ())) != MathMan.roundInt(from.getZ())) { Vehicle vehicle = event.getVehicle(); // Check allowed - Entity passenger = vehicle.getPassenger(); + Entity passenger = vehicle.getPassengers().get(1); if (passenger instanceof Player) { final Player player = (Player) passenger; // reset - if (moveTmp == null) moveTmp = new PlayerMoveEvent(null, from, to); + if (moveTmp == null) + moveTmp = new PlayerMoveEvent(null, from, to); moveTmp.setFrom(from); moveTmp.setTo(to); moveTmp.setCancelled(false); fieldPlayer.set(moveTmp, player); - List passengers; - if (v112) passengers = vehicle.getPassengers(); - else passengers = null; + List passengers = vehicle.getPassengers(); this.playerMove(moveTmp); org.bukkit.Location dest; if (moveTmp.isCancelled()) { dest = from; - } else if (MathMan.roundInt(moveTmp.getTo().getX()) != toX || MathMan.roundInt(moveTmp.getTo().getZ()) != toZ) { + } else if (MathMan.roundInt(moveTmp.getTo().getX()) != toX + || MathMan.roundInt(moveTmp.getTo().getZ()) != toZ) { dest = to; } else { dest = null; @@ -595,7 +673,7 @@ public class PlayerEvents extends PlotListener implements Listener { vehicle.eject(); vehicle.setVelocity(new Vector(0d, 0d, 0d)); vehicle.teleport(dest); - for (final Entity entity : passengers) vehicle.addPassenger(entity); + passengers.forEach(vehicle::addPassenger); } else { vehicle.eject(); vehicle.setVelocity(new Vector(0d, 0d, 0d)); @@ -624,7 +702,8 @@ public class PlayerEvents extends PlotListener implements Listener { vehicle.remove(); } } else if (toPlot != null) { - vehicle.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, toPlot)); + vehicle.setMetadata("plot", + new FixedMetadataValue((Plugin) PlotSquared.get().IMP, toPlot)); } } } @@ -644,14 +723,14 @@ public class PlayerEvents extends PlotListener implements Listener { TaskManager.TELEPORT_QUEUE.remove(pp.getName()); // Set last location Location loc = BukkitUtil.getLocation(to); - pp.setMeta("location", loc); + pp.setMeta(PlotPlayer.META_LOCATION, loc); PlotArea area = loc.getPlotArea(); if (area == null) { - pp.deleteMeta("lastplot"); + pp.deleteMeta(PlotPlayer.META_LAST_PLOT); return; } Plot now = area.getPlot(loc); - Plot lastPlot = pp.getMeta("lastplot"); + Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT); if (now == null) { if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); @@ -705,14 +784,14 @@ public class PlayerEvents extends PlotListener implements Listener { TaskManager.TELEPORT_QUEUE.remove(pp.getName()); // Set last location Location loc = BukkitUtil.getLocation(to); - pp.setMeta("location", loc); + pp.setMeta(PlotPlayer.META_LOCATION, loc); PlotArea area = loc.getPlotArea(); if (area == null) { - pp.deleteMeta("lastplot"); + pp.deleteMeta(PlotPlayer.META_LAST_PLOT); return; } Plot now = area.getPlot(loc); - Plot lastPlot = pp.getMeta("lastplot"); + Plot lastPlot = pp.getMeta(PlotPlayer.META_LAST_PLOT); if (now == null) { if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport) { MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); @@ -757,8 +836,7 @@ public class PlayerEvents extends PlotListener implements Listener { } } - @EventHandler(priority = EventPriority.LOW) - public void onChat(AsyncPlayerChatEvent event) { + @EventHandler(priority = EventPriority.LOW) public void onChat(AsyncPlayerChatEvent event) { if (event.isCancelled()) return; @@ -791,7 +869,8 @@ public class PlayerEvents extends PlotListener implements Listener { } } } - String partial = ChatColor.translateAlternateColorCodes('&',format.replace("%plot_id%", id.x + ";" + id.y).replace("%sender%", sender)); + String partial = ChatColor.translateAlternateColorCodes('&', + format.replace("%plot_id%", id.x + ";" + id.y).replace("%sender%", sender)); if (plotPlayer.hasPermission("plots.chat.color")) { message = C.color(message); } @@ -800,16 +879,16 @@ public class PlayerEvents extends PlotListener implements Listener { receiver.sendMessage(full); } if (!spies.isEmpty()) { - String spyMessage = C.PLOT_CHAT_SPY_FORMAT.s().replace("%plot_id%", id.x + ";" + id.y).replace("%sender%", sender).replace("%msg%", message); + String spyMessage = C.PLOT_CHAT_SPY_FORMAT.s().replace("%plot_id%", id.x + ";" + id.y) + .replace("%sender%", sender).replace("%msg%", message); for (Player player : spies) { player.sendMessage(spyMessage); } } - PS.debug(full); + PlotSquared.debug(full); } - @EventHandler(priority = EventPriority.LOWEST) - public void blockDestroy(BlockBreakEvent event) { + @EventHandler(priority = EventPriority.LOWEST) public void blockDestroy(BlockBreakEvent event) { Player player = event.getPlayer(); Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); PlotArea area = location.getPlotArea(); @@ -820,21 +899,27 @@ public class PlayerEvents extends PlotListener implements Listener { if (plot != null) { PlotPlayer plotPlayer = BukkitUtil.getPlayer(player); if (event.getBlock().getY() == 0) { - if (!Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_DESTROY_GROUNDLEVEL)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_GROUNDLEVEL); + if (!Permissions + .hasPermission(plotPlayer, C.PERMISSION_ADMIN_DESTROY_GROUNDLEVEL)) { + MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, + C.PERMISSION_ADMIN_DESTROY_GROUNDLEVEL); event.setCancelled(true); return; } - } else if ((location.getY() > area.MAX_BUILD_HEIGHT || location.getY() < area.MIN_BUILD_HEIGHT) && !Permissions + } else if ( + (location.getY() > area.MAX_BUILD_HEIGHT || location.getY() < area.MIN_BUILD_HEIGHT) + && !Permissions .hasPermission(plotPlayer, C.PERMISSION_ADMIN_BUILD_HEIGHTLIMIT)) { event.setCancelled(true); - MainUtil.sendMessage(plotPlayer, C.HEIGHT_LIMIT.s().replace("{limit}", String.valueOf(area.MAX_BUILD_HEIGHT))); + MainUtil.sendMessage(plotPlayer, + C.HEIGHT_LIMIT.s().replace("{limit}", String.valueOf(area.MAX_BUILD_HEIGHT))); } if (!plot.hasOwner()) { if (Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { return; } - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_UNOWNED); + MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, + C.PERMISSION_ADMIN_DESTROY_UNOWNED); event.setCancelled(true); return; } @@ -842,17 +927,19 @@ public class PlayerEvents extends PlotListener implements Listener { Optional> destroy = plot.getFlag(Flags.BREAK); Block block = event.getBlock(); if (destroy.isPresent() && destroy.get() - .contains(PlotBlock.get((short) block.getTypeId(), block.getData()))) { + .contains(PlotBlock.get(block.getType().name()))) { return; } if (Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_DESTROY_OTHER)) { return; } - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER); + MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, + C.PERMISSION_ADMIN_DESTROY_OTHER); event.setCancelled(true); } else if (Settings.Done.RESTRICT_BUILDING && plot.getFlags().containsKey(Flags.DONE)) { if (!Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, + C.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); return; } @@ -863,8 +950,9 @@ public class PlayerEvents extends PlotListener implements Listener { if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD)) { return; } - if (PS.get().worldedit != null && pp.getAttribute("worldedit")) { - if (player.getItemInHand().getTypeId() == PS.get().worldedit.getConfiguration().wandItem) { + if (PlotSquared.get().worldedit != null && pp.getAttribute("worldedit")) { + if (player.getInventory().getItemInMainHand().getType() == Material + .getMaterial(PlotSquared.get().worldedit.getConfiguration().wandItem)) { return; } } @@ -877,7 +965,7 @@ public class PlayerEvents extends PlotListener implements Listener { Location location = BukkitUtil.getLocation(event.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { - if (!PS.get().hasPlotArea(location.getWorld())) { + if (!PlotSquared.get().hasPlotArea(location.getWorld())) { return; } Iterator iterator = event.blockList().iterator(); @@ -900,11 +988,14 @@ public class PlayerEvents extends PlotListener implements Listener { origin = (Plot) meta.get(0).value(); } if (this.lastRadius != 0) { - List nearby = event.getEntity().getNearbyEntities(this.lastRadius, this.lastRadius, this.lastRadius); + List nearby = event.getEntity() + .getNearbyEntities(this.lastRadius, this.lastRadius, this.lastRadius); for (Entity near : nearby) { - if (near instanceof TNTPrimed || near.getType().equals(EntityType.MINECART_TNT)) { + if (near instanceof TNTPrimed || near.getType() + .equals(EntityType.MINECART_TNT)) { if (!near.hasMetadata("plot")) { - near.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot)); + near.setMetadata("plot", + new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot)); } } } @@ -914,7 +1005,8 @@ public class PlayerEvents extends PlotListener implements Listener { while (iterator.hasNext()) { Block block = iterator.next(); location = BukkitUtil.getLocation(block.getLocation()); - if (!area.contains(location.getX(), location.getZ()) || !origin.equals(area.getOwnedPlot(location))) { + if (!area.contains(location.getX(), location.getZ()) || !origin + .equals(area.getOwnedPlot(location))) { iterator.remove(); } } @@ -929,12 +1021,12 @@ public class PlayerEvents extends PlotListener implements Listener { Player player = event.getPlayer(); PlotPlayer pp = BukkitUtil.getPlayer(player); // Delete last location - pp.deleteMeta("location"); - Plot plot = (Plot) pp.deleteMeta("lastplot"); + pp.deleteMeta(PlotPlayer.META_LOCATION); + Plot plot = (Plot) pp.deleteMeta(PlotPlayer.META_LAST_PLOT); if (plot != null) { plotExit(pp, plot); } - if (PS.get().worldedit != null) { + if (PlotSquared.get().worldedit != null) { if (!Permissions.hasPermission(pp, C.PERMISSION_WORLDEDIT_BYPASS)) { if (pp.getAttribute("worldedit")) { pp.removeAttribute("worldedit"); @@ -945,7 +1037,7 @@ public class PlayerEvents extends PlotListener implements Listener { pp.deleteMeta("perm"); } Location loc = pp.getLocation(); - PlotArea area = PS.get().getPlotAreaAbs(loc); + PlotArea area = PlotSquared.get().getPlotAreaAbs(loc); if (area == null) { return; } @@ -963,7 +1055,8 @@ public class PlayerEvents extends PlotListener implements Listener { PlotArea area = location.getPlotArea(); if (area != null) { Plot plot = area.getOwnedPlot(location); - if (plot != null && Flags.MOB_BREAK.isTrue(plot)) return; + if (plot != null && Flags.MOB_BREAK.isTrue(plot)) + return; event.setCancelled(true); } } @@ -972,7 +1065,7 @@ public class PlayerEvents extends PlotListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntityBlockForm(EntityBlockFormEvent event) { String world = event.getBlock().getWorld().getName(); - if (!PS.get().hasPlotArea(world)) { + if (!PlotSquared.get().hasPlotArea(world)) { return; } Location location = BukkitUtil.getLocation(event.getBlock().getLocation()); @@ -1033,7 +1126,7 @@ public class PlayerEvents extends PlotListener implements Listener { event.setCancelled(true); } break; - case MYCEL: + case MYCELIUM: if (Flags.MYCEL_GROW.isFalse(plot)) { event.setCancelled(true); } @@ -1116,8 +1209,9 @@ public class PlayerEvents extends PlotListener implements Listener { if (!plot.isAdded(plotPlayer.getUUID())) { Optional> destroy = plot.getFlag(Flags.BREAK); Block block = event.getBlock(); - if (destroy.isPresent() && destroy.get().contains(PlotBlock.get((short) block.getTypeId(), block.getData())) || Permissions - .hasPermission(plotPlayer, C.PERMISSION_ADMIN_DESTROY_OTHER)) { + if (destroy.isPresent() && destroy.get() + .contains(PlotBlock.get(block.getType().name())) || Permissions + .hasPermission(plotPlayer, C.PERMISSION_ADMIN_DESTROY_OTHER)) { return; } event.setCancelled(true); @@ -1156,7 +1250,7 @@ public class PlayerEvents extends PlotListener implements Listener { event.setCancelled(true); } break; - case SOIL: + case FARMLAND: if (Flags.SOIL_DRY.isFalse(plot)) { event.setCancelled(true); } @@ -1179,20 +1273,20 @@ public class PlayerEvents extends PlotListener implements Listener { if (Flags.DISABLE_PHYSICS.isFalse(plot)) { event.setCancelled(true); return; - } else if (!area.contains(fLocation.getX(), fLocation.getZ()) || !Objects.equals(plot, area.getOwnedPlot(fLocation))) { + } else if (!area.contains(fLocation.getX(), fLocation.getZ()) || !Objects + .equals(plot, area.getOwnedPlot(fLocation))) { event.setCancelled(true); return; } if (Flags.LIQUID_FLOW.isFalse(plot)) { switch (to.getType()) { case WATER: - case STATIONARY_WATER: case LAVA: - case STATIONARY_LAVA: event.setCancelled(true); } } - } else if (!area.contains(fLocation.getX(), fLocation.getZ()) || !Objects.equals(plot, area.getOwnedPlot(fLocation))) { + } else if (!area.contains(fLocation.getX(), fLocation.getZ()) || !Objects + .equals(null, area.getOwnedPlot(fLocation))) { event.setCancelled(true); } } @@ -1214,7 +1308,7 @@ public class PlayerEvents extends PlotListener implements Listener { Vector relative = new Vector(face.getModX(), face.getModY(), face.getModZ()); PlotArea area = location.getPlotArea(); if (area == null) { - if (!PS.get().hasPlotArea(location.getWorld())) { + if (!PlotSquared.get().hasPlotArea(location.getWorld())) { return; } for (Block b : event.getBlocks()) { @@ -1233,11 +1327,13 @@ public class PlayerEvents extends PlotListener implements Listener { List blocks = event.getBlocks(); for (Block b : blocks) { Location bloc = BukkitUtil.getLocation(b.getLocation()); - if (!area.contains(bloc.getX(), bloc.getZ()) || !area.contains(bloc.getX() + relative.getBlockX(), bloc.getZ() + relative.getBlockZ())) { + if (!area.contains(bloc.getX(), bloc.getZ()) || !area + .contains(bloc.getX() + relative.getBlockX(), bloc.getZ() + relative.getBlockZ())) { event.setCancelled(true); return; } - if (!plot.equals(area.getOwnedPlot(bloc)) || !plot.equals(area.getOwnedPlot(bloc.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) { + if (!plot.equals(area.getOwnedPlot(bloc)) || !plot.equals(area.getOwnedPlot( + bloc.add(relative.getBlockX(), relative.getBlockY(), relative.getBlockZ())))) { event.setCancelled(true); return; } @@ -1250,7 +1346,7 @@ public class PlayerEvents extends PlotListener implements Listener { Location location = BukkitUtil.getLocation(block.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { - if (!PS.get().hasPlotArea(location.getWorld())) { + if (!PlotSquared.get().hasPlotArea(location.getWorld())) { return; } if (this.pistonBlocks) { @@ -1266,9 +1362,10 @@ public class PlayerEvents extends PlotListener implements Listener { this.pistonBlocks = false; } } - if (!this.pistonBlocks && block.getType() != Material.PISTON_BASE) { + if (!this.pistonBlocks && !block.getType().toString().contains("PISTON")) { BlockFace dir = event.getDirection(); - location = BukkitUtil.getLocation(block.getLocation().add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); + location = BukkitUtil.getLocation(block.getLocation() + .add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); if (location.getPlotArea() != null) { event.setCancelled(true); return; @@ -1278,17 +1375,18 @@ public class PlayerEvents extends PlotListener implements Listener { } Plot plot = area.getOwnedPlot(location); BlockFace dir = event.getDirection(); -// Location head = location.add(-dir.getModX(), -dir.getModY(), -dir.getModZ()); -// -// if (!Objects.equals(plot, area.getOwnedPlot(head))) { -// // FIXME: cancelling the event doesn't work here. See issue #1484 -// event.setCancelled(true); -// return; -// } + // Location head = location.add(-dir.getModX(), -dir.getModY(), -dir.getModZ()); + // + // if (!Objects.equals(plot, area.getOwnedPlot(head))) { + // // FIXME: cancelling the event doesn't work here. See issue #1484 + // event.setCancelled(true); + // return; + // } if (this.pistonBlocks) { try { for (Block pulled : event.getBlocks()) { - Location from = BukkitUtil.getLocation(pulled.getLocation().add(dir.getModX(), dir.getModY(), dir.getModZ())); + Location from = BukkitUtil.getLocation( + pulled.getLocation().add(dir.getModX(), dir.getModY(), dir.getModZ())); Location to = BukkitUtil.getLocation(pulled.getLocation()); if (!area.contains(to.getX(), to.getZ())) { event.setCancelled(true); @@ -1305,8 +1403,9 @@ public class PlayerEvents extends PlotListener implements Listener { this.pistonBlocks = false; } } - if (!this.pistonBlocks && block.getType() != Material.PISTON_BASE) { - location = BukkitUtil.getLocation(block.getLocation().add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); + if (!this.pistonBlocks && !block.getType().toString().contains("PISTON")) { + location = BukkitUtil.getLocation( + block.getLocation().add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); if (!area.contains(location)) { event.setCancelled(true); return; @@ -1324,19 +1423,23 @@ public class PlayerEvents extends PlotListener implements Listener { switch (type) { case WATER_BUCKET: case LAVA_BUCKET: { - if (event.getBlock().getType() == Material.DROPPER) return; - BlockFace targetFace = ((org.bukkit.material.Dispenser) event.getBlock().getState().getData()).getFacing(); - Location location = BukkitUtil.getLocation(event.getBlock().getRelative(targetFace).getLocation()); + if (event.getBlock().getType() == Material.DROPPER) + return; + BlockFace targetFace = + ((org.bukkit.material.Dispenser) event.getBlock().getState().getData()) + .getFacing(); + Location location = + BukkitUtil.getLocation(event.getBlock().getRelative(targetFace).getLocation()); if (location.isPlotRoad()) { event.setCancelled(true); } } - } + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onStructureGrow(StructureGrowEvent event) { - if (!PS.get().hasPlotArea(event.getWorld().getName())) { + if (!PlotSquared.get().hasPlotArea(event.getWorld().getName())) { return; } List blocks = event.getBlocks(); @@ -1391,6 +1494,203 @@ public class PlayerEvents extends PlotListener implements Listener { } } + @SuppressWarnings("deprecation") + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onInventoryClick(InventoryClickEvent event) { + if (!event.isLeftClick() || (event.getAction() != InventoryAction.PLACE_ALL) || event + .isShiftClick()) { + return; + } + HumanEntity entity = event.getWhoClicked(); + if (!(entity instanceof Player) || !PlotSquared.get() + .hasPlotArea(entity.getWorld().getName())) { + return; + } + + HumanEntity clicker = event.getWhoClicked(); + if (!(clicker instanceof Player)) { + return; + } + Player player = (Player) clicker; + PlotPlayer pp = BukkitUtil.getPlayer(player); + PlotInventory inventory = pp.getMeta("inventory"); + if (inventory != null && event.getRawSlot() == event.getSlot()) { + if (!inventory.onClick(event.getSlot())) { + event.setCancelled(true); + inventory.close(); + } + } + PlayerInventory inv = player.getInventory(); + int slot = inv.getHeldItemSlot(); + if ((slot > 8) || !event.getEventName().equals("InventoryCreativeEvent")) { + return; + } + ItemStack current = inv.getItemInHand(); + ItemStack newItem = event.getCursor(); + ItemMeta newMeta = newItem.getItemMeta(); + ItemMeta oldMeta = newItem.getItemMeta(); + String newLore = ""; + if (newMeta != null) { + List lore = newMeta.getLore(); + if (lore != null) { + newLore = lore.toString(); + } + } + String oldLore = ""; + if (oldMeta != null) { + List lore = oldMeta.getLore(); + if (lore != null) { + oldLore = lore.toString(); + } + } + if (!"[(+NBT)]".equals(newLore) || (current.equals(newItem) && newLore.equals(oldLore))) { + switch (newItem.getType()) { + case LEGACY_BANNER: + case PLAYER_HEAD: + if (newMeta != null) + break; + default: + return; + } + } + Block block = player.getTargetBlock(null, 7); + BlockState state = block.getState(); + if (state == null) { + return; + } + Material stateType = state.getType(); + Material itemType = newItem.getType(); + if (stateType != itemType) { + switch (stateType) { + case LEGACY_STANDING_BANNER: + case LEGACY_WALL_BANNER: + if (itemType == Material.LEGACY_BANNER) + break; + case LEGACY_SKULL: + if (itemType == Material.LEGACY_SKULL_ITEM) + break; + default: + return; + } + } + Location l = BukkitUtil.getLocation(state.getLocation()); + PlotArea area = l.getPlotArea(); + if (area == null) { + return; + } + Plot plot = area.getPlotAbs(l); + boolean cancelled = false; + if (plot == null) { + 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")) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.unowned"); + cancelled = true; + } + } else { + UUID uuid = pp.getUUID(); + 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.getType() == newItem.getType()) && (current.getDurability() == newItem + .getDurability())) { + event.setCursor( + new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability())); + event.setCancelled(true); + return; + } + event.setCursor( + new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability())); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPotionSplash(LingeringPotionSplashEvent event) { + LingeringPotion entity = event.getEntity(); + Location l = BukkitUtil.getLocation(entity); + if (!PlotSquared.get().hasPlotArea(l.getWorld())) { + return; + } + if (!this.onProjectileHit(event)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onInteract(PlayerInteractAtEntityEvent e) { + Entity entity = e.getRightClicked(); + if (!(entity instanceof ArmorStand)) { + return; + } + Location l = BukkitUtil.getLocation(e.getRightClicked().getLocation()); + PlotArea area = l.getPlotArea(); + if (area == null) { + return; + } + + EntitySpawnListener.test(entity); + + Plot plot = area.getPlotAbs(l); + PlotPlayer pp = BukkitUtil.getPlayer(e.getPlayer()); + if (plot == null) { + 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")) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.unowned"); + e.setCancelled(true); + } + } else { + UUID uuid = pp.getUUID(); + if (!plot.isAdded(uuid)) { + if (Flags.MISC_INTERACT.isTrue(plot)) { + return; + } + if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) { + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.other"); + e.setCancelled(true); + } + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBigBoom(BlockExplodeEvent event) { + Block block = event.getBlock(); + Location location = BukkitUtil.getLocation(block.getLocation()); + String world = location.getWorld(); + if (!PlotSquared.get().hasPlotArea(world)) { + return; + } + PlotArea area = location.getPlotArea(); + if (area == null) { + Iterator iterator = event.blockList().iterator(); + while (iterator.hasNext()) { + location = BukkitUtil.getLocation(iterator.next().getLocation()); + if (location.getPlotArea() != null) { + iterator.remove(); + } + } + return; + } + Plot plot = area.getOwnedPlot(location); + if (plot == null || !plot.getFlag(Flags.EXPLOSION).or(false)) { + event.setCancelled(true); + } + event.blockList().removeIf( + b -> !plot.equals(area.getOwnedPlot(BukkitUtil.getLocation(b.getLocation())))); + } + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onInteract(PlayerInteractEvent event) { Player player = event.getPlayer(); @@ -1415,7 +1715,8 @@ public class PlayerEvents extends PlotListener implements Listener { Block block = event.getClickedBlock(); location = BukkitUtil.getLocation(block.getLocation()); Material blockType = block.getType(); - int blockId = blockType.getId(); + int blockId = ((LegacyPlotBlock) PlotSquared.get().IMP.getLegacyMappings() + .fromStringToLegacy(blockType.name())).id; switch (blockType) { case ANVIL: case ACACIA_DOOR: @@ -1424,48 +1725,98 @@ public class PlayerEvents extends PlotListener implements Listener { case IRON_DOOR: case JUNGLE_DOOR: case SPRUCE_DOOR: - case TRAP_DOOR: + case OAK_DOOR: + case ACACIA_TRAPDOOR: + case BIRCH_TRAPDOOR: + case DARK_OAK_TRAPDOOR: + case JUNGLE_TRAPDOOR: + case OAK_TRAPDOOR: + case SPRUCE_TRAPDOOR: case IRON_TRAPDOOR: - case WOOD_DOOR: - case WOODEN_DOOR: case TRAPPED_CHEST: case ENDER_CHEST: case CHEST: case ACACIA_FENCE_GATE: case BIRCH_FENCE_GATE: case DARK_OAK_FENCE_GATE: - case FENCE_GATE: + case OAK_FENCE_GATE: case JUNGLE_FENCE_GATE: case SPRUCE_FENCE_GATE: case LEVER: - case DIODE: - case DIODE_BLOCK_OFF: - case DIODE_BLOCK_ON: - case COMMAND: - case REDSTONE_COMPARATOR: - case REDSTONE_COMPARATOR_OFF: - case REDSTONE_COMPARATOR_ON: + case REDSTONE_TORCH: + case REDSTONE_WALL_TORCH: + case COMMAND_BLOCK: + case COMPARATOR: case REDSTONE_ORE: - case WOOD_BUTTON: + case BIRCH_BUTTON: + case DARK_OAK_BUTTON: + case JUNGLE_BUTTON: + case ACACIA_BUTTON: + case OAK_BUTTON: + case SPRUCE_BUTTON: case STONE_BUTTON: case BEACON: - case BED_BLOCK: + case BLACK_BED: + case BLUE_BED: + case BROWN_BED: + case CYAN_BED: + case GRAY_BED: + case GREEN_BED: + case LIGHT_BLUE_BED: + case LIGHT_GRAY_BED: + case LIME_BED: + case MAGENTA_BED: + case ORANGE_BED: + case PINK_BED: + case PURPLE_BED: + case RED_BED: + case WHITE_BED: + case YELLOW_BED: case SIGN: case WALL_SIGN: - case SIGN_POST: - case ENCHANTMENT_TABLE: + case ENCHANTING_TABLE: case BREWING_STAND: - case STANDING_BANNER: - case BURNING_FURNACE: + case BLACK_BANNER: + case BLACK_WALL_BANNER: + case BLUE_BANNER: + case BLUE_WALL_BANNER: + case BROWN_BANNER: + case BROWN_WALL_BANNER: + case CYAN_BANNER: + case CYAN_WALL_BANNER: + case GRAY_BANNER: + case GRAY_WALL_BANNER: + case GREEN_BANNER: + case GREEN_WALL_BANNER: + case LIGHT_BLUE_BANNER: + case LIGHT_BLUE_WALL_BANNER: + case LIGHT_GRAY_BANNER: + case LIGHT_GRAY_WALL_BANNER: + case LIME_BANNER: + case LIME_WALL_BANNER: + case MAGENTA_BANNER: + case MAGENTA_WALL_BANNER: + case ORANGE_BANNER: + case ORANGE_WALL_BANNER: + case PINK_BANNER: + case PINK_WALL_BANNER: + case PURPLE_BANNER: + case PURPLE_WALL_BANNER: + case RED_BANNER: + case RED_WALL_BANNER: + case WHITE_BANNER: + case WHITE_WALL_BANNER: + case YELLOW_BANNER: + case YELLOW_WALL_BANNER: case FURNACE: - case CAKE_BLOCK: + case CAKE: case DISPENSER: case DROPPER: case HOPPER: case NOTE_BLOCK: case JUKEBOX: - case WORKBENCH: - case SILVER_SHULKER_BOX: + case CRAFTING_TABLE: + case LIGHT_GRAY_SHULKER_BOX: case BLACK_SHULKER_BOX: case BLUE_SHULKER_BOX: case RED_SHULKER_BOX: @@ -1481,8 +1832,8 @@ public class PlayerEvents extends PlotListener implements Listener { case LIME_SHULKER_BOX: case LIGHT_BLUE_SHULKER_BOX: case MAGENTA_SHULKER_BOX: - case COMMAND_REPEATING: - case COMMAND_CHAIN: + case CHAIN_COMMAND_BLOCK: + case REPEATING_COMMAND_BLOCK: eventType = PlayerBlockEventType.INTERACT_BLOCK; break; @@ -1495,80 +1846,100 @@ public class PlayerEvents extends PlotListener implements Listener { } break; } - lb = new BukkitLazyBlock(blockId, block); - ItemStack hand = player.getItemInHand(); - if (eventType != null && (eventType != PlayerBlockEventType.INTERACT_BLOCK || !player.isSneaking())) { + lb = new BukkitLazyBlock(PlotBlock.get(block.getType().toString())); + ItemStack hand = player.getInventory().getItemInMainHand(); + if (eventType != null && (eventType != PlayerBlockEventType.INTERACT_BLOCK + || !player.isSneaking())) { break; } Material type = (hand == null) ? null : hand.getType(); - int id = (type == null) ? 0 : type.getId(); if (type == Material.AIR) { eventType = PlayerBlockEventType.INTERACT_BLOCK; break; } - if (id < 198) { - location = BukkitUtil.getLocation(block.getRelative(event.getBlockFace()).getLocation()); + if (type == null || type.isBlock()) { + location = BukkitUtil + .getLocation(block.getRelative(event.getBlockFace()).getLocation()); eventType = PlayerBlockEventType.PLACE_BLOCK; - lb = new BukkitLazyBlock(id, block); break; } Material handType = hand.getType(); - lb = new BukkitLazyBlock(PlotBlock.get((short) handType.getId(), (byte) 0)); - switch (handType) { - case FIREWORK: - case MONSTER_EGG: - case MONSTER_EGGS: - eventType = PlayerBlockEventType.SPAWN_MOB; - break; - case ARMOR_STAND: - location = BukkitUtil.getLocation(block.getRelative(event.getBlockFace()).getLocation()); - eventType = PlayerBlockEventType.PLACE_MISC; - break; - case WRITTEN_BOOK: - case BOOK_AND_QUILL: - case BOOK: - eventType = PlayerBlockEventType.READ; - break; - case APPLE: - case BAKED_POTATO: - case MUSHROOM_SOUP: - case BREAD: - case CARROT: - case CARROT_ITEM: - case COOKIE: - case GRILLED_PORK: - case POISONOUS_POTATO: - case MUTTON: - case PORK: - case POTATO: - case POTATO_ITEM: - case POTION: - case PUMPKIN_PIE: - case RABBIT: - case RABBIT_FOOT: - case RABBIT_STEW: - case RAW_BEEF: - case RAW_FISH: - case RAW_CHICKEN: - eventType = PlayerBlockEventType.EAT; - break; - case MINECART: - case STORAGE_MINECART: - case POWERED_MINECART: - case HOPPER_MINECART: - case EXPLOSIVE_MINECART: - case COMMAND_MINECART: - case BOAT: - eventType = PlayerBlockEventType.PLACE_VEHICLE; - break; - case PAINTING: - case ITEM_FRAME: - location = BukkitUtil.getLocation(block.getRelative(event.getBlockFace()).getLocation()); - eventType = PlayerBlockEventType.PLACE_HANGING; - break; - default: - eventType = PlayerBlockEventType.INTERACT_BLOCK; - break; + lb = new BukkitLazyBlock(PlotBlock.get(handType.toString())); + if (handType.toString().endsWith("egg")) { + eventType = PlayerBlockEventType.SPAWN_MOB; + } else { + switch (handType) { + case FIREWORK_ROCKET: + case FIREWORK_STAR: + eventType = PlayerBlockEventType.SPAWN_MOB; + break; + case ARMOR_STAND: + location = BukkitUtil + .getLocation(block.getRelative(event.getBlockFace()).getLocation()); + eventType = PlayerBlockEventType.PLACE_MISC; + break; + case WRITTEN_BOOK: + case WRITABLE_BOOK: + case ENCHANTED_BOOK: + case KNOWLEDGE_BOOK: + case BOOK: + eventType = PlayerBlockEventType.READ; + break; + case APPLE: + case BAKED_POTATO: + case MUSHROOM_STEW: + case BREAD: + case CARROT: + case GOLDEN_CARROT: + case COOKIE: + case PORKCHOP: + case POISONOUS_POTATO: + case MUTTON: + case COOKED_PORKCHOP: + case POTATO: + case POTION: + case PUMPKIN_PIE: + case RABBIT: + case RABBIT_FOOT: + case RABBIT_STEW: + case BEEF: + case COOKED_BEEF: + case TROPICAL_FISH: + case PUFFERFISH: + case CHICKEN: + case COOKED_CHICKEN: + case COOKED_MUTTON: + case COOKED_RABBIT: + case COOKED_SALMON: + case SALMON: + case COD: + case COOKED_COD: + eventType = PlayerBlockEventType.EAT; + break; + case MINECART: + case CHEST_MINECART: + case FURNACE_MINECART: + case HOPPER_MINECART: + case TNT_MINECART: + case COMMAND_BLOCK_MINECART: + case BIRCH_BOAT: + case ACACIA_BOAT: + case DARK_OAK_BOAT: + case JUNGLE_BOAT: + case OAK_BOAT: + case SPRUCE_BOAT: + eventType = PlayerBlockEventType.PLACE_VEHICLE; + break; + case PAINTING: + case ITEM_FRAME: + location = BukkitUtil + .getLocation(block.getRelative(event.getBlockFace()).getLocation()); + eventType = PlayerBlockEventType.PLACE_HANGING; + break; + default: + eventType = PlayerBlockEventType.INTERACT_BLOCK; + break; + } } break; } @@ -1581,8 +1952,9 @@ public class PlayerEvents extends PlotListener implements Listener { default: return; } - if (PS.get().worldedit != null && pp.getAttribute("worldedit")) { - if (player.getItemInHand().getTypeId() == PS.get().worldedit.getConfiguration().wandItem) { + if (PlotSquared.get().worldedit != null && pp.getAttribute("worldedit")) { + if (player.getInventory().getItemInMainHand().getType() == Material + .getMaterial(PlotSquared.get().worldedit.getConfiguration().wandItem)) { return; } } @@ -1619,7 +1991,7 @@ public class PlayerEvents extends PlotListener implements Listener { case BUILD_WITHER: case BUILD_SNOWMAN: case CUSTOM: - if (!area.SPAWN_CUSTOM && entity.getType().getTypeId() != 30) { + if (!area.SPAWN_CUSTOM && entity.getType() != EntityType.ARMOR_STAND) { event.setCancelled(true); return; } @@ -1651,7 +2023,7 @@ public class PlayerEvents extends PlotListener implements Listener { Block block = event.getBlock(); World world = block.getWorld(); String worldName = world.getName(); - if (!PS.get().hasPlotArea(worldName)) { + if (!PlotSquared.get().hasPlotArea(worldName)) { return; } Location location = BukkitUtil.getLocation(block.getLocation()); @@ -1676,219 +2048,15 @@ public class PlayerEvents extends PlotListener implements Listener { entity.remove(); } } else if (event.getTo() == Material.AIR) { - event.getEntity().setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot)); + event.getEntity() + .setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot)); } } - @EventHandler - public void onPrime(ExplosionPrimeEvent event) { + @EventHandler public void onPrime(ExplosionPrimeEvent event) { this.lastRadius = event.getRadius() + 1; } - public static boolean checkEntity(Plot plot, IntegerFlag... flags) { - if (Settings.Done.RESTRICT_BUILDING && Flags.DONE.isSet(plot)) { - return true; - } - int[] mobs = null; - for (IntegerFlag flag : flags) { - int i; - switch (flag.getName()) { - case "entity-cap": - i = 0; - break; - case "mob-cap": - i = 3; - break; - case "hostile-cap": - i = 2; - break; - case "animal-cap": - i = 1; - break; - case "vehicle-cap": - i = 4; - break; - case "misc-cap": - i = 5; - break; - default: - i = 0; - } - int cap = plot.getFlag(flag, Integer.MAX_VALUE); - if (cap == Integer.MAX_VALUE) { - continue; - } - if (cap == 0) { - return true; - } - if (mobs == null) { - mobs = plot.countEntities(); - } - if (mobs[i] >= cap) { - plot.setMeta("EntityCount", mobs); - plot.setMeta("EntityCountTime", System.currentTimeMillis()); - return true; - } - } - if (mobs != null) { - for (IntegerFlag flag : flags) { - int i; - switch (flag.getName()) { - case "entity-cap": - i = 0; - break; - case "mob-cap": - i = 3; - break; - case "hostile-cap": - i = 2; - break; - case "animal-cap": - i = 1; - break; - case "vehicle-cap": - i = 4; - break; - case "misc-cap": - i = 5; - break; - default: - i = 0; - } - mobs[i]++; - } - plot.setMeta("EntityCount", mobs); - plot.setMeta("EntityCountTime", System.currentTimeMillis()); - } - return false; - } - - public static boolean checkEntity(Entity entity, Plot plot) { - if (plot == null || !plot.hasOwner() || plot.getFlags().isEmpty() && plot.getArea().DEFAULT_FLAGS.isEmpty()) { - return false; - } - switch (entity.getType()) { - case PLAYER: - return false; - case LLAMA_SPIT: - case SMALL_FIREBALL: - case FIREBALL: - case DROPPED_ITEM: - case EGG: - case THROWN_EXP_BOTTLE: - case SPLASH_POTION: - case LINGERING_POTION: - case SNOWBALL: - case ENDER_PEARL: - case ARROW: - case TIPPED_ARROW: - case SPECTRAL_ARROW: - case SHULKER_BULLET: - case DRAGON_FIREBALL: - // projectile - case PRIMED_TNT: - case FALLING_BLOCK: - // Block entities - case ENDER_CRYSTAL: - case COMPLEX_PART: - case FISHING_HOOK: - case ENDER_SIGNAL: - case EXPERIENCE_ORB: - case LEASH_HITCH: - case FIREWORK: - case WEATHER: - case AREA_EFFECT_CLOUD: - case LIGHTNING: - case WITHER_SKULL: - case EVOKER_FANGS: - case UNKNOWN: - // non moving / unmovable - return checkEntity(plot, Flags.ENTITY_CAP); - case ITEM_FRAME: - case PAINTING: - case ARMOR_STAND: - return checkEntity(plot, Flags.ENTITY_CAP, Flags.MISC_CAP); - // misc - case MINECART: - case MINECART_CHEST: - case MINECART_COMMAND: - case MINECART_FURNACE: - case MINECART_HOPPER: - case MINECART_MOB_SPAWNER: - case MINECART_TNT: - case BOAT: - return checkEntity(plot, Flags.ENTITY_CAP, Flags.VEHICLE_CAP); - case POLAR_BEAR: - case RABBIT: - case SHEEP: - case MUSHROOM_COW: - case OCELOT: - case PIG: - case SQUID: - case VILLAGER: - case IRON_GOLEM: - case WOLF: - case CHICKEN: - case COW: - case SNOWMAN: - case BAT: - case HORSE: - case DONKEY: - case LLAMA: - case MULE: - case ZOMBIE_HORSE: - case SKELETON_HORSE: - // animal - return checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP, Flags.ANIMAL_CAP); - case BLAZE: - case CAVE_SPIDER: - case CREEPER: - case ENDERMAN: - case ENDERMITE: - case ENDER_DRAGON: - case GHAST: - case GIANT: - case GUARDIAN: - case MAGMA_CUBE: - case PIG_ZOMBIE: - case SILVERFISH: - case SKELETON: - case SLIME: - case SPIDER: - case WITCH: - case WITHER: - case ZOMBIE: - case SHULKER: - case HUSK: - case STRAY: - case ELDER_GUARDIAN: - case WITHER_SKELETON: - case VINDICATOR: - case EVOKER: - case VEX: - case ZOMBIE_VILLAGER: - // monster - return checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP, Flags.HOSTILE_CAP); - default: - if (entity instanceof LivingEntity) { - if (entity instanceof Animals) { - return checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP, Flags.ANIMAL_CAP); - } else if (entity instanceof Monster) { - return checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP, Flags.HOSTILE_CAP); - } else { - return checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP); - } - } - if (entity instanceof Vehicle) { - return checkEntity(plot, Flags.ENTITY_CAP, Flags.VEHICLE_CAP); - } - if (entity instanceof Hanging) { - return checkEntity(plot, Flags.ENTITY_CAP, Flags.MISC_CAP); - } - return checkEntity(plot, Flags.ENTITY_CAP); - } - } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockBurn(BlockBurnEvent event) { Block b = event.getBlock(); @@ -1942,7 +2110,8 @@ public class PlayerEvents extends PlotListener implements Listener { } } else if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + MainUtil + .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); } } else if (!plot.isAdded(pp.getUUID())) { @@ -1959,7 +2128,7 @@ public class PlayerEvents extends PlotListener implements Listener { return; } if (ignitingEntity != null) { - if (!plot.getFlag(Flags.BLOCK_IGNITION,false)) { + if (!plot.getFlag(Flags.BLOCK_IGNITION, false)) { event.setCancelled(true); return; } @@ -1971,7 +2140,8 @@ public class PlayerEvents extends PlotListener implements Listener { Entity shooter = (Entity) fireball.getShooter(); location = BukkitUtil.getLocation(shooter.getLocation()); } else if (fireball.getShooter() instanceof BlockProjectileSource) { - Block shooter = ((BlockProjectileSource) fireball.getShooter()).getBlock(); + Block shooter = + ((BlockProjectileSource) fireball.getShooter()).getBlock(); location = BukkitUtil.getLocation(shooter.getLocation()); } if (location != null && !plot.equals(location.getPlot())) { @@ -1983,10 +2153,13 @@ public class PlayerEvents extends PlotListener implements Listener { } else if (event.getIgnitingBlock() != null) { Block ignitingBlock = event.getIgnitingBlock(); Plot plotIgnited = BukkitUtil.getLocation(ignitingBlock.getLocation()).getPlot(); - if (igniteCause == BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL && (!plot.getFlag(Flags.BLOCK_IGNITION,false) - || plotIgnited == null || !plotIgnited.equals(plot)) - || (igniteCause == BlockIgniteEvent.IgniteCause.SPREAD || igniteCause == BlockIgniteEvent.IgniteCause.LAVA) && ( - !plot.getFlag(Flags.BLOCK_IGNITION).or(false) || plotIgnited == null || !plotIgnited.equals(plot))) { + if (igniteCause == BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL && ( + !plot.getFlag(Flags.BLOCK_IGNITION, false) || plotIgnited == null + || !plotIgnited.equals(plot)) || + (igniteCause == BlockIgniteEvent.IgniteCause.SPREAD + || igniteCause == BlockIgniteEvent.IgniteCause.LAVA) && ( + !plot.getFlag(Flags.BLOCK_IGNITION).or(false) || plotIgnited == null + || !plotIgnited.equals(plot))) { event.setCancelled(true); } } @@ -1996,7 +2169,9 @@ public class PlayerEvents extends PlotListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBucketEmpty(PlayerBucketEmptyEvent event) { BlockFace bf = event.getBlockFace(); - Block b = event.getBlockClicked().getLocation().add(bf.getModX(), bf.getModY(), bf.getModZ()).getBlock(); + Block b = + event.getBlockClicked().getLocation().add(bf.getModX(), bf.getModY(), bf.getModZ()) + .getBlock(); Location location = BukkitUtil.getLocation(b.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { @@ -2028,23 +2203,6 @@ public class PlayerEvents extends PlotListener implements Listener { } } - @EventHandler(priority = EventPriority.HIGHEST) - public void onInventoryClick(InventoryClickEvent event) { - HumanEntity clicker = event.getWhoClicked(); - if (!(clicker instanceof Player)) { - return; - } - Player player = (Player) clicker; - PlotPlayer pp = BukkitUtil.getPlayer(player); - PlotInventory inventory = pp.getMeta("inventory"); - if (inventory != null && event.getRawSlot() == event.getSlot()) { - if (!inventory.onClick(event.getSlot())) { - event.setCancelled(true); - inventory.close(); - } - } - } - @EventHandler(priority = EventPriority.HIGHEST) public void onInventoryClose(InventoryCloseEvent event) { HumanEntity closer = event.getPlayer(); @@ -2055,8 +2213,7 @@ public class PlayerEvents extends PlotListener implements Listener { BukkitUtil.getPlayer(player).deleteMeta("inventory"); } - @EventHandler(priority = EventPriority.MONITOR) - public void onLeave(PlayerQuitEvent event) { + @EventHandler(priority = EventPriority.MONITOR) public void onLeave(PlayerQuitEvent event) { if (TaskManager.TELEPORT_QUEUE.contains(event.getPlayer().getName())) { TaskManager.TELEPORT_QUEUE.remove(event.getPlayer().getName()); } @@ -2085,12 +2242,13 @@ public class PlayerEvents extends PlotListener implements Listener { if (Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { return; } - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + MainUtil + .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); } else if (!plot.isAdded(plotPlayer.getUUID())) { Optional> use = plot.getFlag(Flags.USE); Block block = event.getBlockClicked(); - if (use.isPresent() && use.get().contains(PlotBlock.get(block.getTypeId(), block.getData()))) { + if (use.isPresent() && use.get().contains(PlotBlock.get(block.getType().name()))) { return; } if (Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_BUILD_OTHER)) { @@ -2115,7 +2273,8 @@ public class PlayerEvents extends PlotListener implements Listener { return; } if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) { - entity.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot)); + entity + .setMetadata("plot", new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot)); } } @@ -2138,15 +2297,17 @@ public class PlayerEvents extends PlotListener implements Listener { } else { if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + MainUtil + .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); } return; } if (!plot.isAdded(pp.getUUID())) { - if (!plot.getFlag(Flags.HANGING_PLACE,false)) { + if (!plot.getFlag(Flags.HANGING_PLACE, false)) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + MainUtil + .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); } return; @@ -2173,12 +2334,14 @@ public class PlayerEvents extends PlotListener implements Listener { Plot plot = area.getPlot(location); if (plot == null) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_ROAD); + MainUtil + .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_ROAD); event.setCancelled(true); } } else if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_UNOWNED); + MainUtil + .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_UNOWNED); event.setCancelled(true); } } else if (!plot.isAdded(pp.getUUID())) { @@ -2186,7 +2349,8 @@ public class PlayerEvents extends PlotListener implements Listener { return; } if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER); + MainUtil + .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER); event.setCancelled(true); } } @@ -2203,14 +2367,18 @@ public class PlayerEvents extends PlotListener implements Listener { Plot plot = area.getPlot(BukkitUtil.getLocation(event.getEntity())); if (plot != null) { if (!plot.hasOwner()) { - if (!Permissions.hasPermission(player, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { - MainUtil.sendMessage(player, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_UNOWNED); + if (!Permissions + .hasPermission(player, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { + MainUtil.sendMessage(player, C.NO_PERMISSION_EVENT, + C.PERMISSION_ADMIN_DESTROY_UNOWNED); event.setCancelled(true); } } else if (!plot.isAdded(player.getUUID())) { if (!plot.getFlag(Flags.HANGING_BREAK, false)) { - if (!Permissions.hasPermission(player, C.PERMISSION_ADMIN_DESTROY_OTHER)) { - MainUtil.sendMessage(player, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER); + if (!Permissions + .hasPermission(player, C.PERMISSION_ADMIN_DESTROY_OTHER)) { + MainUtil.sendMessage(player, C.NO_PERMISSION_EVENT, + C.PERMISSION_ADMIN_DESTROY_OTHER); event.setCancelled(true); } } @@ -2239,7 +2407,8 @@ public class PlayerEvents extends PlotListener implements Listener { } } else if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_UNOWNED); + MainUtil + .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_UNOWNED); event.setCancelled(true); } } else if (!plot.isAdded(pp.getUUID())) { @@ -2250,7 +2419,8 @@ public class PlayerEvents extends PlotListener implements Listener { if (entity instanceof Animals && plot.getFlag(Flags.ANIMAL_INTERACT, false)) { return; } - if (entity instanceof Tameable && ((Tameable) entity).isTamed() && plot.getFlag(Flags.TAMED_INTERACT, false)) { + if (entity instanceof Tameable && ((Tameable) entity).isTamed() && plot + .getFlag(Flags.TAMED_INTERACT, false)) { return; } if (entity instanceof Vehicle && plot.getFlag(Flags.VEHICLE_USE, false)) { @@ -2286,13 +2456,15 @@ public class PlayerEvents extends PlotListener implements Listener { Plot plot = area.getPlot(l); if (plot == null) { if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.road")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.road"); + MainUtil + .sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.road"); event.setCancelled(true); } } else { if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.unowned")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.unowned"); + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, + "plots.admin.vehicle.break.unowned"); event.setCancelled(true); return; } @@ -2303,7 +2475,8 @@ public class PlayerEvents extends PlotListener implements Listener { return; } if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.other")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.other"); + MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, + "plots.admin.vehicle.break.other"); event.setCancelled(true); } } @@ -2315,7 +2488,7 @@ public class PlayerEvents extends PlotListener implements Listener { public void onPotionSplash(PotionSplashEvent event) { ThrownPotion damager = event.getPotion(); Location l = BukkitUtil.getLocation(damager); - if (!PS.get().hasPlotArea(l.getWorld())) { + if (!PlotSquared.get().hasPlotArea(l.getWorld())) { return; } int count = 0; @@ -2330,26 +2503,11 @@ public class PlayerEvents extends PlotListener implements Listener { } } - @SuppressWarnings("deprecation") - @EventHandler(priority = EventPriority.HIGHEST) + @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.HIGHEST) public void onEntityCombustByEntity(EntityCombustByEntityEvent event) { EntityDamageByEntityEvent eventChange = null; - if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_11_0)) { - eventChange = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), - EntityDamageEvent.DamageCause.FIRE_TICK, (double)event.getDuration()); - } else { - try { - Constructor constructor = EntityDamageByEntityEvent.class.getConstructor(Entity.class, - Entity.class, EntityDamageEvent.DamageCause.class, Integer.TYPE); - eventChange = constructor.newInstance(event.getCombuster(), event.getEntity(), - EntityDamageEvent.DamageCause.FIRE_TICK, event.getDuration()); - } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { - e.printStackTrace(); - } - } - if (eventChange == null) { - return; - } + eventChange = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), + EntityDamageEvent.DamageCause.FIRE_TICK, (double) event.getDuration()); onEntityDamageByEntityEvent(eventChange); if (eventChange.isCancelled()) { event.setCancelled(true); @@ -2360,7 +2518,7 @@ public class PlayerEvents extends PlotListener implements Listener { public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) { Entity damager = event.getDamager(); Location l = BukkitUtil.getLocation(damager); - if (!PS.get().hasPlotArea(l.getWorld())) { + if (!PlotSquared.get().hasPlotArea(l.getWorld())) { return; } Entity victim = event.getEntity(); @@ -2382,7 +2540,8 @@ public class PlayerEvents extends PlotListener implements Listener { Location dloc = BukkitUtil.getLocation(damager); Location vloc = BukkitUtil.getLocation(victim); PlotArea dArea = dloc.getPlotArea(); - PlotArea vArea = dArea != null && dArea.contains(vloc.getX(), vloc.getZ()) ? dArea : vloc.getPlotArea(); + PlotArea vArea = + dArea != null && dArea.contains(vloc.getX(), vloc.getZ()) ? dArea : vloc.getPlotArea(); if (dArea == null && vArea == null) { return true; } @@ -2438,7 +2597,8 @@ public class PlayerEvents extends PlotListener implements Listener { player = (Player) shooter; } else { // shooter is not player if (shooter instanceof BlockProjectileSource) { - Location sLoc = BukkitUtil.getLocation(((BlockProjectileSource) shooter).getBlock().getLocation()); + Location sLoc = BukkitUtil + .getLocation(((BlockProjectileSource) shooter).getBlock().getLocation()); dplot = dArea.getPlot(sLoc); } player = null; @@ -2449,76 +2609,92 @@ public class PlayerEvents extends PlotListener implements Listener { if (player != null) { PlotPlayer plotPlayer = BukkitUtil.getPlayer(player); if (victim instanceof Hanging) { // hanging - if (plot != null && (plot.getFlag(Flags.HANGING_BREAK, false) || plot.isAdded(plotPlayer.getUUID()))) { + if (plot != null && (plot.getFlag(Flags.HANGING_BREAK, false) || plot + .isAdded(plotPlayer.getUUID()))) { return true; } if (!Permissions.hasPermission(plotPlayer, "plots.admin.destroy." + stub)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.destroy." + stub); + MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, + "plots.admin.destroy." + stub); return false; } } else if (victim.getEntityId() == 30) { - if (plot != null && (plot.getFlag(Flags.MISC_BREAK, false) || plot.isAdded(plotPlayer.getUUID()))) { + if (plot != null && (plot.getFlag(Flags.MISC_BREAK, false) || plot + .isAdded(plotPlayer.getUUID()))) { return true; } if (!Permissions.hasPermission(plotPlayer, "plots.admin.destroy." + stub)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.destroy." + stub); + MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, + "plots.admin.destroy." + stub); return false; } - } else if (victim instanceof Monster || victim instanceof EnderDragon) { // victim is monster - if (plot != null && (plot.getFlag(Flags.HOSTILE_ATTACK, false) || plot.getFlag(Flags.PVE, false) || plot - .isAdded(plotPlayer.getUUID()))) { + } else if (victim instanceof Monster + || victim instanceof EnderDragon) { // victim is monster + if (plot != null && (plot.getFlag(Flags.HOSTILE_ATTACK, false) || plot + .getFlag(Flags.PVE, false) || plot.isAdded(plotPlayer.getUUID()))) { return true; } if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); + MainUtil + .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); return false; } } else if (victim instanceof Tameable) { // victim is tameable - if (plot != null && (plot.getFlag(Flags.TAMED_ATTACK, false) || plot.getFlag(Flags.PVE, false) || plot.isAdded(plotPlayer.getUUID()))) { + if (plot != null && (plot.getFlag(Flags.TAMED_ATTACK, false) || plot + .getFlag(Flags.PVE, false) || plot.isAdded(plotPlayer.getUUID()))) { return true; } if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); + MainUtil + .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); return false; } } else if (victim instanceof Player) { if (plot != null) { - if (Flags.PVP.isFalse(plot) && !Permissions.hasPermission(plotPlayer, "plots.admin.pvp." + stub)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pvp." + stub); + if (Flags.PVP.isFalse(plot) && !Permissions + .hasPermission(plotPlayer, "plots.admin.pvp." + stub)) { + MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, + "plots.admin.pvp." + stub); return false; } else { return true; } } if (!Permissions.hasPermission(plotPlayer, "plots.admin.pvp." + stub)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pvp." + stub); + MainUtil + .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pvp." + stub); return false; } } else if (victim instanceof Creature) { // victim is animal - if (plot != null && (plot.getFlag(Flags.ANIMAL_ATTACK, false) || plot.getFlag(Flags.PVE, false) || plot - .isAdded(plotPlayer.getUUID()))) { + if (plot != null && (plot.getFlag(Flags.ANIMAL_ATTACK, false) || plot + .getFlag(Flags.PVE, false) || plot.isAdded(plotPlayer.getUUID()))) { return true; } if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); + MainUtil + .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); return false; } } else if (victim instanceof Vehicle) { // Vehicles are managed in vehicle destroy event return true; } else { // victim is something else - if (plot != null && (plot.getFlag(Flags.PVE, false) || plot.isAdded(plotPlayer.getUUID()))) { + if (plot != null && (plot.getFlag(Flags.PVE, false) || plot + .isAdded(plotPlayer.getUUID()))) { return true; } if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); + MainUtil + .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); return false; } } return true; - } else if (dplot != null && (!(dplot.equals(vplot)) || (vplot != null && Objects.equals(dplot.owner, vplot.owner)))) { + } else if (dplot != null && (!dplot.equals(vplot) || Objects + .equals(dplot.guessOwner(), vplot.guessOwner()))) { return vplot != null && Flags.PVE.isTrue(vplot); } - return ((vplot != null && Flags.PVE.isTrue(vplot)) || !(damager instanceof Arrow && !(victim instanceof Creature))); + return ((vplot != null && Flags.PVE.isTrue(vplot)) || !(damager instanceof Arrow + && !(victim instanceof Creature))); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @@ -2533,17 +2709,20 @@ public class PlayerEvents extends PlotListener implements Listener { Plot plot = area.getPlot(l); if (plot == null) { if (!Permissions.hasPermission(plotPlayer, "plots.admin.projectile.road")) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.projectile.road"); + MainUtil + .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.projectile.road"); event.setHatching(false); } } else if (!plot.hasOwner()) { if (!Permissions.hasPermission(plotPlayer, "plots.admin.projectile.unowned")) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.projectile.unowned"); + MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, + "plots.admin.projectile.unowned"); event.setHatching(false); } } else if (!plot.isAdded(plotPlayer.getUUID())) { if (!Permissions.hasPermission(plotPlayer, "plots.admin.projectile.other")) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.projectile.other"); + MainUtil + .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.projectile.other"); event.setHatching(false); } } @@ -2560,14 +2739,16 @@ public class PlayerEvents extends PlotListener implements Listener { PlotPlayer pp = BukkitUtil.getPlayer(player); Plot plot = area.getPlot(location); if (plot != null) { - if ((location.getY() > area.MAX_BUILD_HEIGHT || location.getY() < area.MIN_BUILD_HEIGHT) && !Permissions - .hasPermission(pp, C.PERMISSION_ADMIN_BUILD_HEIGHTLIMIT)) { + if ((location.getY() > area.MAX_BUILD_HEIGHT || location.getY() < area.MIN_BUILD_HEIGHT) + && !Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_HEIGHTLIMIT)) { event.setCancelled(true); - MainUtil.sendMessage(pp, C.HEIGHT_LIMIT.s().replace("{limit}", String.valueOf(area.MAX_BUILD_HEIGHT))); + MainUtil.sendMessage(pp, + C.HEIGHT_LIMIT.s().replace("{limit}", String.valueOf(area.MAX_BUILD_HEIGHT))); } if (!plot.hasOwner()) { if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + MainUtil + .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); return; } @@ -2575,7 +2756,7 @@ public class PlayerEvents extends PlotListener implements Listener { Set place = plot.getFlag(Flags.PLACE, null); if (place != null) { Block block = event.getBlock(); - if (place.contains(PlotBlock.get((short) block.getTypeId(), block.getData()))) { + if (place.contains(PlotBlock.get(block.getType().name()))) { return; } } @@ -2594,7 +2775,7 @@ public class PlayerEvents extends PlotListener implements Listener { if (plot.getFlag(Flags.DISABLE_PHYSICS, false)) { Block block = event.getBlockPlaced(); if (block.getType().hasGravity()) { - sendBlockChange(block.getLocation(), block.getType(), block.getData()); + sendBlockChange(block.getLocation(), block.getBlockData()); } } } else if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlotPlusListener.java similarity index 62% rename from Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlotPlusListener.java index 7b9d43100..afabd8250 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlotPlusListener.java @@ -1,21 +1,18 @@ -package com.plotsquared.bukkit.listeners; +package com.github.intellectualsites.plotsquared.bukkit.listeners; +import com.github.intellectualsites.plotsquared.bukkit.events.PlayerEnterPlotEvent; +import com.github.intellectualsites.plotsquared.bukkit.events.PlayerLeavePlotEvent; +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil; +import com.github.intellectualsites.plotsquared.plot.flag.Flags; +import com.github.intellectualsites.plotsquared.plot.listener.PlotListener; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.google.common.base.Optional; -import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.plotsquared.bukkit.events.PlayerEnterPlotEvent; -import com.plotsquared.bukkit.events.PlayerLeavePlotEvent; -import com.plotsquared.bukkit.util.BukkitUtil; -import com.plotsquared.listener.PlotListener; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; -import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.block.Block; import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -23,22 +20,28 @@ import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityPickupItemEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.java.JavaPlugin; -public class PlotPlusListener extends PlotListener implements Listener { +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; +import java.util.UUID; - private static final HashMap feedRunnable = new HashMap<>(); - private static final HashMap healRunnable = new HashMap<>(); +@SuppressWarnings("unused") public class PlotPlusListener extends PlotListener implements Listener { + + private static final HashMap feedRunnable = new HashMap<>(); + private static final HashMap healRunnable = new HashMap<>(); public static void startRunnable(JavaPlugin plugin) { plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { - @Override - public void run() { + @Override public void run() { if (!healRunnable.isEmpty()) { - for (Iterator> iterator = healRunnable.entrySet().iterator(); iterator.hasNext(); ) { - Entry entry = iterator.next(); + for (Iterator> iterator = + healRunnable.entrySet().iterator(); iterator.hasNext(); ) { + Entry entry = iterator.next(); Interval value = entry.getValue(); ++value.count; if (value.count == value.interval) { @@ -56,8 +59,9 @@ public class PlotPlusListener extends PlotListener implements Listener { } } if (!feedRunnable.isEmpty()) { - for (Iterator> iterator = feedRunnable.entrySet().iterator(); iterator.hasNext(); ) { - Entry entry = iterator.next(); + for (Iterator> iterator = + feedRunnable.entrySet().iterator(); iterator.hasNext(); ) { + Entry entry = iterator.next(); Interval value = entry.getValue(); ++value.count; if (value.count == value.interval) { @@ -78,8 +82,7 @@ public class PlotPlusListener extends PlotListener implements Listener { }, 0L, 20L); } - @EventHandler(priority = EventPriority.HIGH) - public void onInteract(BlockDamageEvent event) { + @EventHandler(priority = EventPriority.HIGH) public void onInteract(BlockDamageEvent event) { Player player = event.getPlayer(); if (player.getGameMode() != GameMode.SURVIVAL) { return; @@ -97,9 +100,8 @@ public class PlotPlusListener extends PlotListener implements Listener { } } } - - @EventHandler(priority = EventPriority.HIGH) - public void onDamage(EntityDamageEvent event) { + + @EventHandler(priority = EventPriority.HIGH) public void onDamage(EntityDamageEvent event) { if (event.getEntityType() != EntityType.PLAYER) { return; } @@ -112,9 +114,8 @@ public class PlotPlusListener extends PlotListener implements Listener { event.setCancelled(true); } } - - @EventHandler - public void onItemDrop(PlayerDropItemEvent event) { + + @EventHandler public void onItemDrop(PlayerDropItemEvent event) { Player player = event.getPlayer(); PlotPlayer pp = BukkitUtil.getPlayer(player); Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); @@ -128,42 +129,53 @@ public class PlotPlusListener extends PlotListener implements Listener { } } } - - @EventHandler - public void onPlotEnter(PlayerEnterPlotEvent event) { + + @EventHandler public void onPlotEnter(PlayerEnterPlotEvent event) { Player player = event.getPlayer(); Plot plot = event.getPlot(); Optional feed = plot.getFlag(Flags.FEED); if (feed.isPresent()) { Integer[] value = feed.get(); - feedRunnable.put(player.getName(), new Interval(value[0], value[1], 20)); + feedRunnable.put(player.getUniqueId(), new Interval(value[0], value[1], 20)); } Optional heal = plot.getFlag(Flags.HEAL); if (heal.isPresent()) { Integer[] value = heal.get(); - healRunnable.put(player.getName(), new Interval(value[0], value[1], 20)); + healRunnable.put(player.getUniqueId(), new Interval(value[0], value[1], 20)); } } - - @EventHandler - public void onPlayerQuit(PlayerQuitEvent event) { + + @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { Player player = event.getPlayer(); - String name = player.getName(); - feedRunnable.remove(name); - healRunnable.remove(name); + feedRunnable.remove(player.getUniqueId()); + healRunnable.remove(player.getUniqueId()); } - - @EventHandler - public void onPlotLeave(PlayerLeavePlotEvent event) { + + @EventHandler public void onPlotLeave(PlayerLeavePlotEvent event) { Player leaver = event.getPlayer(); Plot plot = event.getPlot(); if (!plot.hasOwner()) { return; } BukkitUtil.getPlayer(leaver); - String name = leaver.getName(); - feedRunnable.remove(name); - healRunnable.remove(name); + feedRunnable.remove(leaver.getUniqueId()); + healRunnable.remove(leaver.getUniqueId()); + } + + @EventHandler public void onItemPickup(EntityPickupItemEvent event) { + LivingEntity ent = event.getEntity(); + if (ent instanceof Player) { + Player player = (Player) ent; + PlotPlayer pp = BukkitUtil.getPlayer(player); + Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); + if (plot == null) { + return; + } + UUID uuid = pp.getUUID(); + if (!plot.isAdded(uuid) && Flags.DROP_PROTECTION.isTrue(plot)) { + event.setCancelled(true); + } + } } private static class Interval { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/SingleWorldListener.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/SingleWorldListener.java similarity index 64% rename from Bukkit/src/main/java/com/plotsquared/bukkit/listeners/SingleWorldListener.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/SingleWorldListener.java index 146d30f53..6a3e26d59 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/SingleWorldListener.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/SingleWorldListener.java @@ -1,11 +1,9 @@ -package com.plotsquared.bukkit.listeners; +package com.github.intellectualsites.plotsquared.bukkit.listeners; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.object.worlds.PlotAreaManager; -import com.intellectualcrafters.plot.object.worlds.SinglePlotAreaManager; -import com.intellectualcrafters.plot.util.ReflectionUtils; -import java.lang.reflect.Field; -import java.lang.reflect.Method; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.object.worlds.PlotAreaManager; +import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotAreaManager; +import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.World; @@ -16,10 +14,12 @@ import org.bukkit.event.world.ChunkEvent; import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.plugin.Plugin; +import java.lang.reflect.Field; +import java.lang.reflect.Method; -import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; +import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass; -public class SingleWorldListener implements Listener { +@SuppressWarnings("unused") public class SingleWorldListener implements Listener { private Method methodGetHandleChunk; private Field mustSave, done, lit, s; @@ -42,10 +42,14 @@ public class SingleWorldListener implements Listener { public void markChunkAsClean(Chunk chunk) { try { Object nmsChunk = methodGetHandleChunk.invoke(chunk); - if (done != null) this.done.set(nmsChunk, true); - if (mustSave != null) this.mustSave.set(nmsChunk, false); - if (lit != null) this.lit.set(nmsChunk, false); - if (s != null) this.s.set(nmsChunk, false); + if (done != null) + this.done.set(nmsChunk, true); + if (mustSave != null) + this.mustSave.set(nmsChunk, false); + if (lit != null) + this.lit.set(nmsChunk, false); + if (s != null) + this.s.set(nmsChunk, false); } catch (Throwable e) { e.printStackTrace(); } @@ -54,20 +58,21 @@ public class SingleWorldListener implements Listener { private void handle(ChunkEvent event) { World world = event.getWorld(); String name = world.getName(); - PlotAreaManager man = PS.get().getPlotAreaManager(); - if (!(man instanceof SinglePlotAreaManager)) return; - if (!isPlotId(name)) return; + PlotAreaManager man = PlotSquared.get().getPlotAreaManager(); + if (!(man instanceof SinglePlotAreaManager)) + return; + if (!isPlotId(name)) + return; markChunkAsClean(event.getChunk()); } -// @EventHandler -// public void onPopulate(ChunkPopulateEvent event) { -// handle(event); -// } + // @EventHandler + // public void onPopulate(ChunkPopulateEvent event) { + // handle(event); + // } - @EventHandler(priority = EventPriority.LOWEST) - public void onChunkLoad(ChunkLoadEvent event) { + @EventHandler(priority = EventPriority.LOWEST) public void onChunkLoad(ChunkLoadEvent event) { handle(event); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/WorldEvents.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/WorldEvents.java similarity index 51% rename from Bukkit/src/main/java/com/plotsquared/bukkit/listeners/WorldEvents.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/WorldEvents.java index 1e80cc19b..98d6c0f5a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/WorldEvents.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/WorldEvents.java @@ -1,10 +1,10 @@ -package com.plotsquared.bukkit.listeners; +package com.github.intellectualsites.plotsquared.bukkit.listeners; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.generator.GeneratorWrapper; -import com.intellectualcrafters.plot.object.worlds.PlotAreaManager; -import com.intellectualcrafters.plot.object.worlds.SinglePlotAreaManager; -import com.plotsquared.bukkit.generator.BukkitPlotGenerator; +import com.github.intellectualsites.plotsquared.bukkit.generator.BukkitPlotGenerator; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; +import com.github.intellectualsites.plotsquared.plot.object.worlds.PlotAreaManager; +import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotAreaManager; import org.bukkit.World; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -12,13 +12,13 @@ import org.bukkit.event.Listener; import org.bukkit.event.world.WorldInitEvent; import org.bukkit.generator.ChunkGenerator; -public class WorldEvents implements Listener { - +@SuppressWarnings("unused") public class WorldEvents implements Listener { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onWorldInit(WorldInitEvent event) { World world = event.getWorld(); String name = world.getName(); - PlotAreaManager manager = PS.get().getPlotAreaManager(); + PlotAreaManager manager = PlotSquared.get().getPlotAreaManager(); if (manager instanceof SinglePlotAreaManager) { SinglePlotAreaManager single = (SinglePlotAreaManager) manager; if (single.isWorld(name)) { @@ -28,9 +28,9 @@ public class WorldEvents implements Listener { } ChunkGenerator gen = world.getGenerator(); if (gen instanceof GeneratorWrapper) { - PS.get().loadWorld(name, (GeneratorWrapper) gen); + PlotSquared.get().loadWorld(name, (GeneratorWrapper) gen); } else { - PS.get().loadWorld(name, new BukkitPlotGenerator(name, gen)); + PlotSquared.get().loadWorld(name, new BukkitPlotGenerator(name, gen)); } } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitLazyBlock.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitLazyBlock.java new file mode 100644 index 000000000..0903e78d9 --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitLazyBlock.java @@ -0,0 +1,25 @@ +package com.github.intellectualsites.plotsquared.bukkit.object; + +import com.github.intellectualsites.plotsquared.plot.object.LazyBlock; +import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; +import com.github.intellectualsites.plotsquared.plot.object.StringPlotBlock; +import org.bukkit.block.Block; + +public class BukkitLazyBlock extends LazyBlock { + + private StringPlotBlock pb; + + public BukkitLazyBlock(Block block) { + this.pb = (StringPlotBlock) PlotBlock.get(block.getType().toString()); + } + + public BukkitLazyBlock(StringPlotBlock pb) { + this.pb = pb; + } + + public StringPlotBlock getPlotBlock() { + return this.pb; + } + + +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitOfflinePlayer.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitOfflinePlayer.java similarity index 66% rename from Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitOfflinePlayer.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitOfflinePlayer.java index 715b92bee..390e9d9be 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitOfflinePlayer.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitOfflinePlayer.java @@ -1,6 +1,6 @@ -package com.plotsquared.bukkit.object; +package com.github.intellectualsites.plotsquared.bukkit.object; -import com.intellectualcrafters.plot.object.OfflinePlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer; import org.bukkit.OfflinePlayer; import java.util.UUID; @@ -19,23 +19,19 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer { this.player = player; } - @Override - public UUID getUUID() { + @Override public UUID getUUID() { return this.player.getUniqueId(); } - @Override - public long getLastPlayed() { + @Override public long getLastPlayed() { return this.player.getLastPlayed(); } - @Override - public boolean isOnline() { + @Override public boolean isOnline() { return this.player.isOnline(); } - @Override - public String getName() { + @Override public String getName() { return this.player.getName(); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitPlayer.java similarity index 71% rename from Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitPlayer.java index efeb04e11..a97993cfc 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitPlayer.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitPlayer.java @@ -1,28 +1,27 @@ -package com.plotsquared.bukkit.object; +package com.github.intellectualsites.plotsquared.bukkit.object; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.*; -import com.plotsquared.bukkit.util.BukkitUtil; -import org.apache.commons.lang.StringUtils; +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.*; import org.bukkit.Effect; import org.bukkit.GameMode; import org.bukkit.WeatherType; import org.bukkit.entity.Player; +import org.bukkit.event.Event; import org.bukkit.event.EventException; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import org.bukkit.permissions.PermissionAttachmentInfo; +import org.bukkit.plugin.RegisteredListener; import java.util.Set; import java.util.UUID; -import org.bukkit.permissions.PermissionAttachmentInfo; -import org.bukkit.plugin.RegisteredListener; - public class BukkitPlayer extends PlotPlayer { - + public final Player player; public boolean offline; private UUID uuid; @@ -31,6 +30,7 @@ public class BukkitPlayer extends PlotPlayer { /** *

Please do not use this method. Instead use * BukkitUtil.getPlayer(Player), as it caches player objects.

+ * * @param player */ public BukkitPlayer(Player player) { @@ -44,14 +44,12 @@ public class BukkitPlayer extends PlotPlayer { super.populatePersistentMetaMap(); } - @Override - public Location getLocation() { + @Override public Location getLocation() { Location location = super.getLocation(); return location == null ? BukkitUtil.getLocation(this.player) : location; } - - @Override - public UUID getUUID() { + + @Override public UUID getUUID() { if (this.uuid == null) { this.uuid = UUIDHandler.getUUID(this); } @@ -62,28 +60,23 @@ public class BukkitPlayer extends PlotPlayer { return this.player.getLastPlayed(); } - @Override - public boolean canTeleport(Location loc) { + @Override public boolean canTeleport(Location loc) { org.bukkit.Location to = BukkitUtil.getLocation(loc); org.bukkit.Location from = player.getLocation(); PlayerTeleportEvent event = new PlayerTeleportEvent(player, from, to); - RegisteredListener[] listeners = event.getHandlers().getRegisteredListeners(); - for (RegisteredListener listener : listeners) { - if (listener.getPlugin().getName().equals(PS.imp().getPluginName())) { - continue; - } - try { - listener.callEvent(event); - } catch (EventException e) { - e.printStackTrace(); - } - } + callEvent(event); if (event.isCancelled() || !event.getTo().equals(to)) { return false; } event = new PlayerTeleportEvent(player, to, from); + callEvent(event); + return true; + } + + private void callEvent(final Event event) { + RegisteredListener[] listeners = event.getHandlers().getRegisteredListeners(); for (RegisteredListener listener : listeners) { - if (listener.getPlugin().getName().equals(PS.imp().getPluginName())) { + if (listener.getPlugin().getName().equals(PlotSquared.imp().getPluginName())) { continue; } try { @@ -92,19 +85,16 @@ public class BukkitPlayer extends PlotPlayer { e.printStackTrace(); } } - return true; } - @Override - public boolean hasPermission(String permission) { + @Override public boolean hasPermission(String permission) { if (this.offline && EconHandler.manager != null) { return EconHandler.manager.hasPermission(getName(), permission); } return this.player.hasPermission(permission); } - @Override - public int hasPermissionRange(String stub, int range) { + @Override public int hasPermissionRange(String stub, int range) { if (hasPermission(C.PERMISSION_ADMIN.s())) { return Integer.MAX_VALUE; } @@ -131,8 +121,10 @@ public class BukkitPlayer extends PlotPlayer { String end = perm.substring(stubPlus.length()); if (MathMan.isInteger(end)) { int val = Integer.parseInt(end); - if (val > range) return val; - if (val > max) max = val; + if (val > range) + return val; + if (val > max) + max = val; } } } @@ -146,57 +138,52 @@ public class BukkitPlayer extends PlotPlayer { return max; } - @Override - public boolean isPermissionSet(String permission) { + @Override public boolean isPermissionSet(String permission) { return this.player.isPermissionSet(permission); } - @Override - public void sendMessage(String message) { - if (!StringMan.isEqual(this.getMeta("lastMessage"), message) || (System.currentTimeMillis() - this.getMeta("lastMessageTime") > 5000)) { + @Override public void sendMessage(String message) { + if (!StringMan.isEqual(this.getMeta("lastMessage"), message) || ( + System.currentTimeMillis() - this.getMeta("lastMessageTime") > 5000)) { setMeta("lastMessage", message); setMeta("lastMessageTime", System.currentTimeMillis()); this.player.sendMessage(message); } } - - @Override - public void teleport(Location location) { + + @Override public void teleport(Location location) { if (Math.abs(location.getX()) >= 30000000 || Math.abs(location.getZ()) >= 30000000) { return; } this.player.teleport( - new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX() + 0.5, location.getY(), location.getZ() + 0.5, - location.getYaw(), location.getPitch()), TeleportCause.COMMAND); + new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX() + 0.5, + location.getY(), location.getZ() + 0.5, location.getYaw(), location.getPitch()), + TeleportCause.COMMAND); } - - @Override - public String getName() { + + @Override public String getName() { if (this.name == null) { this.name = this.player.getName(); } return this.name; } - - @Override - public boolean isOnline() { + + @Override public boolean isOnline() { return !this.offline && this.player.isOnline(); } - - @Override - public void setCompassTarget(Location location) { + + @Override public void setCompassTarget(Location location) { this.player.setCompassTarget( - new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX(), location.getY(), location.getZ())); - + new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX(), + location.getY(), location.getZ())); + } - - @Override - public Location getLocationFull() { + + @Override public Location getLocationFull() { return BukkitUtil.getLocationFull(this.player); } - @Override - public void setWeather(PlotWeather weather) { + @Override public void setWeather(PlotWeather weather) { switch (weather) { case CLEAR: this.player.setPlayerWeather(WeatherType.CLEAR); @@ -212,9 +199,8 @@ public class BukkitPlayer extends PlotPlayer { break; } } - - @Override - public PlotGameMode getGameMode() { + + @Override public PlotGameMode getGameMode() { switch (this.player.getGameMode()) { case ADVENTURE: return PlotGameMode.ADVENTURE; @@ -228,9 +214,8 @@ public class BukkitPlayer extends PlotPlayer { return PlotGameMode.NOT_SET; } } - - @Override - public void setGameMode(PlotGameMode gameMode) { + + @Override public void setGameMode(PlotGameMode gameMode) { switch (gameMode) { case ADVENTURE: this.player.setGameMode(GameMode.ADVENTURE); @@ -249,34 +234,29 @@ public class BukkitPlayer extends PlotPlayer { break; } } - - @Override - public void setTime(long time) { + + @Override public void setTime(long time) { if (time != Long.MAX_VALUE) { this.player.setPlayerTime(time, false); } else { this.player.resetPlayerTime(); } } - - @Override - public void setFlight(boolean fly) { - this.player.setAllowFlight(fly); - } - @Override - public boolean getFlight() { + @Override public boolean getFlight() { return player.getAllowFlight(); } - @Override - public void playMusic(Location location, int id) { + @Override public void setFlight(boolean fly) { + this.player.setAllowFlight(fly); + } + + @Override public void playMusic(Location location, int id) { //noinspection deprecation this.player.playEffect(BukkitUtil.getLocation(location), Effect.RECORD_PLAY, id); } - - @Override - public void kick(String message) { + + @Override public void kick(String message) { this.player.kickPlayer(message); } @@ -286,8 +266,7 @@ public class BukkitPlayer extends PlotPlayer { } } - @Override - public boolean isBanned() { + @Override public boolean isBanned() { return this.player.isBanned(); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/AgeableStats.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/AgeableStats.java similarity index 52% rename from Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/AgeableStats.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/AgeableStats.java index a7016efb6..5769f0e46 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/AgeableStats.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/AgeableStats.java @@ -1,4 +1,4 @@ -package com.plotsquared.bukkit.object.entity; +package com.github.intellectualsites.plotsquared.bukkit.object.entity; class AgeableStats { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/ArmorStandStats.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/ArmorStandStats.java similarity index 83% rename from Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/ArmorStandStats.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/ArmorStandStats.java index e6331436c..56b36e2bb 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/ArmorStandStats.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/ArmorStandStats.java @@ -1,4 +1,4 @@ -package com.plotsquared.bukkit.object.entity; +package com.github.intellectualsites.plotsquared.bukkit.object.entity; class ArmorStandStats { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/EntityBaseStats.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/EntityBaseStats.java similarity index 67% rename from Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/EntityBaseStats.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/EntityBaseStats.java index 5a26d675f..d33b4d913 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/EntityBaseStats.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/EntityBaseStats.java @@ -1,4 +1,4 @@ -package com.plotsquared.bukkit.object.entity; +package com.github.intellectualsites.plotsquared.bukkit.object.entity; class EntityBaseStats { diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/EntityWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/EntityWrapper.java new file mode 100644 index 000000000..d0b6f28b5 --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/EntityWrapper.java @@ -0,0 +1,40 @@ +package com.github.intellectualsites.plotsquared.bukkit.object.entity; + +import lombok.Getter; +import lombok.NonNull; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; + +@Getter public abstract class EntityWrapper { + + protected final float yaw; + protected final float pitch; + private final Entity entity; + private final EntityType type; + public double x; + public double y; + public double z; + + EntityWrapper(@NonNull final Entity entity) { + this.entity = entity; + this.type = entity.getType(); + + final Location location = entity.getLocation(); + this.x = location.getX(); + this.y = location.getY(); + this.z = location.getZ(); + this.yaw = location.getYaw(); + this.pitch = location.getPitch(); + } + + @SuppressWarnings("deprecation") @Override public String toString() { + return String.format("[%s, x=%s, y=%s, z=%s]", type.getName(), x, y, z); + } + + public abstract Entity spawn(World world, int xOffset, int zOffset); + + public abstract void saveEntity(); + +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/HorseStats.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/HorseStats.java similarity index 69% rename from Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/HorseStats.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/HorseStats.java index 2253136d4..7fd976258 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/HorseStats.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/HorseStats.java @@ -1,4 +1,4 @@ -package com.plotsquared.bukkit.object.entity; +package com.github.intellectualsites.plotsquared.bukkit.object.entity; import org.bukkit.entity.Horse; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/LivingEntityStats.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/LivingEntityStats.java similarity index 88% rename from Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/LivingEntityStats.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/LivingEntityStats.java index 39e79c2b0..c702ffaa7 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/LivingEntityStats.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/LivingEntityStats.java @@ -1,4 +1,4 @@ -package com.plotsquared.bukkit.object.entity; +package com.github.intellectualsites.plotsquared.bukkit.object.entity; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/ReplicatingEntityWrapper.java similarity index 81% rename from Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/ReplicatingEntityWrapper.java index 33dc737ab..e71373771 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/EntityWrapper.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/ReplicatingEntityWrapper.java @@ -1,52 +1,21 @@ -package com.plotsquared.bukkit.object.entity; +package com.github.intellectualsites.plotsquared.bukkit.object.entity; -import com.intellectualcrafters.plot.PS; -import com.plotsquared.bukkit.util.BukkitVersion; -import org.bukkit.Art; -import org.bukkit.DyeColor; -import org.bukkit.Location; -import org.bukkit.Rotation; -import org.bukkit.TreeSpecies; -import org.bukkit.World; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import org.bukkit.*; import org.bukkit.block.BlockFace; -import org.bukkit.entity.Ageable; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Bat; -import org.bukkit.entity.Boat; -import org.bukkit.entity.EnderDragon; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Guardian; -import org.bukkit.entity.Horse; -import org.bukkit.entity.IronGolem; -import org.bukkit.entity.Item; -import org.bukkit.entity.ItemFrame; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Painting; -import org.bukkit.entity.Rabbit; -import org.bukkit.entity.Rabbit.Type; -import org.bukkit.entity.Sheep; -import org.bukkit.entity.Skeleton; -import org.bukkit.entity.Skeleton.SkeletonType; -import org.bukkit.entity.Slime; -import org.bukkit.entity.Tameable; +import org.bukkit.entity.*; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.util.EulerAngle; import org.bukkit.util.Vector; -public class EntityWrapper { +public final class ReplicatingEntityWrapper extends EntityWrapper { - private final EntityType type; - private final float yaw; - private final float pitch; private final short depth; private final int hash; private final EntityBaseStats base = new EntityBaseStats(); - public double x; - public double y; - public double z; + public ItemStack[] inventory; // Extended private ItemStack stack; @@ -60,22 +29,18 @@ public class EntityWrapper { private HorseStats horse; private boolean noGravity; - public EntityWrapper(Entity entity, short depth) { + public ReplicatingEntityWrapper(Entity entity, short depth) { + super(entity); + this.hash = entity.getEntityId(); this.depth = depth; - Location location = entity.getLocation(); - this.yaw = location.getYaw(); - this.pitch = location.getPitch(); - this.x = location.getX(); - this.y = location.getY(); - this.z = location.getZ(); - this.type = entity.getType(); + if (depth == 0) { return; } Entity passenger = entity.getPassenger(); if (passenger != null) { - this.base.passenger = new EntityWrapper(passenger, depth); + this.base.passenger = new ReplicatingEntityWrapper(passenger, depth); } this.base.fall = entity.getFallDistance(); this.base.fire = (short) entity.getFireTicks(); @@ -87,18 +52,15 @@ public class EntityWrapper { if (depth == 1) { return; } - if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_10_0) || entity instanceof ArmorStand) { - if (!entity.hasGravity()) { - this.noGravity = true; - } + if (!entity.hasGravity()) { + this.noGravity = true; } switch (entity.getType()) { - case ARROW: case BOAT: - if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_9_0)) { - Boat boat = (Boat) entity; - this.dataByte = getOrdinal(TreeSpecies.values(), boat.getWoodType()); - } + Boat boat = (Boat) entity; + this.dataByte = getOrdinal(TreeSpecies.values(), boat.getWoodType()); + return; + case ARROW: case COMPLEX_PART: case EGG: case ENDER_CRYSTAL: @@ -134,9 +96,6 @@ public class EntityWrapper { case AREA_EFFECT_CLOUD: // Do this stuff later return; - default: - PS.debug("&cCOULD NOT IDENTIFY ENTITY: " + entity.getType()); - return; // MISC // case DROPPED_ITEM: Item item = (Item) entity; @@ -210,7 +169,7 @@ public class EntityWrapper { storeLiving((LivingEntity) entity); return; case RABBIT: - this.dataByte = getOrdinal(Type.values(), ((Rabbit) entity).getRabbitType()); + this.dataByte = getOrdinal(Rabbit.Type.values(), ((Rabbit) entity).getRabbitType()); storeAgeable((Ageable) entity); storeLiving((LivingEntity) entity); return; @@ -220,13 +179,16 @@ public class EntityWrapper { storeLiving((LivingEntity) entity); return; case SKELETON: - this.dataByte = getOrdinal(SkeletonType.values(),((Skeleton)entity).getSkeletonType()); + this.dataByte = getOrdinal(Skeleton.SkeletonType.values(), + ((Skeleton) entity).getSkeletonType()); storeLiving((LivingEntity) entity); return; case ARMOR_STAND: ArmorStand stand = (ArmorStand) entity; - this.inventory = new ItemStack[]{stand.getItemInHand().clone(), stand.getHelmet().clone(), stand.getChestplate().clone(), - stand.getLeggings().clone(), stand.getBoots().clone()}; + this.inventory = + new ItemStack[] {stand.getItemInHand().clone(), stand.getHelmet().clone(), + stand.getChestplate().clone(), stand.getLeggings().clone(), + stand.getBoots().clone()}; storeLiving(stand); this.stand = new ArmorStandStats(); @@ -312,16 +274,16 @@ public class EntityWrapper { } storeLiving((LivingEntity) entity); // END LIVING // + default: + PlotSquared.debug("&cCOULD NOT IDENTIFY ENTITY: " + entity.getType()); } } - @Override - public boolean equals(Object obj) { + @Override public boolean equals(Object obj) { return this.hash == obj.hashCode(); } - @Override - public int hashCode() { + @Override public int hashCode() { return this.hash; } @@ -354,12 +316,8 @@ public class EntityWrapper { void restoreEquipment(LivingEntity entity) { EntityEquipment equipment = entity.getEquipment(); - if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_9_0)) { - equipment.setItemInMainHand(this.lived.mainHand); - equipment.setItemInOffHand(this.lived.offHand); - } else { - equipment.setItemInHand(this.lived.mainHand); - } + equipment.setItemInMainHand(this.lived.mainHand); + equipment.setItemInOffHand(this.lived.offHand); equipment.setHelmet(this.lived.helmet); equipment.setChestplate(this.lived.chestplate); equipment.setLeggings(this.lived.leggings); @@ -370,7 +328,7 @@ public class EntityWrapper { try { entity.getInventory().setContents(this.inventory); } catch (IllegalArgumentException e) { - PS.debug("&c[WARN] Failed to restore inventory.\n Reason: " + e.getMessage()); + PlotSquared.debug("&c[WARN] Failed to restore inventory.\n Reason: " + e.getMessage()); } } @@ -398,13 +356,8 @@ public class EntityWrapper { } void storeEquipment(EntityEquipment equipment) { - if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_9_0)) { - this.lived.mainHand = equipment.getItemInMainHand().clone(); - this.lived.offHand = equipment.getItemInOffHand().clone(); - } else { - this.lived.mainHand = equipment.getItemInHand().clone(); - this.lived.offHand = null; - } + this.lived.mainHand = equipment.getItemInMainHand().clone(); + this.lived.offHand = equipment.getItemInOffHand().clone(); this.lived.boots = equipment.getBoots().clone(); this.lived.leggings = equipment.getLeggings().clone(); this.lived.chestplate = equipment.getChestplate().clone(); @@ -443,15 +396,15 @@ public class EntityWrapper { this.tamed.tamed = tamed.isTamed(); } - public Entity spawn(World world, int xOffset, int zOffset) { + @Override public Entity spawn(World world, int xOffset, int zOffset) { Location location = new Location(world, this.x + xOffset, this.y, this.z + zOffset); location.setYaw(this.yaw); location.setPitch(this.pitch); - if (!this.type.isSpawnable()) { + if (!this.getType().isSpawnable()) { return null; } Entity entity; - switch (this.type) { + switch (this.getType()) { case DROPPED_ITEM: return world.dropItem(location, this.stack); case PLAYER: @@ -464,7 +417,7 @@ public class EntityWrapper { entity = world.spawn(location, Painting.class); break; default: - entity = world.spawnEntity(location, this.type); + entity = world.spawnEntity(location, this.getType()); break; } if (this.depth == 0) { @@ -473,7 +426,8 @@ public class EntityWrapper { if (this.base.passenger != null) { try { entity.setPassenger(this.base.passenger.spawn(world, xOffset, zOffset)); - } catch (Exception ignored) { } + } catch (Exception ignored) { + } } if (this.base.fall != 0) { entity.setFallDistance(this.base.fall); @@ -488,19 +442,18 @@ public class EntityWrapper { if (this.depth == 1) { return entity; } - if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_10_0) || entity instanceof ArmorStand) { - if (this.noGravity) { - entity.setGravity(false); - } + if (this.noGravity) { + entity.setGravity(false); } switch (entity.getType()) { - case ARROW: case BOAT: - if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_9_0)) { - Boat boat = (Boat) entity; - boat.setWoodType(TreeSpecies.values()[dataByte]); - } - + Boat boat = (Boat) entity; + boat.setWoodType(TreeSpecies.values()[dataByte]); + return entity; + case SLIME: + ((Slime) entity).setSize(this.dataByte); + return entity; + case ARROW: case COMPLEX_PART: case EGG: case ENDER_CRYSTAL: @@ -520,10 +473,6 @@ public class EntityWrapper { case MINECART_TNT: case PLAYER: case PRIMED_TNT: - return entity; - case SLIME: - ((Slime) entity).setSize(this.dataByte); - return entity; case SMALL_FIREBALL: case SNOWBALL: case SPLASH_POTION: @@ -540,9 +489,6 @@ public class EntityWrapper { case UNKNOWN: // Do this stuff later return entity; - default: - PS.debug("&cCOULD NOT IDENTIFY ENTITY: " + entity.getType()); - return entity; // MISC // case ITEM_FRAME: ItemFrame itemframe = (ItemFrame) entity; @@ -606,7 +552,7 @@ public class EntityWrapper { // END AGEABLE // case RABBIT: if (this.dataByte != 0) { - ((Rabbit) entity).setRabbitType(Type.values()[this.dataByte]); + ((Rabbit) entity).setRabbitType(Rabbit.Type.values()[this.dataByte]); } restoreAgeable((Ageable) entity); restoreLiving((LivingEntity) entity); @@ -619,7 +565,8 @@ public class EntityWrapper { return entity; case SKELETON: if (this.dataByte != 0) { - ((Skeleton) entity).setSkeletonType(SkeletonType.values()[this.dataByte]); + ((Skeleton) entity) + .setSkeletonType(Skeleton.SkeletonType.values()[this.dataByte]); } storeLiving((LivingEntity) entity); return entity; @@ -642,27 +589,37 @@ public class EntityWrapper { stand.setBoots(this.inventory[4]); } if (this.stand.head[0] != 0 || this.stand.head[1] != 0 || this.stand.head[2] != 0) { - EulerAngle pose = new EulerAngle(this.stand.head[0], this.stand.head[1], this.stand.head[2]); + EulerAngle pose = + new EulerAngle(this.stand.head[0], this.stand.head[1], this.stand.head[2]); stand.setHeadPose(pose); } if (this.stand.body[0] != 0 || this.stand.body[1] != 0 || this.stand.body[2] != 0) { - EulerAngle pose = new EulerAngle(this.stand.body[0], this.stand.body[1], this.stand.body[2]); + EulerAngle pose = + new EulerAngle(this.stand.body[0], this.stand.body[1], this.stand.body[2]); stand.setBodyPose(pose); } - if (this.stand.leftLeg[0] != 0 || this.stand.leftLeg[1] != 0 || this.stand.leftLeg[2] != 0) { - EulerAngle pose = new EulerAngle(this.stand.leftLeg[0], this.stand.leftLeg[1], this.stand.leftLeg[2]); + if (this.stand.leftLeg[0] != 0 || this.stand.leftLeg[1] != 0 + || this.stand.leftLeg[2] != 0) { + EulerAngle pose = new EulerAngle(this.stand.leftLeg[0], this.stand.leftLeg[1], + this.stand.leftLeg[2]); stand.setLeftLegPose(pose); } - if (this.stand.rightLeg[0] != 0 || this.stand.rightLeg[1] != 0 || this.stand.rightLeg[2] != 0) { - EulerAngle pose = new EulerAngle(this.stand.rightLeg[0], this.stand.rightLeg[1], this.stand.rightLeg[2]); + if (this.stand.rightLeg[0] != 0 || this.stand.rightLeg[1] != 0 + || this.stand.rightLeg[2] != 0) { + EulerAngle pose = new EulerAngle(this.stand.rightLeg[0], this.stand.rightLeg[1], + this.stand.rightLeg[2]); stand.setRightLegPose(pose); } - if (this.stand.leftArm[0] != 0 || this.stand.leftArm[1] != 0 || this.stand.leftArm[2] != 0) { - EulerAngle pose = new EulerAngle(this.stand.leftArm[0], this.stand.leftArm[1], this.stand.leftArm[2]); + if (this.stand.leftArm[0] != 0 || this.stand.leftArm[1] != 0 + || this.stand.leftArm[2] != 0) { + EulerAngle pose = new EulerAngle(this.stand.leftArm[0], this.stand.leftArm[1], + this.stand.leftArm[2]); stand.setLeftArmPose(pose); } - if (this.stand.rightArm[0] != 0 || this.stand.rightArm[1] != 0 || this.stand.rightArm[2] != 0) { - EulerAngle pose = new EulerAngle(this.stand.rightArm[0], this.stand.rightArm[1], this.stand.rightArm[2]); + if (this.stand.rightArm[0] != 0 || this.stand.rightArm[1] != 0 + || this.stand.rightArm[2] != 0) { + EulerAngle pose = new EulerAngle(this.stand.rightArm[0], this.stand.rightArm[1], + this.stand.rightArm[2]); stand.setRightArmPose(pose); } if (this.stand.invisible) { @@ -716,10 +673,16 @@ public class EntityWrapper { } restoreLiving((LivingEntity) entity); return entity; - // END LIVING + default: + PlotSquared.debug("&cCOULD NOT IDENTIFY ENTITY: " + entity.getType()); + return entity; + // END LIVING } } + public void saveEntity() { + } + private byte getOrdinal(Object[] list, Object value) { for (byte i = 0; i < list.length; i++) { if (list[i].equals(value)) { @@ -729,9 +692,5 @@ public class EntityWrapper { return 0; } - @SuppressWarnings("deprecation") - @Override - public String toString() { - return String.format("[%s, x=%s, y=%s, z=%s]", type.getName(), x, y, z); - } + } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/TameableStats.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/TameableStats.java similarity index 60% rename from Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/TameableStats.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/TameableStats.java index 217952e49..f9e8ded36 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/entity/TameableStats.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/TameableStats.java @@ -1,4 +1,4 @@ -package com.plotsquared.bukkit.object.entity; +package com.github.intellectualsites.plotsquared.bukkit.object.entity; import org.bukkit.entity.AnimalTamer; diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/TeleportEntityWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/TeleportEntityWrapper.java new file mode 100644 index 000000000..7456ae10e --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/TeleportEntityWrapper.java @@ -0,0 +1,93 @@ +package com.github.intellectualsites.plotsquared.bukkit.object.entity; + +import com.github.intellectualsites.plotsquared.bukkit.BukkitMain; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.metadata.FixedMetadataValue; + +public class TeleportEntityWrapper extends EntityWrapper { + + private Location oldLocation; + private boolean gravityOld; + private boolean invulnerableOld; + private int fireTicksOld; + private int livingTicksOld; + + public TeleportEntityWrapper(final Entity entity) { + super(entity); + } + + @Override public Entity spawn(final World world, final int xOffset, final int zOffset) { + if (!getEntity().getLocation().getChunk().equals(oldLocation.getChunk())) { + final Location oldLocation = this.oldLocation.clone(); + oldLocation.add(xOffset, 0, xOffset); + getEntity().teleport(oldLocation); + getEntity().setGravity(gravityOld); + getEntity().setInvulnerable(invulnerableOld); + getEntity().setFireTicks(fireTicksOld); + getEntity().setTicksLived(livingTicksOld); + getEntity().removeMetadata("ps-tmp-teleport", BukkitMain.getPlugin(BukkitMain.class)); + } + return getEntity(); + } + + @Override public void saveEntity() { + if (getEntity().hasMetadata("ps-tmp-teleport")) { + this.oldLocation = (Location) this.getEntity().getMetadata("ps-tmp-teleport").get(0); + } else { + this.oldLocation = this.getEntity().getLocation(); + } + + // To account for offsets in the chunk manager + this.oldLocation = oldLocation.clone(); + this.oldLocation.setX(this.x); + this.oldLocation.setY(this.y); + this.oldLocation.setZ(this.z); + + this.gravityOld = this.getEntity().hasGravity(); + this.getEntity().setGravity(false); + this.invulnerableOld = this.getEntity().isInvulnerable(); + this.getEntity().setInvulnerable(true); + this.fireTicksOld = this.getEntity().getFireTicks(); + this.livingTicksOld = this.getEntity().getTicksLived(); + this.getEntity().setMetadata("ps-tmp-teleport", + new FixedMetadataValue(BukkitMain.getPlugin(BukkitMain.class), oldLocation)); + final Chunk newChunk = getNewChunk(); + this.getEntity().teleport( + new Location(newChunk.getWorld(), newChunk.getX() << 4, 5000, newChunk.getZ() << 4)); + } + + private Chunk getNewChunk() { + final Chunk oldChunk = oldLocation.getChunk(); + Chunk chunk = null; + + for (Chunk lChunk : oldChunk.getWorld().getLoadedChunks()) { + if (!lChunk.equals(oldChunk) && lChunk.isLoaded()) { + chunk = lChunk; + break; + } + } + if (chunk == null) { + for (int dx = 1; dx < Integer.MAX_VALUE; dx++) { + for (int dz = 0; dz < Integer.MAX_VALUE; dz++) { + if ((chunk = getChunkRelative(oldChunk, dx, dz)).isLoaded()) { + break; + } else if ((chunk = getChunkRelative(oldChunk, -dx, dz)).isLoaded()) { + break; + } else if ((chunk = getChunkRelative(oldChunk, dx, -dz)).isLoaded()) { + break; + } else if ((chunk = getChunkRelative(oldChunk, -dx, -dz)).isLoaded()) { + break; + } + } + } + } + return chunk; + } + + private Chunk getChunkRelative(final Chunk chunk, final int dx, final int dz) { + return chunk.getWorld().getChunkAt(chunk.getX() + dx, chunk.getZ() + dz); + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/schematic/StateWrapper.java similarity index 63% rename from Bukkit/src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/schematic/StateWrapper.java index 3431e6b77..cfc84338a 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/schematic/StateWrapper.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/schematic/StateWrapper.java @@ -1,13 +1,8 @@ -package com.plotsquared.bukkit.object.schematic; +package com.github.intellectualsites.plotsquared.bukkit.object.schematic; -import com.intellectualcrafters.jnbt.ByteTag; -import com.intellectualcrafters.jnbt.CompoundTag; -import com.intellectualcrafters.jnbt.ListTag; -import com.intellectualcrafters.jnbt.ShortTag; -import com.intellectualcrafters.jnbt.Tag; -import com.intellectualcrafters.plot.object.schematic.ItemType; -import com.intellectualcrafters.plot.util.MathMan; -import com.plotsquared.bukkit.util.BukkitUtil; +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil; +import com.sk89q.jnbt.*; +import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockState; @@ -43,21 +38,14 @@ public class StateWrapper { case "chest": List itemsTag = this.tag.getListTag("Items").getValue(); int length = itemsTag.size(); - short[] ids = new short[length]; - byte[] datas = new byte[length]; + String[] ids = new String[length]; byte[] amounts = new byte[length]; byte[] slots = new byte[length]; for (int i = 0; i < length; i++) { Tag itemTag = itemsTag.get(i); CompoundTag itemComp = (CompoundTag) itemTag; - short id = itemComp.getShort("id"); - String idStr = itemComp.getString("id"); - if (idStr != null && !MathMan.isInteger(idStr)) { - idStr = idStr.split(":")[1].toLowerCase(); - id = (short) ItemType.getId(idStr); - } + String id = itemComp.getString("id"); ids[i] = id; - datas[i] = (byte) itemComp.getShort("Damage"); amounts[i] = itemComp.getByte("Count"); slots[i] = itemComp.getByte("Slot"); } @@ -71,7 +59,8 @@ public class StateWrapper { InventoryHolder holder = (InventoryHolder) state; Inventory inv = holder.getInventory(); for (int i = 0; i < ids.length; i++) { - ItemStack item = new ItemStack(ids[i], amounts[i], datas[i]); + ItemStack item = + new ItemStack(Material.getMaterial(ids[i]), (int) amounts[i]); inv.addItem(item); } state.update(true); @@ -89,7 +78,7 @@ public class StateWrapper { InventoryHolder inv = (InventoryHolder) this.state; ItemStack[] contents = inv.getInventory().getContents(); Map values = new HashMap<>(); - values.put("Items", new ListTag("Items", CompoundTag.class, serializeInventory(contents))); + values.put("Items", new ListTag(CompoundTag.class, serializeInventory(contents))); return new CompoundTag(values); } return null; @@ -104,41 +93,29 @@ public class StateWrapper { for (int i = 0; i < items.length; ++i) { if (items[i] != null) { Map tagData = serializeItem(items[i]); - tagData.put("Slot", new ByteTag("Slot", (byte) i)); + tagData.put("Slot", new ByteTag((byte) i)); tags.add(new CompoundTag(tagData)); } } return tags; } - /* - * TODO: Move this into the sponge module! - * - public Map serializeItem(final org.spongepowered.api.item.inventory.ItemStack item) { - final Map data = new HashMap(); - - // FIXME serialize sponge item - - return data; - } - */ - public Map serializeItem(ItemStack item) { Map data = new HashMap<>(); - 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())); + data.put("id", new StringTag(item.getType().name())); + data.put("Damage", new ShortTag(item.getDurability())); + data.put("Count", new ByteTag((byte) item.getAmount())); if (!item.getEnchantments().isEmpty()) { List enchantmentList = new ArrayList<>(); for (Entry entry : item.getEnchantments().entrySet()) { Map enchantment = new HashMap<>(); - enchantment.put("id", new ShortTag("id", (short) entry.getKey().getId())); - enchantment.put("lvl", new ShortTag("lvl", entry.getValue().shortValue())); + enchantment.put("id", new StringTag(entry.getKey().toString())); + enchantment.put("lvl", new ShortTag(entry.getValue().shortValue())); enchantmentList.add(new CompoundTag(enchantment)); } Map auxData = new HashMap<>(); - auxData.put("ench", new ListTag("ench", CompoundTag.class, enchantmentList)); - data.put("tag", new CompoundTag("tag", auxData)); + auxData.put("ench", new ListTag(CompoundTag.class, enchantmentList)); + data.put("tag", new CompoundTag(auxData)); } return data; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/DefaultTitleManager.java similarity index 66% rename from Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/DefaultTitleManager.java index 98ea32db9..a5447f9bf 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/DefaultTitleManager.java @@ -1,6 +1,6 @@ -package com.plotsquared.bukkit.titles; +package com.github.intellectualsites.plotsquared.bukkit.titles; -import com.plotsquared.bukkit.chat.Reflection; +import com.github.intellectualsites.plotsquared.bukkit.chat.Reflection; import org.bukkit.ChatColor; import org.bukkit.entity.Player; @@ -12,13 +12,14 @@ public class DefaultTitleManager extends TitleManager { /** * Create a new 1.8 title. * - * @param title Title text - * @param subtitle Subtitle text - * @param fadeInTime Fade in time - * @param stayTime Stay on screen time + * @param title Title text + * @param subtitle Subtitle text + * @param fadeInTime Fade in time + * @param stayTime Stay on screen time * @param fadeOutTime Fade out time */ - DefaultTitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) { + DefaultTitleManager(String title, String subtitle, int fadeInTime, int stayTime, + int fadeOutTime) { super(title, subtitle, fadeInTime, stayTime, fadeOutTime); } @@ -32,7 +33,8 @@ public class DefaultTitleManager extends TitleManager { this.nmsChatSerializer = Reflection.getNMSClass("ChatSerializer"); } - @Override public void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException { + @Override public void send(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException { if (this.packetTitle != null) { // First reset previous settings resetTitle(player); @@ -41,38 +43,44 @@ public class DefaultTitleManager extends TitleManager { Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object[] actions = this.packetActions.getEnumConstants(); Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE) - .newInstance(actions[2], null, this.fadeInTime * (this.ticks ? 1 : 20), - this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime * (this.ticks ? 1 : 20)); + Object packet = this.packetTitle + .getConstructor(this.packetActions, this.chatBaseComponent, Integer.TYPE, + Integer.TYPE, Integer.TYPE) + .newInstance(actions[2], null, this.fadeInTime * (this.ticks ? 1 : 20), + this.stayTime * (this.ticks ? 1 : 20), + this.fadeOutTime * (this.ticks ? 1 : 20)); // Send if set if (this.fadeInTime != -1 && this.fadeOutTime != -1 && this.stayTime != -1) { sendPacket.invoke(connection, packet); } // Send title Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, - "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + "\",color:" + this.titleColor.name().toLowerCase() - + '}'); - packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[0], serialized); + "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + + "\",color:" + this.titleColor.name().toLowerCase() + '}'); + packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent) + .newInstance(actions[0], serialized); sendPacket.invoke(connection, packet); if (!this.getSubtitle().isEmpty()) { // Send subtitle if present serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, - "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + "\",color:" + this.subtitleColor.name() - .toLowerCase() + '}'); - packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[1], serialized); + "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + + "\",color:" + this.subtitleColor.name().toLowerCase() + '}'); + packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent) + .newInstance(actions[1], serialized); sendPacket.invoke(connection, packet); } } } - @Override - public void clearTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException { + @Override public void clearTitle(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException { // Send timings first Object handle = getHandle(player); Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object[] actions = this.packetActions.getEnumConstants(); Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[3], null); + Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent) + .newInstance(actions[3], null); sendPacket.invoke(connection, packet); } @@ -84,14 +92,15 @@ public class DefaultTitleManager extends TitleManager { * @throws ReflectiveOperationException * @throws SecurityException */ - @Override - public void resetTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException { + @Override public void resetTitle(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException { // Send timings first Object handle = getHandle(player); Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object[] actions = this.packetActions.getEnumConstants(); Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[4], null); + Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent) + .newInstance(actions[4], null); sendPacket.invoke(connection, packet); } @@ -108,7 +117,8 @@ public class DefaultTitleManager extends TitleManager { Method getMethod(Class clazz, String name, Class... args) { for (Method m : clazz.getMethods()) { - if (m.getName().equals(name) && (args.length == 0 || classListEqual(args, m.getParameterTypes()))) { + if (m.getName().equals(name) && (args.length == 0 || classListEqual(args, + m.getParameterTypes()))) { m.setAccessible(true); return m; } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/DefaultTitle_111.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/DefaultTitle_111.java new file mode 100644 index 000000000..c0d176019 --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/DefaultTitle_111.java @@ -0,0 +1,20 @@ +package com.github.intellectualsites.plotsquared.bukkit.titles; + +import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.AbstractTitle; +import org.bukkit.entity.Player; + +@SuppressWarnings("deprecation") public class DefaultTitle_111 extends AbstractTitle { + + @Override + public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) { + try { + final Player playerObj = ((BukkitPlayer) player).player; + TitleManager_1_11 title = new TitleManager_1_11(head, sub, in, delay, out); + title.send(playerObj); + return; + } catch (Throwable ignored) { + } + } +} diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/HackTitle.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/HackTitle.java new file mode 100644 index 000000000..ae2b50a60 --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/HackTitle.java @@ -0,0 +1,22 @@ +package com.github.intellectualsites.plotsquared.bukkit.titles; + +import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.AbstractTitle; + +public class HackTitle extends AbstractTitle { + + @Override + public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) { + try { + HackTitleManager title = new HackTitleManager(head, sub, in, delay, out); + title.send(((BukkitPlayer) player).player); + } catch (Exception ignored) { + PlotSquared.debug("&cYour server version does not support titles!"); + Settings.TITLES = false; + AbstractTitle.TITLE_CLASS = null; + } + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/HackTitleManager.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/HackTitleManager.java similarity index 67% rename from Bukkit/src/main/java/com/plotsquared/bukkit/titles/HackTitleManager.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/HackTitleManager.java index cf8e87b95..2ec197927 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/HackTitleManager.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/HackTitleManager.java @@ -1,6 +1,6 @@ -package com.plotsquared.bukkit.titles; +package com.github.intellectualsites.plotsquared.bukkit.titles; -import com.plotsquared.bukkit.chat.Reflection; +import com.github.intellectualsites.plotsquared.bukkit.chat.Reflection; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; @@ -13,10 +13,10 @@ public class HackTitleManager extends TitleManager { /** * Create a new 1.8 title. * - * @param title Title text - * @param subtitle Subtitle text - * @param fadeInTime Fade in time - * @param stayTime Stay on screen time + * @param title Title text + * @param subtitle Subtitle text + * @param fadeInTime Fade in time + * @param stayTime Stay on screen time * @param fadeOutTime Fade out time */ HackTitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) { @@ -26,14 +26,14 @@ public class HackTitleManager extends TitleManager { /** * Load spigot and NMS classes. */ - @Override - void loadClasses() { + @Override void loadClasses() { this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle"); this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action"); this.nmsChatSerializer = Reflection.getNMSClass("ChatSerializer"); } - @Override public void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException { + @Override public void send(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException { if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) { // First reset previous settings resetTitle(player); @@ -42,8 +42,9 @@ public class HackTitleManager extends TitleManager { Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object[] actions = this.packetActions.getEnumConstants(); Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = this.packetTitle.getConstructor(this.packetActions, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], - this.fadeInTime * (this.ticks ? 1 : 20), + Object packet = this.packetTitle + .getConstructor(this.packetActions, Integer.TYPE, Integer.TYPE, Integer.TYPE) + .newInstance(actions[2], this.fadeInTime * (this.ticks ? 1 : 20), this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime * (this.ticks ? 1 : 20)); // Send if set @@ -52,43 +53,49 @@ public class HackTitleManager extends TitleManager { } // Send title Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, - "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + "\",color:" + this.titleColor.name().toLowerCase() - + "}"); - packet = this.packetTitle.getConstructor(this.packetActions, Reflection.getNMSClass("IChatBaseComponent")) - .newInstance(actions[0], serialized); + "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + + "\",color:" + this.titleColor.name().toLowerCase() + "}"); + packet = this.packetTitle + .getConstructor(this.packetActions, Reflection.getNMSClass("IChatBaseComponent")) + .newInstance(actions[0], serialized); sendPacket.invoke(connection, packet); if (!this.getSubtitle().isEmpty()) { // Send subtitle if present serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, - "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + "\",color:" + this.subtitleColor.name() - .toLowerCase() + "}"); - packet = this.packetTitle.getConstructor(this.packetActions, Reflection.getNMSClass("IChatBaseComponent")) - .newInstance(actions[1], serialized); + "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + + "\",color:" + this.subtitleColor.name().toLowerCase() + "}"); + packet = this.packetTitle.getConstructor(this.packetActions, + Reflection.getNMSClass("IChatBaseComponent")) + .newInstance(actions[1], serialized); sendPacket.invoke(connection, packet); } } } - @Override public void clearTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException { + @Override public void clearTitle(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException { if ((getProtocolVersion(player) >= 47) && isSpigot()) { // Send timings first Object handle = getHandle(player); Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object[] actions = this.packetActions.getEnumConstants(); Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[3]); + Object packet = + this.packetTitle.getConstructor(this.packetActions).newInstance(actions[3]); sendPacket.invoke(connection, packet); } } - @Override public void resetTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException { + @Override public void resetTitle(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException { if ((getProtocolVersion(player) >= 47) && isSpigot()) { // Send timings first Object handle = getHandle(player); Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object[] actions = this.packetActions.getEnumConstants(); Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[4]); + Object packet = + this.packetTitle.getConstructor(this.packetActions).newInstance(actions[4]); sendPacket.invoke(connection, packet); } } @@ -102,7 +109,8 @@ public class HackTitleManager extends TitleManager { * @throws ReflectiveOperationException * @throws SecurityException */ - private int getProtocolVersion(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException { + private int getProtocolVersion(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException { Object handle = getHandle(player); Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object networkManager = getValue("networkManager", connection); @@ -127,15 +135,18 @@ public class HackTitleManager extends TitleManager { private Class getClass(String namespace) { try { return Class.forName(namespace); - } catch (ClassNotFoundException ignored) {} + } catch (ClassNotFoundException ignored) { + } return null; } - private Field getField(String name, Class clazz) throws NoSuchFieldException, SecurityException { + private Field getField(String name, Class clazz) + throws NoSuchFieldException, SecurityException { return clazz.getDeclaredField(name); } - private Object getValue(String name, Object obj) throws ReflectiveOperationException, SecurityException, IllegalArgumentException { + private Object getValue(String name, Object obj) + throws ReflectiveOperationException, SecurityException, IllegalArgumentException { Field f = getField(name, obj.getClass()); f.setAccessible(true); return f.get(obj); @@ -154,7 +165,8 @@ public class HackTitleManager extends TitleManager { private Method getMethod(Class clazz, String name, Class... args) { for (Method m : clazz.getMethods()) { - if (m.getName().equals(name) && ((args.length == 0) || classListEqual(args, m.getParameterTypes()))) { + if (m.getName().equals(name) && ((args.length == 0) || classListEqual(args, + m.getParameterTypes()))) { m.setAccessible(true); return m; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/TitleManager.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager.java similarity index 87% rename from Bukkit/src/main/java/com/plotsquared/bukkit/titles/TitleManager.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager.java index 91a5d68a0..f4c249f97 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/TitleManager.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager.java @@ -1,4 +1,4 @@ -package com.plotsquared.bukkit.titles; +package com.github.intellectualsites.plotsquared.bukkit.titles; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -12,17 +12,13 @@ import java.util.Map; public abstract class TitleManager { private static final Map, Class> CORRESPONDING_TYPES = new HashMap<>(); - /* Title packet */ - Class packetTitle; - /* Title packet actions ENUM */ - Class packetActions; - /* Chat serializer */ - Class nmsChatSerializer; + /* Title packet */ Class packetTitle; + /* Title packet actions ENUM */ Class packetActions; + /* Chat serializer */ Class nmsChatSerializer; Class chatBaseComponent; ChatColor titleColor = ChatColor.WHITE; ChatColor subtitleColor = ChatColor.WHITE; - /* Title timings */ - int fadeInTime = -1; + /* Title timings */ int fadeInTime = -1; int stayTime = -1; int fadeOutTime = -1; boolean ticks = false; @@ -34,10 +30,10 @@ public abstract class TitleManager { /** * Create a new 1.8 title. * - * @param title Title text - * @param subtitle Subtitle text - * @param fadeInTime Fade in time - * @param stayTime Stay on screen time + * @param title Title text + * @param subtitle Subtitle text + * @param fadeInTime Fade in time + * @param stayTime Stay on screen time * @param fadeOutTime Fade out time */ TitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) { @@ -154,7 +150,8 @@ public abstract class TitleManager { * @throws ReflectiveOperationException * @throws SecurityException */ - public abstract void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException; + public abstract void send(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException; /** * Broadcasts the title to all players. @@ -175,7 +172,8 @@ public abstract class TitleManager { * @throws ReflectiveOperationException * @throws SecurityException */ - public abstract void clearTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException; + public abstract void clearTitle(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException; /** * Resets the title settings. @@ -185,7 +183,8 @@ public abstract class TitleManager { * @throws ReflectiveOperationException * @throws SecurityException */ - public abstract void resetTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException; + public abstract void resetTitle(Player player) + throws IllegalArgumentException, ReflectiveOperationException, SecurityException; private Class getPrimitiveType(Class clazz) { if (CORRESPONDING_TYPES.containsKey(clazz)) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/TitleManager_1_11.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager_1_11.java similarity index 78% rename from Bukkit/src/main/java/com/plotsquared/bukkit/titles/TitleManager_1_11.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager_1_11.java index 935f3d850..92155ba45 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/TitleManager_1_11.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager_1_11.java @@ -1,14 +1,14 @@ -package com.plotsquared.bukkit.titles; +package com.github.intellectualsites.plotsquared.bukkit.titles; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - /** * Minecraft 1.8 Title * For 1.11 @@ -17,6 +17,8 @@ import org.bukkit.entity.Player; * @version 1.1.0 */ public class TitleManager_1_11 { + private static final Map, Class> CORRESPONDING_TYPES = + new HashMap, Class>(); /* Title packet */ private static Class packetTitle; /* Title packet actions ENUM */ @@ -43,8 +45,6 @@ public class TitleManager_1_11 { private int fadeOutTime = -1; private boolean ticks = false; - private static final Map, Class> CORRESPONDING_TYPES = new HashMap, Class>(); - public TitleManager_1_11() { loadClasses(); } @@ -98,7 +98,8 @@ public class TitleManager_1_11 { * @param stayTime Stay on screen time * @param fadeOutTime Fade out time */ - public TitleManager_1_11(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) { + public TitleManager_1_11(String title, String subtitle, int fadeInTime, int stayTime, + int fadeOutTime) { this.title = title; this.subtitle = subtitle; this.fadeInTime = fadeInTime; @@ -107,6 +108,15 @@ public class TitleManager_1_11 { loadClasses(); } + private static boolean equalsTypeArray(Class[] a, Class[] o) { + if (a.length != o.length) + return false; + for (int i = 0; i < a.length; i++) + if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) + return false; + return true; + } + /** * Load spigot and NMS classes */ @@ -118,23 +128,13 @@ public class TitleManager_1_11 { nmsChatSerializer = getNMSClass("ChatComponentText"); nmsPlayer = getNMSClass("EntityPlayer"); nmsPlayerConnection = getNMSClass("PlayerConnection"); - playerConnection = getField(nmsPlayer, - "playerConnection"); + playerConnection = getField(nmsPlayer, "playerConnection"); sendPacket = getMethod(nmsPlayerConnection, "sendPacket"); obcPlayer = getOBCClass("entity.CraftPlayer"); methodPlayerGetHandle = getMethod("getHandle", obcPlayer); } } - /** - * Set title text - * - * @param title Title - */ - public void setTitle(String title) { - this.title = title; - } - /** * Get title text * @@ -145,12 +145,12 @@ public class TitleManager_1_11 { } /** - * Set subtitle text + * Set title text * - * @param subtitle Subtitle text + * @param title Title */ - public void setSubtitle(String subtitle) { - this.subtitle = subtitle; + public void setTitle(String title) { + this.title = title; } /** @@ -163,48 +163,12 @@ public class TitleManager_1_11 { } /** - * Set the title color + * Set subtitle text * - * @param color Chat color + * @param subtitle Subtitle text */ - public void setTitleColor(ChatColor color) { - this.titleColor = color; - } - - /** - * Set the subtitle color - * - * @param color Chat color - */ - public void setSubtitleColor(ChatColor color) { - this.subtitleColor = color; - } - - /** - * Set title fade in time - * - * @param time Time - */ - public void setFadeInTime(int time) { - this.fadeInTime = time; - } - - /** - * Set title fade out time - * - * @param time Time - */ - public void setFadeOutTime(int time) { - this.fadeOutTime = time; - } - - /** - * Set title stay time - * - * @param time Time - */ - public void setStayTime(int time) { - this.stayTime = time; + public void setSubtitle(String subtitle) { + this.subtitle = subtitle; } /** @@ -235,12 +199,10 @@ public class TitleManager_1_11 { Object handle = getHandle(player); Object connection = playerConnection.get(handle); Object[] actions = packetActions.getEnumConstants(); - Object packet = packetTitle.getConstructor(packetActions, - chatBaseComponent, Integer.TYPE, Integer.TYPE, - Integer.TYPE).newInstance(actions[3], null, - fadeInTime * (ticks ? 1 : 20), - stayTime * (ticks ? 1 : 20), - fadeOutTime * (ticks ? 1 : 20)); + Object packet = packetTitle + .getConstructor(packetActions, chatBaseComponent, Integer.TYPE, Integer.TYPE, + Integer.TYPE).newInstance(actions[3], null, fadeInTime * (ticks ? 1 : 20), + stayTime * (ticks ? 1 : 20), fadeOutTime * (ticks ? 1 : 20)); // Send if set if (fadeInTime != -1 && fadeOutTime != -1 && stayTime != -1) sendPacket.invoke(connection, packet); @@ -248,22 +210,18 @@ public class TitleManager_1_11 { Object serialized; if (!subtitle.equals("")) { // Send subtitle if present - serialized = nmsChatSerializer.getConstructor(String.class) - .newInstance(subtitleColor + - ChatColor.translateAlternateColorCodes('&', - subtitle)); - packet = packetTitle.getConstructor(packetActions, - chatBaseComponent).newInstance(actions[1], - serialized); + serialized = nmsChatSerializer.getConstructor(String.class).newInstance( + subtitleColor + ChatColor.translateAlternateColorCodes('&', subtitle)); + packet = packetTitle.getConstructor(packetActions, chatBaseComponent) + .newInstance(actions[1], serialized); sendPacket.invoke(connection, packet); } // Send title - serialized = nmsChatSerializer.getConstructor( - String.class).newInstance(titleColor + - ChatColor.translateAlternateColorCodes('&', title)); - packet = packetTitle.getConstructor(packetActions, - chatBaseComponent).newInstance(actions[0], serialized); + serialized = nmsChatSerializer.getConstructor(String.class) + .newInstance(titleColor + ChatColor.translateAlternateColorCodes('&', title)); + packet = packetTitle.getConstructor(packetActions, chatBaseComponent) + .newInstance(actions[0], serialized); sendPacket.invoke(connection, packet); } catch (Exception e) { e.printStackTrace(); @@ -278,19 +236,12 @@ public class TitleManager_1_11 { Object connection = playerConnection.get(handle); Object[] actions = TitleManager_1_11.packetActions.getEnumConstants(); Object packet = TitleManager_1_11.packetTitle.getConstructor( - new Class[]{TitleManager_1_11.packetActions, chatBaseComponent, - Integer.TYPE, Integer.TYPE, Integer.TYPE}) - .newInstance( - actions[3], - null, - this.fadeInTime - * (this.ticks ? 1 : 20), - this.stayTime - * (this.ticks ? 1 : 20), - this.fadeOutTime - * (this.ticks ? 1 : 20)); - if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) - && (this.stayTime != -1)) { + new Class[] {TitleManager_1_11.packetActions, chatBaseComponent, Integer.TYPE, + Integer.TYPE, Integer.TYPE}) + .newInstance(actions[3], null, this.fadeInTime * (this.ticks ? 1 : 20), + this.stayTime * (this.ticks ? 1 : 20), + this.fadeOutTime * (this.ticks ? 1 : 20)); + if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) { sendPacket.invoke(connection, packet); } } catch (Exception e) { @@ -303,21 +254,14 @@ public class TitleManager_1_11 { if (TitleManager_1_11.packetTitle != null) { try { Object handle = getHandle(player); - Object connection = getField(handle.getClass(), - "playerConnection").get(handle); + Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object[] actions = TitleManager_1_11.packetActions.getEnumConstants(); - Method sendPacket = getMethod(connection.getClass(), - "sendPacket"); - Object serialized = nmsChatSerializer.getConstructor( - String.class) - .newInstance(titleColor + - ChatColor.translateAlternateColorCodes('&', - this.title)); - Object packet = TitleManager_1_11.packetTitle - .getConstructor( - new Class[]{TitleManager_1_11.packetActions, - chatBaseComponent}).newInstance( - actions[0], serialized); + Method sendPacket = getMethod(connection.getClass(), "sendPacket"); + Object serialized = nmsChatSerializer.getConstructor(String.class).newInstance( + titleColor + ChatColor.translateAlternateColorCodes('&', this.title)); + Object packet = TitleManager_1_11.packetTitle.getConstructor( + new Class[] {TitleManager_1_11.packetActions, chatBaseComponent}) + .newInstance(actions[0], serialized); sendPacket.invoke(connection, packet); } catch (Exception e) { e.printStackTrace(); @@ -331,16 +275,11 @@ public class TitleManager_1_11 { Object handle = getHandle(player); Object connection = playerConnection.get(handle); Object[] actions = TitleManager_1_11.packetActions.getEnumConstants(); - Object serialized = nmsChatSerializer.getConstructor( - String.class) - .newInstance(subtitleColor + - ChatColor.translateAlternateColorCodes('&', - this.subtitle)); - Object packet = TitleManager_1_11.packetTitle - .getConstructor( - new Class[]{TitleManager_1_11.packetActions, - chatBaseComponent}).newInstance( - actions[1], serialized); + Object serialized = nmsChatSerializer.getConstructor(String.class).newInstance( + subtitleColor + ChatColor.translateAlternateColorCodes('&', this.subtitle)); + Object packet = TitleManager_1_11.packetTitle.getConstructor( + new Class[] {TitleManager_1_11.packetActions, chatBaseComponent}) + .newInstance(actions[1], serialized); sendPacket.invoke(connection, packet); } catch (Exception e) { e.printStackTrace(); @@ -368,8 +307,8 @@ public class TitleManager_1_11 { Object handle = getHandle(player); Object connection = playerConnection.get(handle); Object[] actions = packetActions.getEnumConstants(); - Object packet = packetTitle.getConstructor(packetActions, - chatBaseComponent).newInstance(actions[4], null); + Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent) + .newInstance(actions[4], null); sendPacket.invoke(connection, packet); } catch (Exception e) { e.printStackTrace(); @@ -387,8 +326,8 @@ public class TitleManager_1_11 { Object handle = getHandle(player); Object connection = playerConnection.get(handle); Object[] actions = packetActions.getEnumConstants(); - Object packet = packetTitle.getConstructor(packetActions, - chatBaseComponent).newInstance(actions[5], null); + Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent) + .newInstance(actions[5], null); sendPacket.invoke(connection, packet); } catch (Exception e) { e.printStackTrace(); @@ -396,8 +335,7 @@ public class TitleManager_1_11 { } private Class getPrimitiveType(Class clazz) { - return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES - .get(clazz) : clazz; + return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz; } private Class[] toPrimitiveTypeArray(Class[] classes) { @@ -408,15 +346,6 @@ public class TitleManager_1_11 { return types; } - private static boolean equalsTypeArray(Class[] a, Class[] o) { - if (a.length != o.length) - return false; - for (int i = 0; i < a.length; i++) - if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) - return false; - return true; - } - private Object getHandle(Player player) { try { return methodPlayerGetHandle.invoke(player); @@ -426,8 +355,7 @@ public class TitleManager_1_11 { } } - private Method getMethod(String name, Class clazz, - Class... paramTypes) { + private Method getMethod(String name, Class clazz, Class... paramTypes) { Class[] t = toPrimitiveTypeArray(paramTypes); for (Method m : clazz.getMethods()) { Class[] types = toPrimitiveTypeArray(m.getParameterTypes()); @@ -465,7 +393,6 @@ public class TitleManager_1_11 { return clazz; } - private Field getField(Class clazz, String name) { try { Field field = clazz.getDeclaredField(name); @@ -479,9 +406,8 @@ public class TitleManager_1_11 { private Method getMethod(Class clazz, String name, Class... args) { for (Method m : clazz.getMethods()) - if (m.getName().equals(name) - && (args.length == 0 || ClassListEqual(args, - m.getParameterTypes()))) { + if (m.getName().equals(name) && (args.length == 0 || ClassListEqual(args, + m.getParameterTypes()))) { m.setAccessible(true); return m; } @@ -504,23 +430,68 @@ public class TitleManager_1_11 { return titleColor; } + /** + * Set the title color + * + * @param color Chat color + */ + public void setTitleColor(ChatColor color) { + this.titleColor = color; + } + public ChatColor getSubtitleColor() { return subtitleColor; } + /** + * Set the subtitle color + * + * @param color Chat color + */ + public void setSubtitleColor(ChatColor color) { + this.subtitleColor = color; + } + public int getFadeInTime() { return fadeInTime; } + /** + * Set title fade in time + * + * @param time Time + */ + public void setFadeInTime(int time) { + this.fadeInTime = time; + } + public int getFadeOutTime() { return fadeOutTime; } + /** + * Set title fade out time + * + * @param time Time + */ + public void setFadeOutTime(int time) { + this.fadeOutTime = time; + } + public int getStayTime() { return stayTime; } + /** + * Set title stay time + * + * @param time Time + */ + public void setStayTime(int time) { + this.stayTime = time; + } + public boolean isTicks() { return ticks; } -} \ No newline at end of file +} diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitBlockRegistry.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitBlockRegistry.java new file mode 100644 index 000000000..b5ac5f1fb --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitBlockRegistry.java @@ -0,0 +1,18 @@ +package com.github.intellectualsites.plotsquared.bukkit.util; + +import com.github.intellectualsites.plotsquared.plot.object.BlockRegistry; +import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; +import lombok.NonNull; +import org.bukkit.Material; + +public class BukkitBlockRegistry extends BlockRegistry { + + public BukkitBlockRegistry(final Material... preInitializedItems) { + super(Material.class, preInitializedItems); + } + + @Override public PlotBlock getPlotBlock(@NonNull final Material item) { + return PlotBlock.get(item.name()); + } + +} diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitChatManager.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitChatManager.java new file mode 100644 index 000000000..a133d9630 --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitChatManager.java @@ -0,0 +1,54 @@ +package com.github.intellectualsites.plotsquared.bukkit.util; + +import com.github.intellectualsites.plotsquared.bukkit.chat.FancyMessage; +import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.object.ConsolePlayer; +import com.github.intellectualsites.plotsquared.plot.object.PlotMessage; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.ChatManager; +import org.bukkit.ChatColor; + +import java.util.ArrayList; +import java.util.List; + +public class BukkitChatManager extends ChatManager { + + @Override public FancyMessage builder() { + return new FancyMessage(""); + } + + @Override public void color(PlotMessage message, String color) { + message.$(this).color(ChatColor.getByChar(C.color(color).substring(1))); + } + + @Override public void tooltip(PlotMessage message, PlotMessage... tooltips) { + List lines = new ArrayList<>(); + for (PlotMessage tooltip : tooltips) { + lines.add(tooltip.$(this)); + } + message.$(this).formattedTooltip(lines); + } + + @Override public void command(PlotMessage message, String command) { + message.$(this).command(command); + } + + @Override public void text(PlotMessage message, String text) { + message.$(this).then(ChatColor.stripColor(text)); + } + + @Override public void send(PlotMessage plotMessage, PlotPlayer player) { + if (player instanceof ConsolePlayer || !Settings.Chat.INTERACTIVE) { + player.sendMessage(plotMessage.$(this).toOldMessageFormat()); + } else { + plotMessage.$(this).send(((BukkitPlayer) player).player); + } + } + + @Override public void suggest(PlotMessage plotMessage, String command) { + plotMessage.$(this).suggest(command); + } + +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitChunkManager.java similarity index 65% rename from Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitChunkManager.java index e39ab5f4e..32d067e70 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitChunkManager.java @@ -1,62 +1,25 @@ -package com.plotsquared.bukkit.util; +package com.github.intellectualsites.plotsquared.bukkit.util; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.generator.AugmentedUtils; -import com.intellectualcrafters.plot.object.BlockLoc; -import com.intellectualcrafters.plot.object.ChunkLoc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotBlock; -import com.intellectualcrafters.plot.object.PlotLoc; -import com.intellectualcrafters.plot.object.RegionWrapper; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.block.GlobalBlockQueue; -import com.intellectualcrafters.plot.util.block.LocalBlockQueue; -import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue; -import com.plotsquared.bukkit.object.entity.EntityWrapper; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.DyeColor; -import org.bukkit.Material; -import org.bukkit.Note; -import org.bukkit.SkullType; -import org.bukkit.World; -import org.bukkit.block.Banner; -import org.bukkit.block.Beacon; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.BlockState; -import org.bukkit.block.BrewingStand; -import org.bukkit.block.CommandBlock; -import org.bukkit.block.CreatureSpawner; -import org.bukkit.block.Dispenser; -import org.bukkit.block.Dropper; -import org.bukkit.block.Furnace; -import org.bukkit.block.Hopper; -import org.bukkit.block.Jukebox; -import org.bukkit.block.NoteBlock; -import org.bukkit.block.Sign; -import org.bukkit.block.Skull; +import com.github.intellectualsites.plotsquared.bukkit.object.entity.EntityWrapper; +import com.github.intellectualsites.plotsquared.bukkit.object.entity.ReplicatingEntityWrapper; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.generator.AugmentedUtils; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue; +import org.bukkit.*; +import org.bukkit.block.*; import org.bukkit.block.banner.Pattern; -import org.bukkit.entity.Animals; -import org.bukkit.entity.Creature; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; +import org.bukkit.block.data.BlockData; +import org.bukkit.entity.*; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Set; public class BukkitChunkManager extends ChunkManager { @@ -73,7 +36,8 @@ public class BukkitChunkManager extends ChunkManager { return 0; } - public static ContentMap swapChunk(World world1, World world2, Chunk pos1, Chunk pos2, RegionWrapper r1, RegionWrapper r2) { + public static ContentMap swapChunk(World world1, World world2, Chunk pos1, Chunk pos2, + RegionWrapper r1, RegionWrapper r2) { ContentMap map = new ContentMap(); int relX = r2.minX - r1.minX; int relZ = r2.minZ - r1.minZ; @@ -95,29 +59,35 @@ public class BukkitChunkManager extends ChunkManager { map.saveBlocks(world1, 256, sx, sz, relX, relZ, false); for (int y = 0; y < 256; y++) { Block block1 = world1.getBlockAt(x, y, z); - int id1 = block1.getTypeId(); - byte data1 = block1.getData(); + // int id1 = block1.getTypeId(); + Material id1 = block1.getType(); + BlockData data1 = block1.getBlockData(); + // byte data1 = block1.getData(); int xx = x + relX; int zz = z + relZ; Block block2 = world2.getBlockAt(xx, y, zz); - int id2 = block2.getTypeId(); - byte data2 = block2.getData(); - if (id1 == 0) { - if (id2 != 0) { - queue1.setBlock(x, y, z, (short) id2, data2); + // int id2 = block2.getTypeId(); + Material id2 = block2.getType(); + BlockData data2 = block2.getBlockData(); + // byte data2 = block2.getData(); + if (id1 == Material.AIR) { + if (id2 != Material.AIR) { + queue1.setBlock(x, y, z, id2.name()); queue2.setBlock(xx, y, zz, (short) 0, (byte) 0); } - } else if (id2 == 0) { + } else if (id2 == Material.AIR) { queue1.setBlock(x, y, z, (short) 0, (byte) 0); - queue2.setBlock(xx, y, zz, (short) id1, data1); + queue2.setBlock(xx, y, zz, id1.name()); } else if (id1 == id2) { if (data1 != data2) { - block1.setData(data2); - block2.setData(data1); + block1.setBlockData(data2); + block2.setBlockData(data1); } } else { - queue1.setBlock(x, y, z, (short) id2, data2); - queue2.setBlock(xx, y, zz, (short) id1, data1); + queue1.setBlock(x, y, z, id2.name()); + queue2.setBlock(xx, y, zz, id1.name()); + // queue1.setBlock(x, y, z, (short) id2, data2); + // queue2.setBlock(xx, y, zz, (short) id1, data1); } } } @@ -127,8 +97,7 @@ public class BukkitChunkManager extends ChunkManager { return map; } - @Override - public Set getChunkChunks(String world) { + @Override public Set getChunkChunks(String world) { Set chunks = super.getChunkChunks(world); for (Chunk chunk : Bukkit.getWorld(world).getLoadedChunks()) { ChunkLoc loc = new ChunkLoc(chunk.getX() >> 5, chunk.getZ() >> 5); @@ -140,12 +109,18 @@ public class BukkitChunkManager extends ChunkManager { } @Override - public boolean copyRegion(Location pos1, Location pos2, Location newPos, final Runnable whenDone) { + public boolean copyRegion(com.github.intellectualsites.plotsquared.plot.object.Location pos1, + com.github.intellectualsites.plotsquared.plot.object.Location pos2, + com.github.intellectualsites.plotsquared.plot.object.Location newPos, + final Runnable whenDone) { final int relX = newPos.getX() - pos1.getX(); final int relZ = newPos.getZ() - pos1.getZ(); - Location pos4 = new Location(newPos.getWorld(), newPos.getX() + relX, 256, newPos.getZ() + relZ); + com.github.intellectualsites.plotsquared.plot.object.Location pos4 = + new com.github.intellectualsites.plotsquared.plot.object.Location(newPos.getWorld(), + newPos.getX() + relX, 256, newPos.getZ() + relZ); - final RegionWrapper region = new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); + final RegionWrapper region = + new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); final World oldWorld = Bukkit.getWorld(pos1.getWorld()); final World newWorld = Bukkit.getWorld(newPos.getWorld()); final String newWorldName = newWorld.getName(); @@ -153,8 +128,7 @@ public class BukkitChunkManager extends ChunkManager { final ContentMap map = new ContentMap(); final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(newWorldName, false); ChunkManager.chunkTask(pos1, pos2, new RunnableVal() { - @Override - public void run(int[] value) { + @Override public void run(int[] value) { int bx = value[2]; int bz = value[3]; int tx = value[4]; @@ -171,8 +145,7 @@ public class BukkitChunkManager extends ChunkManager { } } }, new Runnable() { - @Override - public void run() { + @Override public void run() { for (Entry entry : map.allBlocks.entrySet()) { PlotLoc loc = entry.getKey(); PlotBlock[] blocks = entry.getValue(); @@ -185,8 +158,7 @@ public class BukkitChunkManager extends ChunkManager { } queue.enqueue(); GlobalBlockQueue.IMP.addTask(new Runnable() { - @Override - public void run() { + @Override public void run() { map.restoreBlocks(newWorld, 0, 0); map.restoreEntities(newWorld, relX, relZ); TaskManager.runTask(whenDone); @@ -197,8 +169,10 @@ public class BukkitChunkManager extends ChunkManager { return true; } - @Override - public boolean regenerateRegion(final Location pos1, final Location pos2, final boolean ignoreAugment, final Runnable whenDone) { + @Override public boolean regenerateRegion( + final com.github.intellectualsites.plotsquared.plot.object.Location pos1, + final com.github.intellectualsites.plotsquared.plot.object.Location pos2, + final boolean ignoreAugment, final Runnable whenDone) { final String world = pos1.getWorld(); final int p1x = pos1.getX(); @@ -219,8 +193,7 @@ public class BukkitChunkManager extends ChunkManager { } final World worldObj = Bukkit.getWorld(world); TaskManager.runTask(new Runnable() { - @Override - public void run() { + @Override public void run() { long start = System.currentTimeMillis(); while (!chunks.isEmpty() && System.currentTimeMillis() - start < 5) { final ChunkLoc chunk = chunks.remove(0); @@ -235,11 +208,11 @@ public class BukkitChunkManager extends ChunkManager { continue; } final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false); - RegionWrapper currentPlotClear = new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); + RegionWrapper currentPlotClear = + new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z) { AugmentedUtils.bypass(ignoreAugment, new Runnable() { - @Override - public void run() { + @Override public void run() { queue.regenChunkSafe(chunk.x, chunk.z); } }); @@ -306,12 +279,11 @@ public class BukkitChunkManager extends ChunkManager { } map.saveEntitiesOut(chunkObj, currentPlotClear); AugmentedUtils.bypass(ignoreAugment, new Runnable() { - @Override - public void run() { + @Override public void run() { setChunkInPlotArea(null, new RunnableVal() { - @Override - public void run(ScopedLocalBlockQueue value) { - Location min = value.getMin(); + @Override public void run(ScopedLocalBlockQueue value) { + com.github.intellectualsites.plotsquared.plot.object.Location + min = value.getMin(); int bx = min.getX(); int bz = min.getZ(); for (int x = 0; x < 16; x++) { @@ -319,7 +291,8 @@ public class BukkitChunkManager extends ChunkManager { PlotLoc loc = new PlotLoc(bx + x, bz + z); PlotBlock[] ids = map.allBlocks.get(loc); if (ids != null) { - for (int y = 0; y < Math.min(128, ids.length); y++) { + for (int y = 0; + y < Math.min(128, ids.length); y++) { PlotBlock id = ids[y]; if (id != null) { value.setBlock(x, y, z, id); @@ -327,7 +300,8 @@ public class BukkitChunkManager extends ChunkManager { value.setBlock(x, y, z, 0, (byte) 0); } } - for (int y = Math.min(128, ids.length); y < ids.length; y++) { + for (int y = Math.min(128, ids.length); + y < ids.length; y++) { PlotBlock id = ids[y]; if (id != null) { value.setBlock(x, y, z, id); @@ -354,7 +328,8 @@ public class BukkitChunkManager extends ChunkManager { } @Override - public void clearAllEntities(Location pos1, Location pos2) { + public void clearAllEntities(com.github.intellectualsites.plotsquared.plot.object.Location pos1, + com.github.intellectualsites.plotsquared.plot.object.Location pos2) { String world = pos1.getWorld(); List entities = BukkitUtil.getEntities(world); int bx = pos1.getX(); @@ -364,26 +339,27 @@ public class BukkitChunkManager extends ChunkManager { for (Entity entity : entities) { if (!(entity instanceof Player)) { org.bukkit.Location location = entity.getLocation(); - if (location.getX() >= bx && location.getX() <= tx && location.getZ() >= bz && location.getZ() <= tz) { + if (location.getX() >= bx && location.getX() <= tx && location.getZ() >= bz + && location.getZ() <= tz) { + if (entity.hasMetadata("ps-tmp-teleport")) { + continue; + } entity.remove(); } } } } - @Override - public boolean loadChunk(String world, ChunkLoc loc, boolean force) { + @Override public boolean loadChunk(String world, ChunkLoc loc, boolean force) { return BukkitUtil.getWorld(world).getChunkAt(loc.x, loc.z).load(force); } - @SuppressWarnings("deprecation") - @Override - public void unloadChunk(final String world, final ChunkLoc loc, final boolean save, final boolean safe) { - if (!PS.get().isMainThread(Thread.currentThread())) { + @SuppressWarnings("deprecation") @Override + public void unloadChunk(final String world, final ChunkLoc loc, final boolean save, + final boolean safe) { + if (!PlotSquared.get().isMainThread(Thread.currentThread())) { TaskManager.runTask(new Runnable() { - @SuppressWarnings("deprecation") - @Override - public void run() { + @SuppressWarnings("deprecation") @Override public void run() { BukkitUtil.getWorld(world).unloadChunk(loc.x, loc.z, save, safe); } }); @@ -392,10 +368,15 @@ public class BukkitChunkManager extends ChunkManager { } } - @Override - public void swap(Location bot1, Location top1, Location bot2, Location top2, final Runnable whenDone) { - RegionWrapper region1 = new RegionWrapper(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ()); - RegionWrapper region2 = new RegionWrapper(bot2.getX(), top2.getX(), bot2.getZ(), top2.getZ()); + @Override public void swap(com.github.intellectualsites.plotsquared.plot.object.Location bot1, + com.github.intellectualsites.plotsquared.plot.object.Location top1, + com.github.intellectualsites.plotsquared.plot.object.Location bot2, + com.github.intellectualsites.plotsquared.plot.object.Location top2, + final Runnable whenDone) { + RegionWrapper region1 = + new RegionWrapper(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ()); + RegionWrapper region2 = + new RegionWrapper(bot2.getX(), top2.getX(), bot2.getZ(), top2.getZ()); final World world1 = Bukkit.getWorld(bot1.getWorld()); World world2 = Bukkit.getWorld(bot2.getWorld()); @@ -412,8 +393,7 @@ public class BukkitChunkManager extends ChunkManager { } } GlobalBlockQueue.IMP.addTask(new Runnable() { - @Override - public void run() { + @Override public void run() { for (ContentMap map : maps) { map.restoreBlocks(world1, 0, 0); map.restoreEntities(world1, 0, 0); @@ -423,17 +403,17 @@ public class BukkitChunkManager extends ChunkManager { }); } - @Override - public int[] countEntities(Plot plot) { + @Override public int[] countEntities(Plot plot) { int[] existing = (int[]) plot.getMeta("EntityCount"); - if (existing != null && (System.currentTimeMillis() - (long) plot.getMeta("EntityCountTime") < 1000)) { + if (existing != null && (System.currentTimeMillis() - (long) plot.getMeta("EntityCountTime") + < 1000)) { return existing; } PlotArea area = plot.getArea(); World world = BukkitUtil.getWorld(area.worldname); - Location bot = plot.getBottomAbs(); - Location top = plot.getTopAbs(); + com.github.intellectualsites.plotsquared.plot.object.Location bot = plot.getBottomAbs(); + com.github.intellectualsites.plotsquared.plot.object.Location top = plot.getTopAbs(); int bx = bot.getX() >> 4; int bz = bot.getZ() >> 4; @@ -542,7 +522,7 @@ public class BukkitChunkManager extends ChunkManager { case ARMOR_STAND: count[5]++; break; - // misc + // misc case MINECART: case MINECART_CHEST: case MINECART_COMMAND: @@ -691,7 +671,8 @@ public class BukkitChunkManager extends ChunkManager { public void saveEntitiesOut(Chunk chunk, RegionWrapper region) { for (Entity entity : chunk.getEntities()) { - Location loc = BukkitUtil.getLocation(entity); + com.github.intellectualsites.plotsquared.plot.object.Location loc = + BukkitUtil.getLocation(entity); int x = loc.getX(); int z = loc.getZ(); if (isIn(region, x, z)) { @@ -700,14 +681,17 @@ public class BukkitChunkManager extends ChunkManager { if (entity.getVehicle() != null) { continue; } - EntityWrapper wrap = new EntityWrapper(entity, (short) 2); + EntityWrapper wrap = new ReplicatingEntityWrapper(entity, (short) 2); + wrap.saveEntity(); this.entities.add(wrap); } } - public void saveEntitiesIn(Chunk chunk, RegionWrapper region, int offsetX, int offsetZ, boolean delete) { + public void saveEntitiesIn(Chunk chunk, RegionWrapper region, int offsetX, int offsetZ, + boolean delete) { for (Entity entity : chunk.getEntities()) { - Location loc = BukkitUtil.getLocation(entity); + com.github.intellectualsites.plotsquared.plot.object.Location loc = + BukkitUtil.getLocation(entity); int x = loc.getX(); int z = loc.getZ(); if (!isIn(region, x, z)) { @@ -716,9 +700,10 @@ public class BukkitChunkManager extends ChunkManager { if (entity.getVehicle() != null) { continue; } - EntityWrapper wrap = new EntityWrapper(entity, (short) 2); + EntityWrapper wrap = new ReplicatingEntityWrapper(entity, (short) 2); wrap.x += offsetX; wrap.z += offsetZ; + wrap.saveEntity(); this.entities.add(wrap); if (delete) { if (!(entity instanceof Player)) { @@ -733,7 +718,7 @@ public class BukkitChunkManager extends ChunkManager { try { entity.spawn(world, xOffset, zOffset); } catch (Exception e) { - PS.debug("Failed to restore entity (e): " + e.toString()); + PlotSquared.debug("Failed to restore entity (e): " + e.toString()); e.printStackTrace(); } } @@ -743,26 +728,30 @@ public class BukkitChunkManager extends ChunkManager { public void restoreBlocks(World world, int xOffset, int zOffset) { for (Entry blockLocEntry : this.chestContents.entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof InventoryHolder) { InventoryHolder chest = (InventoryHolder) state; chest.getInventory().setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate chest: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to regenerate chest: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate chest (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to regenerate chest (e): " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ',' + + (blockLocEntry.getKey().z + zOffset)); } } for (Entry blockLocEntry : this.signContents.entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Sign) { Sign sign = (Sign) state; @@ -773,95 +762,105 @@ public class BukkitChunkManager extends ChunkManager { } state.update(true); } else { - PS.debug( - "&c[WARN] Plot clear failed to regenerate sign: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y - + ',' + ( - blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to regenerate sign: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (IndexOutOfBoundsException ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate sign: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y - + ',' + ( - blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to regenerate sign: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ',' + + (blockLocEntry.getKey().z + zOffset)); } } for (Entry blockLocEntry : this.dispenserContents.entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Dispenser) { - ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); + ((InventoryHolder) state).getInventory() + .setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ',' + + (blockLocEntry.getKey().z + zOffset)); } } for (Entry blockLocEntry : this.dropperContents.entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Dropper) { - ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); + ((InventoryHolder) state).getInventory() + .setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to regenerate dispenser: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to regenerate dispenser (e): " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ',' + + (blockLocEntry.getKey().z + zOffset)); } } for (Entry blockLocEntry : this.beaconContents.entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Beacon) { - ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); + ((InventoryHolder) state).getInventory() + .setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate beacon: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to regenerate beacon: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate beacon (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to regenerate beacon (e): " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ',' + + (blockLocEntry.getKey().z + zOffset)); } } for (Entry blockLocMaterialEntry : this.jukeboxDisc.entrySet()) { try { - Block block = - world.getBlockAt(blockLocMaterialEntry.getKey().x + xOffset, blockLocMaterialEntry.getKey().y, blockLocMaterialEntry - .getKey().z + zOffset); + Block block = world.getBlockAt(blockLocMaterialEntry.getKey().x + xOffset, + blockLocMaterialEntry.getKey().y, + blockLocMaterialEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Jukebox) { ((Jukebox) state).setPlaying(blockLocMaterialEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to restore jukebox: " + (blockLocMaterialEntry.getKey().x + xOffset) + ',' - + blockLocMaterialEntry - .getKey().y + ',' + ( - blockLocMaterialEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to restore jukebox: " + ( + blockLocMaterialEntry.getKey().x + xOffset) + ',' + + blockLocMaterialEntry.getKey().y + ',' + ( + blockLocMaterialEntry.getKey().z + zOffset)); } } catch (Exception ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate jukebox (e): " + (blockLocMaterialEntry.getKey().x + xOffset) + ',' - + blockLocMaterialEntry - .getKey().y + ',' + ( - blockLocMaterialEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to regenerate jukebox (e): " + ( + blockLocMaterialEntry.getKey().x + xOffset) + ',' + blockLocMaterialEntry + .getKey().y + ',' + (blockLocMaterialEntry.getKey().z + zOffset)); } } for (Entry blockLocEntry : this.skullData.entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Skull) { Object[] data = blockLocEntry.getValue(); @@ -872,193 +871,221 @@ public class BukkitChunkManager extends ChunkManager { ((Skull) state).setSkullType((SkullType) data[3]); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to restore skull: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to restore skull: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (Exception e) { - PS.debug("&c[WARN] Plot clear failed to regenerate skull (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to regenerate skull (e): " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ',' + + (blockLocEntry.getKey().z + zOffset)); e.printStackTrace(); } } for (Entry blockLocEntry : this.hopperContents.entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Hopper) { - ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); + ((InventoryHolder) state).getInventory() + .setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate hopper: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to regenerate hopper: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate hopper (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to regenerate hopper (e): " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ',' + + (blockLocEntry.getKey().z + zOffset)); } } for (Entry blockLocNoteEntry : this.noteBlockContents.entrySet()) { try { - Block block = world.getBlockAt( - blockLocNoteEntry.getKey().x + xOffset, blockLocNoteEntry.getKey().y, blockLocNoteEntry.getKey().z + zOffset); + Block block = world.getBlockAt(blockLocNoteEntry.getKey().x + xOffset, + blockLocNoteEntry.getKey().y, blockLocNoteEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof NoteBlock) { ((NoteBlock) state).setNote(blockLocNoteEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate note block: " + (blockLocNoteEntry.getKey().x + xOffset) + ',' - + blockLocNoteEntry - .getKey().y + ',' + ( - blockLocNoteEntry.getKey().z + zOffset)); + PlotSquared.debug( + "&c[WARN] Plot clear failed to regenerate note block: " + ( + blockLocNoteEntry.getKey().x + xOffset) + ',' + blockLocNoteEntry + .getKey().y + ',' + (blockLocNoteEntry.getKey().z + zOffset)); } } catch (Exception ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate note block (e): " + (blockLocNoteEntry.getKey().x + xOffset) + ',' - + blockLocNoteEntry - .getKey().y + ',' + ( - blockLocNoteEntry.getKey().z + zOffset)); + PlotSquared.debug( + "&c[WARN] Plot clear failed to regenerate note block (e): " + ( + blockLocNoteEntry.getKey().x + xOffset) + ',' + blockLocNoteEntry + .getKey().y + ',' + (blockLocNoteEntry.getKey().z + zOffset)); } } for (Entry blockLocShortEntry : this.brewTime.entrySet()) { try { - Block block = world.getBlockAt( - blockLocShortEntry.getKey().x + xOffset, blockLocShortEntry.getKey().y, blockLocShortEntry.getKey().z + zOffset); + Block block = world.getBlockAt(blockLocShortEntry.getKey().x + xOffset, + blockLocShortEntry.getKey().y, blockLocShortEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof BrewingStand) { ((BrewingStand) state).setBrewingTime(blockLocShortEntry.getValue()); } else { - PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking: " + (blockLocShortEntry.getKey().x + xOffset) + ',' - + blockLocShortEntry - .getKey().y + ',' + ( - blockLocShortEntry.getKey().z + zOffset)); + PlotSquared.debug( + "&c[WARN] Plot clear failed to restore brewing stand cooking: " + ( + blockLocShortEntry.getKey().x + xOffset) + ',' + blockLocShortEntry + .getKey().y + ',' + (blockLocShortEntry.getKey().z + zOffset)); } } catch (Exception ignored) { - PS.debug("&c[WARN] Plot clear failed to restore brewing stand cooking (e): " + (blockLocShortEntry.getKey().x + xOffset) + ',' - + blockLocShortEntry.getKey().y + ',' + (blockLocShortEntry.getKey().z + zOffset)); + PlotSquared.debug( + "&c[WARN] Plot clear failed to restore brewing stand cooking (e): " + ( + blockLocShortEntry.getKey().x + xOffset) + ',' + blockLocShortEntry + .getKey().y + ',' + (blockLocShortEntry.getKey().z + zOffset)); } } - for (Entry blockLocEntityTypeEntry : this.spawnerData.entrySet()) { + for (Entry blockLocEntityTypeEntry : this.spawnerData + .entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntityTypeEntry.getKey().x + xOffset, blockLocEntityTypeEntry.getKey().y, blockLocEntityTypeEntry - .getKey().z + zOffset); + Block block = world.getBlockAt(blockLocEntityTypeEntry.getKey().x + xOffset, + blockLocEntityTypeEntry.getKey().y, + blockLocEntityTypeEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof CreatureSpawner) { - ((CreatureSpawner) state).setSpawnedType(blockLocEntityTypeEntry.getValue()); + ((CreatureSpawner) state) + .setSpawnedType(blockLocEntityTypeEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to restore spawner type: " + (blockLocEntityTypeEntry.getKey().x + xOffset) + ',' - + blockLocEntityTypeEntry - .getKey().y + ',' + ( - blockLocEntityTypeEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to restore spawner type: " + ( + blockLocEntityTypeEntry.getKey().x + xOffset) + ',' + + blockLocEntityTypeEntry.getKey().y + ',' + ( + blockLocEntityTypeEntry.getKey().z + zOffset)); } } catch (Exception ignored) { - PS.debug("&c[WARN] Plot clear failed to restore spawner type (e): " + (blockLocEntityTypeEntry.getKey().x + xOffset) + ',' - + blockLocEntityTypeEntry.getKey().y + ',' + (blockLocEntityTypeEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to restore spawner type (e): " + ( + blockLocEntityTypeEntry.getKey().x + xOffset) + ',' + + blockLocEntityTypeEntry.getKey().y + ',' + ( + blockLocEntityTypeEntry.getKey().z + zOffset)); } } for (Entry blockLocStringEntry : this.cmdData.entrySet()) { try { - Block block = world.getBlockAt( - blockLocStringEntry.getKey().x + xOffset, blockLocStringEntry.getKey().y, blockLocStringEntry.getKey().z + zOffset); + Block block = world.getBlockAt(blockLocStringEntry.getKey().x + xOffset, + blockLocStringEntry.getKey().y, blockLocStringEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof CommandBlock) { ((CommandBlock) state).setCommand(blockLocStringEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to restore command block: " + (blockLocStringEntry.getKey().x + xOffset) + ',' - + blockLocStringEntry - .getKey().y + ',' + ( + PlotSquared.debug( + "&c[WARN] Plot clear failed to restore command block: " + ( + blockLocStringEntry.getKey().x + xOffset) + ',' + + blockLocStringEntry.getKey().y + ',' + ( blockLocStringEntry.getKey().z + zOffset)); } } catch (Exception ignored) { - PS.debug("&c[WARN] Plot clear failed to restore command block (e): " + (blockLocStringEntry.getKey().x + xOffset) + ',' - + blockLocStringEntry - .getKey().y + ',' + ( - blockLocStringEntry.getKey().z + zOffset)); + PlotSquared.debug( + "&c[WARN] Plot clear failed to restore command block (e): " + ( + blockLocStringEntry.getKey().x + xOffset) + ',' + blockLocStringEntry + .getKey().y + ',' + (blockLocStringEntry.getKey().z + zOffset)); } } - for (Entry blockLocEntry : this.brewingStandContents.entrySet()) { + for (Entry blockLocEntry : this.brewingStandContents + .entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof BrewingStand) { - ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); + ((InventoryHolder) state).getInventory() + .setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand: " + (blockLocEntry.getKey().x + xOffset) + ',' - + blockLocEntry - .getKey().y + ',' + ( - blockLocEntry.getKey().z - + zOffset)); + PlotSquared.debug( + "&c[WARN] Plot clear failed to regenerate brewing stand: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate brewing stand (e): " + (blockLocEntry.getKey().x + xOffset) + ',' - + blockLocEntry.getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug( + "&c[WARN] Plot clear failed to regenerate brewing stand (e): " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } for (Entry blockLocEntry : this.furnaceTime.entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Furnace) { Short[] time = blockLocEntry.getValue(); ((Furnace) state).setBurnTime(time[0]); ((Furnace) state).setCookTime(time[1]); } else { - PS.debug( - "&c[WARN] Plot clear failed to restore furnace cooking: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug( + "&c[WARN] Plot clear failed to restore furnace cooking: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (Exception ignored) { - PS.debug( - "&c[WARN] Plot clear failed to restore furnace cooking (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug( + "&c[WARN] Plot clear failed to restore furnace cooking (e): " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } for (Entry blockLocEntry : this.furnaceContents.entrySet()) { try { - Block block = - world.getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, blockLocEntry.getKey().z + zOffset); + Block block = world + .getBlockAt(blockLocEntry.getKey().x + xOffset, blockLocEntry.getKey().y, + blockLocEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Furnace) { - ((InventoryHolder) state).getInventory().setContents(blockLocEntry.getValue()); + ((InventoryHolder) state).getInventory() + .setContents(blockLocEntry.getValue()); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate furnace: " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to regenerate furnace: " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + + ',' + (blockLocEntry.getKey().z + zOffset)); } } catch (IllegalArgumentException ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate furnace (e): " + (blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry - .getKey().y + ',' + (blockLocEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to regenerate furnace (e): " + ( + blockLocEntry.getKey().x + xOffset) + ',' + blockLocEntry.getKey().y + ',' + + (blockLocEntry.getKey().z + zOffset)); } } for (Entry blockLocByteEntry : this.bannerBase.entrySet()) { try { - Block block = world.getBlockAt( - blockLocByteEntry.getKey().x + xOffset, blockLocByteEntry.getKey().y, blockLocByteEntry.getKey().z + zOffset); + Block block = world.getBlockAt(blockLocByteEntry.getKey().x + xOffset, + blockLocByteEntry.getKey().y, blockLocByteEntry.getKey().z + zOffset); BlockState state = block.getState(); if (state instanceof Banner) { Banner banner = (Banner) state; DyeColor base = blockLocByteEntry.getValue(); - List patterns = this.bannerPatterns.get(blockLocByteEntry.getKey()); + List patterns = + this.bannerPatterns.get(blockLocByteEntry.getKey()); banner.setBaseColor(base); banner.setPatterns(patterns); state.update(true); } else { - PS.debug("&c[WARN] Plot clear failed to regenerate banner: " + (blockLocByteEntry.getKey().x + xOffset) + ',' - + blockLocByteEntry.getKey().y + ',' + (blockLocByteEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to regenerate banner: " + ( + blockLocByteEntry.getKey().x + xOffset) + ',' + blockLocByteEntry + .getKey().y + ',' + (blockLocByteEntry.getKey().z + zOffset)); } } catch (Exception ignored) { - PS.debug("&c[WARN] Plot clear failed to regenerate banner (e): " + (blockLocByteEntry.getKey().x + xOffset) + ',' - + blockLocByteEntry.getKey().y + ',' + (blockLocByteEntry.getKey().z + zOffset)); + PlotSquared.debug("&c[WARN] Plot clear failed to regenerate banner (e): " + ( + blockLocByteEntry.getKey().x + xOffset) + ',' + blockLocByteEntry.getKey().y + + ',' + (blockLocByteEntry.getKey().z + zOffset)); } } } - public void saveBlocks(World world, int maxY, int x, int z, int offsetX, int offsetZ, boolean storeNormal) { + public void saveBlocks(World world, int maxY, int x, int z, int offsetX, int offsetZ, + boolean storeNormal) { maxY = Math.min(255, maxY); PlotBlock[] ids; if (storeNormal) { @@ -1072,7 +1099,7 @@ public class BukkitChunkManager extends ChunkManager { if (storeNormal) { int typeId = id.getId(); if (typeId == 0) { - ids[y] = PlotBlock.EVERYTHING; + ids[y] = StringPlotBlock.EVERYTHING; } else { ids[y] = PlotBlock.get((short) typeId, block.getData()); } @@ -1082,7 +1109,8 @@ public class BukkitChunkManager extends ChunkManager { BlockLoc bl = new BlockLoc(x + offsetX, y, z + offsetZ); if (block.getState() instanceof InventoryHolder) { InventoryHolder inventoryHolder = (InventoryHolder) block.getState(); - ItemStack[] inventory = inventoryHolder.getInventory().getContents().clone(); + ItemStack[] inventory = + inventoryHolder.getInventory().getContents().clone(); switch (id) { case CHEST: this.chestContents.put(bl, inventory); @@ -1105,18 +1133,20 @@ public class BukkitChunkManager extends ChunkManager { if (time > 0) { this.brewTime.put(bl, time); } - ItemStack[] invBre = brewingStand.getInventory().getContents().clone(); + ItemStack[] invBre = + brewingStand.getInventory().getContents().clone(); this.brewingStandContents.put(bl, invBre); break; case FURNACE: - case BURNING_FURNACE: + case LEGACY_BURNING_FURNACE: Furnace furnace = (Furnace) inventoryHolder; short burn = furnace.getBurnTime(); short cook = furnace.getCookTime(); - ItemStack[] invFur = furnace.getInventory().getContents().clone(); + ItemStack[] invFur = + furnace.getInventory().getContents().clone(); this.furnaceContents.put(bl, invFur); if (cook != 0) { - this.furnaceTime.put(bl, new Short[]{burn, cook}); + this.furnaceTime.put(bl, new Short[] {burn, cook}); } break; } @@ -1144,7 +1174,8 @@ public class BukkitChunkManager extends ChunkManager { } } else if (block.getState() instanceof Skull) { Skull skull = (Skull) block.getState(); - this.skullData.put(bl, new Object[]{skull.hasOwner(), skull.getOwner(), skull.getRotation(), skull.getSkullType()}); + this.skullData.put(bl, new Object[] {skull.hasOwner(), skull.getOwner(), + skull.getRotation(), skull.getSkullType()}); } else if (block.getState() instanceof Banner) { Banner banner = (Banner) block.getState(); DyeColor base = banner.getBaseColor(); @@ -1153,9 +1184,9 @@ public class BukkitChunkManager extends ChunkManager { } } catch (Exception e) { - PS.debug("------------ FAILED TO DO SOMETHING --------"); + PlotSquared.debug("------------ FAILED TO DO SOMETHING --------"); e.printStackTrace(); - PS.debug("------------ but we caught it ^ --------"); + PlotSquared.debug("------------ but we caught it ^ --------"); } } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitCommand.java similarity index 60% rename from Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitCommand.java index d97271f4b..27edabf78 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitCommand.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitCommand.java @@ -1,16 +1,10 @@ -package com.plotsquared.bukkit.util; +package com.github.intellectualsites.plotsquared.bukkit.util; -import com.intellectualcrafters.plot.commands.MainCommand; -import com.intellectualcrafters.plot.object.ConsolePlayer; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.plotsquared.bukkit.commands.DebugUUID; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.command.ProxiedCommandSender; -import org.bukkit.command.RemoteConsoleCommandSender; -import org.bukkit.command.TabCompleter; +import com.github.intellectualsites.plotsquared.bukkit.commands.DebugUUID; +import com.github.intellectualsites.plotsquared.plot.commands.MainCommand; +import com.github.intellectualsites.plotsquared.plot.object.ConsolePlayer; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import org.bukkit.command.*; import org.bukkit.entity.Player; import java.util.ArrayList; @@ -25,19 +19,22 @@ public class BukkitCommand implements CommandExecutor, TabCompleter { } @Override - public boolean onCommand(CommandSender commandSender, Command command, String commandLabel, String[] args) { + public boolean onCommand(CommandSender commandSender, Command command, String commandLabel, + String[] args) { if (commandSender instanceof Player) { return MainCommand.onCommand(BukkitUtil.getPlayer((Player) commandSender), args); } - if (commandSender instanceof ConsoleCommandSender || commandSender instanceof ProxiedCommandSender - || commandSender instanceof RemoteConsoleCommandSender) { + if (commandSender instanceof ConsoleCommandSender + || commandSender instanceof ProxiedCommandSender + || commandSender instanceof RemoteConsoleCommandSender) { return MainCommand.onCommand(ConsolePlayer.getConsole(), args); } return false; } @Override - public List onTabComplete(CommandSender commandSender, Command command, String s, String[] args) { + public List onTabComplete(CommandSender commandSender, Command command, String s, + String[] args) { if (!(commandSender instanceof Player)) { return null; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitEconHandler.java similarity index 63% rename from Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitEconHandler.java index 830afe93c..a9978b76c 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEconHandler.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitEconHandler.java @@ -1,10 +1,10 @@ -package com.plotsquared.bukkit.util; +package com.github.intellectualsites.plotsquared.bukkit.util; -import com.intellectualcrafters.plot.object.OfflinePlotPlayer; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.EconHandler; -import com.plotsquared.bukkit.object.BukkitOfflinePlayer; -import com.plotsquared.bukkit.object.BukkitPlayer; +import com.github.intellectualsites.plotsquared.bukkit.object.BukkitOfflinePlayer; +import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer; +import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.EconHandler; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.permission.Permission; import org.bukkit.Bukkit; @@ -24,7 +24,8 @@ public class BukkitEconHandler extends EconHandler { } private boolean setupPermissions() { - RegisteredServiceProvider permissionProvider = Bukkit.getServer().getServicesManager().getRegistration(Permission.class); + RegisteredServiceProvider permissionProvider = + Bukkit.getServer().getServicesManager().getRegistration(Permission.class); if (permissionProvider != null) { this.perms = permissionProvider.getProvider(); } @@ -35,15 +36,15 @@ public class BukkitEconHandler extends EconHandler { if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) { return false; } - RegisteredServiceProvider economyProvider = Bukkit.getServer().getServicesManager().getRegistration(Economy.class); + RegisteredServiceProvider economyProvider = + Bukkit.getServer().getServicesManager().getRegistration(Economy.class); if (economyProvider != null) { this.econ = economyProvider.getProvider(); } return this.econ != null; } - @Override - public double getMoney(PlotPlayer player) { + @Override public double getMoney(PlotPlayer player) { double bal = super.getMoney(player); if (Double.isNaN(bal)) { return this.econ.getBalance(((BukkitPlayer) player).player); @@ -51,28 +52,23 @@ public class BukkitEconHandler extends EconHandler { return bal; } - @Override - public void withdrawMoney(PlotPlayer player, double amount) { + @Override public void withdrawMoney(PlotPlayer player, double amount) { this.econ.withdrawPlayer(((BukkitPlayer) player).player, amount); } - @Override - public void depositMoney(PlotPlayer player, double amount) { + @Override public void depositMoney(PlotPlayer player, double amount) { this.econ.depositPlayer(((BukkitPlayer) player).player, amount); } - @Override - public void depositMoney(OfflinePlotPlayer player, double amount) { + @Override public void depositMoney(OfflinePlotPlayer player, double amount) { this.econ.depositPlayer(((BukkitOfflinePlayer) player).player, amount); } - @Override - public boolean hasPermission(String world, String player, String perm) { + @Override public boolean hasPermission(String world, String player, String perm) { return this.perms.playerHas(world, Bukkit.getOfflinePlayer(player), perm); } - @Override - public double getBalance(PlotPlayer player) { + @Override public double getBalance(PlotPlayer player) { return this.econ.getBalance(player.getName()); } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitEventUtil.java similarity index 51% rename from Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitEventUtil.java index 6564c6dc7..4b7df7471 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEventUtil.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitEventUtil.java @@ -1,16 +1,10 @@ -package com.plotsquared.bukkit.util; +package com.github.intellectualsites.plotsquared.bukkit.util; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotCluster; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.Rating; -import com.intellectualcrafters.plot.util.EventUtil; -import com.plotsquared.bukkit.events.*; -import com.plotsquared.bukkit.object.BukkitPlayer; +import com.github.intellectualsites.plotsquared.bukkit.events.*; +import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer; +import com.github.intellectualsites.plotsquared.plot.flag.Flag; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.EventUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; @@ -34,89 +28,74 @@ public class BukkitEventUtil extends EventUtil { return !(event instanceof Cancellable) || !((Cancellable) event).isCancelled(); } - @Override - public boolean callClaim(PlotPlayer player, Plot plot, boolean auto) { + @Override public boolean callClaim(PlotPlayer player, Plot plot, boolean auto) { return callEvent(new PlayerClaimPlotEvent(getPlayer(player), plot, auto)); } - @Override - public boolean callTeleport(PlotPlayer player, Location from, Plot plot) { + @Override public boolean callTeleport(PlotPlayer player, Location from, Plot plot) { return callEvent(new PlayerTeleportToPlotEvent(getPlayer(player), from, plot)); } - @Override - public boolean callComponentSet(Plot plot, String component) { + @Override public boolean callComponentSet(Plot plot, String component) { return callEvent(new PlotComponentSetEvent(plot, component)); } - @Override - public boolean callClear(Plot plot) { + @Override public boolean callClear(Plot plot) { return callEvent(new PlotClearEvent(plot)); } - @Override - public void callDelete(Plot plot) { + @Override public void callDelete(Plot plot) { callEvent(new PlotDeleteEvent(plot)); } - @Override - public boolean callFlagAdd(Flag flag, Plot plot) { + @Override public boolean callFlagAdd(Flag flag, Plot plot) { return callEvent(new PlotFlagAddEvent(flag, plot)); } - @Override - public boolean callFlagRemove(Flag flag, Plot plot, Object value) { + @Override public boolean callFlagRemove(Flag flag, Plot plot, Object value) { return callEvent(new PlotFlagRemoveEvent(flag, plot)); } - @Override - public boolean callMerge(Plot plot, ArrayList plots) { + @Override public boolean callMerge(Plot plot, ArrayList plots) { return callEvent(new PlotMergeEvent(BukkitUtil.getWorld(plot.getWorldName()), plot, plots)); } - @Override - public boolean callUnlink(PlotArea area, ArrayList plots) { + @Override public boolean callUnlink(PlotArea area, ArrayList plots) { return callEvent(new PlotUnlinkEvent(BukkitUtil.getWorld(area.worldname), area, plots)); } - @Override - public void callEntry(PlotPlayer player, Plot plot) { + @Override public void callEntry(PlotPlayer player, Plot plot) { callEvent(new PlayerEnterPlotEvent(getPlayer(player), plot)); } - @Override - public void callLeave(PlotPlayer player, Plot plot) { + @Override public void callLeave(PlotPlayer player, Plot plot) { callEvent(new PlayerLeavePlotEvent(getPlayer(player), plot)); } - @Override - public void callDenied(PlotPlayer initiator, Plot plot, UUID player, boolean added) { + @Override public void callDenied(PlotPlayer initiator, Plot plot, UUID player, boolean added) { callEvent(new PlayerPlotDeniedEvent(getPlayer(initiator), plot, player, added)); } - @Override - public void callTrusted(PlotPlayer initiator, Plot plot, UUID player, boolean added) { + @Override public void callTrusted(PlotPlayer initiator, Plot plot, UUID player, boolean added) { callEvent(new PlayerPlotTrustedEvent(getPlayer(initiator), plot, player, added)); } - @Override - public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) { + @Override public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) { callEvent(new PlayerPlotHelperEvent(getPlayer(initiator), plot, player, added)); } @Override - public boolean callOwnerChange(PlotPlayer initiator, Plot plot, UUID oldOwner, UUID newOwner, boolean hasOldOwner) { - return callEvent(new PlotChangeOwnerEvent(getPlayer(initiator), plot, oldOwner, newOwner, hasOldOwner)); + public boolean callOwnerChange(PlotPlayer initiator, Plot plot, UUID oldOwner, UUID newOwner, + boolean hasOldOwner) { + return callEvent( + new PlotChangeOwnerEvent(getPlayer(initiator), plot, oldOwner, newOwner, hasOldOwner)); } - @Override - public boolean callFlagRemove(Flag flag, Object object, PlotCluster cluster) { + @Override public boolean callFlagRemove(Flag flag, Object object, PlotCluster cluster) { return callEvent(new ClusterFlagRemoveEvent(flag, cluster)); } - @Override - @Nullable - public Rating callRating(PlotPlayer player, Plot plot, Rating rating) { + @Override @Nullable public Rating callRating(PlotPlayer player, Plot plot, Rating rating) { PlotRateEvent event = new PlotRateEvent(player, rating, plot); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitHybridUtils.java similarity index 82% rename from Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitHybridUtils.java index 225998ab2..0410ef7a9 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitHybridUtils.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitHybridUtils.java @@ -1,17 +1,17 @@ -package com.plotsquared.bukkit.util; +package com.github.intellectualsites.plotsquared.bukkit.util; -import com.intellectualcrafters.plot.generator.HybridUtils; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.PlotBlock; -import com.intellectualcrafters.plot.object.RegionWrapper; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.block.GlobalBlockQueue; -import com.intellectualcrafters.plot.util.block.LocalBlockQueue; -import com.intellectualcrafters.plot.util.expiry.PlotAnalysis; +import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; +import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.util.expiry.PlotAnalysis; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.World; @@ -26,8 +26,8 @@ import java.util.Random; public class BukkitHybridUtils extends HybridUtils { - @Override - public void analyzeRegion(final String world, final RegionWrapper region, final RunnableVal whenDone) { + @Override public void analyzeRegion(final String world, final RegionWrapper region, + final RunnableVal whenDone) { // int diff, int variety, int vertices, int rotation, int height_sd /* * diff: compare to base by looping through all blocks @@ -41,8 +41,7 @@ public class BukkitHybridUtils extends HybridUtils { * */ TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false); final World worldObj = Bukkit.getWorld(world); final ChunkGenerator gen = worldObj.getGenerator(); @@ -50,12 +49,10 @@ public class BukkitHybridUtils extends HybridUtils { return; } final BiomeGrid nullBiomeGrid = new BiomeGrid() { - @Override - public void setBiome(int a, int b, Biome c) { + @Override public void setBiome(int a, int b, Biome c) { } - @Override - public Biome getBiome(int a, int b) { + @Override public Biome getBiome(int a, int b) { return null; } }; @@ -82,15 +79,14 @@ public class BukkitHybridUtils extends HybridUtils { final short[][][] newBlocks = new short[256][width][length]; final Runnable run = new Runnable() { - @Override - public void run() { + @Override public void run() { ChunkManager.chunkTask(bot, top, new RunnableVal() { - @Override - public void run(int[] value) { + @Override public void run(int[] value) { // [chunkx, chunkz, pos1x, pos1z, pos2x, pos2z, isedge] int X = value[0]; int Z = value[1]; - short[][] result = gen.generateExtBlockSections(worldObj, r, X, Z, nullBiomeGrid); + short[][] result = + gen.generateExtBlockSections(worldObj, r, X, Z, nullBiomeGrid); int xb = (X << 4) - bx; int zb = (Z << 4) - bz; for (int i = 0; i < result.length; i++) { @@ -125,11 +121,9 @@ public class BukkitHybridUtils extends HybridUtils { } }, new Runnable() { - @Override - public void run() { + @Override public void run() { TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { int size = width * length; int[] changes = new int[size]; int[] faces = new int[size]; @@ -151,7 +145,8 @@ public class BukkitHybridUtils extends HybridUtils { } else { // check vertices // modifications_adjacent - if (x > 0 && z > 0 && y > 0 && x < width - 1 && z < length - 1 && y < 255) { + if (x > 0 && z > 0 && y > 0 && x < width - 1 + && z < length - 1 && y < 255) { if (newBlocks[y - 1][x][z] == 0) { faces[i]++; } @@ -172,12 +167,15 @@ public class BukkitHybridUtils extends HybridUtils { } } - Material material = Material.getMaterial(now); + Material material = + Material.getMaterial(now); if (material != null) { - Class md = material.getData(); + Class md = + material.getData(); if (md.equals(Directional.class)) { data[i] += 8; - } else if (!md.equals(MaterialData.class)) { + } else if (!md + .equals(MaterialData.class)) { data[i]++; } } @@ -199,11 +197,14 @@ public class BukkitHybridUtils extends HybridUtils { analysis.air = (int) (MathMan.getMean(air) * 100); analysis.variety = (int) (MathMan.getMean(variety) * 100); - analysis.changes_sd = (int) MathMan.getSD(changes, analysis.changes); - analysis.faces_sd = (int) MathMan.getSD(faces, analysis.faces); + analysis.changes_sd = + (int) MathMan.getSD(changes, analysis.changes); + analysis.faces_sd = + (int) MathMan.getSD(faces, analysis.faces); analysis.data_sd = (int) MathMan.getSD(data, analysis.data); analysis.air_sd = (int) MathMan.getSD(air, analysis.air); - analysis.variety_sd = (int) MathMan.getSD(variety, analysis.variety); + analysis.variety_sd = + (int) MathMan.getSD(variety, analysis.variety); System.gc(); System.gc(); whenDone.value = analysis; @@ -219,8 +220,7 @@ public class BukkitHybridUtils extends HybridUtils { MainUtil.initCache(); ChunkManager.chunkTask(bot, top, new RunnableVal() { - @Override - public void run(int[] value) { + @Override public void run(int[] value) { int X = value[0]; int Z = value[1]; worldObj.loadChunk(X, Z); @@ -269,8 +269,7 @@ public class BukkitHybridUtils extends HybridUtils { worldObj.unloadChunkRequest(X, Z, true); } }, new Runnable() { - @Override - public void run() { + @Override public void run() { TaskManager.runTaskAsync(run); } }, 5); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitInventoryUtil.java similarity index 75% rename from Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitInventoryUtil.java index cd2c12d51..6beebcd95 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitInventoryUtil.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitInventoryUtil.java @@ -1,12 +1,13 @@ -package com.plotsquared.bukkit.util; +package com.github.intellectualsites.plotsquared.bukkit.util; -import com.intellectualcrafters.plot.object.PlotInventory; -import com.intellectualcrafters.plot.object.PlotItemStack; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.InventoryUtil; -import com.plotsquared.bukkit.object.BukkitPlayer; +import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer; +import com.github.intellectualsites.plotsquared.plot.object.PlotInventory; +import com.github.intellectualsites.plotsquared.plot.object.PlotItemStack; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.InventoryUtil; import org.bukkit.Bukkit; import org.bukkit.ChatColor; +import org.bukkit.Material; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; @@ -23,7 +24,7 @@ public class BukkitInventoryUtil extends InventoryUtil { if (item == null) { return null; } - ItemStack stack = new ItemStack(item.id, item.amount, item.data); + ItemStack stack = new ItemStack(BukkitUtil.getMaterial(item.getPlotBlock()), item.amount); ItemMeta meta = null; if (item.name != null) { meta = stack.getItemMeta(); @@ -45,8 +46,7 @@ public class BukkitInventoryUtil extends InventoryUtil { return stack; } - @Override - public void open(PlotInventory inv) { + @Override public void open(PlotInventory inv) { BukkitPlayer bp = (BukkitPlayer) inv.player; Inventory inventory = Bukkit.createInventory(null, inv.size * 9, inv.getTitle()); PlotItemStack[] items = inv.getItems(); @@ -60,8 +60,7 @@ public class BukkitInventoryUtil extends InventoryUtil { bp.player.openInventory(inventory); } - @Override - public void close(PlotInventory inv) { + @Override public void close(PlotInventory inv) { if (!inv.isOpen()) { return; } @@ -70,8 +69,7 @@ public class BukkitInventoryUtil extends InventoryUtil { bp.player.closeInventory(); } - @Override - public void setItem(PlotInventory inv, int index, PlotItemStack item) { + @Override public void setItem(PlotInventory inv, int index, PlotItemStack item) { BukkitPlayer bp = (BukkitPlayer) inv.player; InventoryView opened = bp.player.getOpenInventory(); if (!inv.isOpen()) { @@ -85,7 +83,8 @@ public class BukkitInventoryUtil extends InventoryUtil { if (item == null) { return null; } - int id = item.getTypeId(); + // int id = item.getTypeId(); + Material id = item.getType(); short data = item.getDurability(); int amount = item.getAmount(); String name = null; @@ -100,11 +99,10 @@ public class BukkitInventoryUtil extends InventoryUtil { lore = itemLore.toArray(new String[itemLore.size()]); } } - return new PlotItemStack(id, data, amount, name, lore); + return new PlotItemStack(id.name(), amount, name, lore); } - @Override - public PlotItemStack[] getItems(PlotPlayer player) { + @Override public PlotItemStack[] getItems(PlotPlayer player) { BukkitPlayer bp = (BukkitPlayer) player; PlayerInventory inv = bp.player.getInventory(); PlotItemStack[] items = new PlotItemStack[36]; @@ -114,13 +112,13 @@ public class BukkitInventoryUtil extends InventoryUtil { return items; } - @Override - public boolean isOpen(PlotInventory inv) { + @Override public boolean isOpen(PlotInventory inv) { if (!inv.isOpen()) { return false; } BukkitPlayer bp = (BukkitPlayer) inv.player; InventoryView opened = bp.player.getOpenInventory(); - return inv.isOpen() && opened.getType() == InventoryType.CRAFTING && opened.getTitle() == null; + return inv.isOpen() && opened.getType() == InventoryType.CRAFTING + && opened.getTitle() == null; } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitLegacyMappings.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitLegacyMappings.java new file mode 100644 index 000000000..b92b6edfe --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitLegacyMappings.java @@ -0,0 +1,814 @@ +package com.github.intellectualsites.plotsquared.bukkit.util; + +import com.github.intellectualsites.plotsquared.plot.object.LegacyPlotBlock; +import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; +import com.github.intellectualsites.plotsquared.plot.object.StringPlotBlock; +import com.github.intellectualsites.plotsquared.plot.util.LegacyMappings; +import com.github.intellectualsites.plotsquared.plot.util.StringComparison; +import lombok.*; +import org.bukkit.Material; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * Borrowed from https://github.com/Phoenix616/IDConverter/blob/master/mappings/src/main/java/de/themoep/idconverter/IdMappings.java + * Original License: + *

+ * Minecraft ID mappings + * Copyright (C) 2017 Max Lee (https://github.com/Phoenix616) + *

+ * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + *

+ * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *

+ * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +public class BukkitLegacyMappings extends LegacyMappings { + + private static final LegacyBlock[] BLOCKS = + new LegacyBlock[] {new LegacyBlock(0, "air"), new LegacyBlock(1, "stone"), + new LegacyBlock(1, 1, "stone", "granite"), + new LegacyBlock(1, 2, "stone", "polished_granite"), + new LegacyBlock(1, 3, "stone", "diorite"), + new LegacyBlock(1, 4, "stone", "polished_diorite"), + new LegacyBlock(1, 5, "stone", "andesite"), + new LegacyBlock(1, 6, "stone", "polished_andesite"), + new LegacyBlock(2, "grass", "grass_block"), new LegacyBlock(3, "dirt"), + new LegacyBlock(3, 1, "dirt", "coarse_dirt"), new LegacyBlock(3, 2, "dirt", "podzol"), + new LegacyBlock(4, "cobblestone"), new LegacyBlock(5, "wood", "oak_planks"), + new LegacyBlock(5, 1, "wood", "spruce_planks"), + new LegacyBlock(5, 2, "wood", "birch_planks"), + new LegacyBlock(5, 3, "wood", "jungle_planks"), + new LegacyBlock(5, 4, "wood", "acacia_planks"), + new LegacyBlock(5, 5, "wood", "dark_oak_planks"), + new LegacyBlock(6, "sapling", "oak_sapling"), + new LegacyBlock(6, 1, "sapling", "spruce_sapling"), + new LegacyBlock(6, 2, "sapling", "birch_sapling"), + new LegacyBlock(6, 3, "sapling", "jungle_sapling"), + new LegacyBlock(6, 4, "sapling", "acacia_sapling"), + new LegacyBlock(6, 5, "sapling", "dark_oak_sapling"), new LegacyBlock(7, "bedrock"), + new LegacyBlock(8, "water", "flowing_water"), + new LegacyBlock(9, "stationary_water", "water"), + new LegacyBlock(10, "lava", "flowing_lava"), + new LegacyBlock(11, "stationary_lava", "lava"), new LegacyBlock(12, "sand"), + new LegacyBlock(12, 1, "sand", "red_sand"), new LegacyBlock(13, "gravel"), + new LegacyBlock(14, "gold_ore"), new LegacyBlock(15, "iron_ore"), + new LegacyBlock(16, "coal_ore"), new LegacyBlock(17, "log", "oak_log"), + new LegacyBlock(17, 1, "log", "oak_log"), new LegacyBlock(17, 2, "log", "spruce_log"), + new LegacyBlock(17, 3, "log", "birch_log"), new LegacyBlock(17, 4, "log", "jungle_log"), + new LegacyBlock(17, 5, "log", "oak_bark"), new LegacyBlock(17, 6, "log", "spruce_bark"), + new LegacyBlock(17, 7, "log", "birch_bark"), + new LegacyBlock(17, 8, "log", "jungle_bark"), + new LegacyBlock(18, "leaves", "oak_leaves"), + new LegacyBlock(18, 1, "leaves", "spruce_leaves"), + new LegacyBlock(18, 2, "leaves", "birch_leaves"), + new LegacyBlock(18, 3, "leaves", "jungle_leaves"), new LegacyBlock(19, "sponge"), + new LegacyBlock(19, 1, "sponge", "wet_sponge"), new LegacyBlock(20, "glass"), + new LegacyBlock(21, "lapis_ore"), new LegacyBlock(22, "lapis_block"), + new LegacyBlock(23, "dispenser"), new LegacyBlock(24, "sandstone"), + new LegacyBlock(24, 1, "sandstone", "chisled_sandstone"), + new LegacyBlock(24, 2, "sandstone", "cut_sandstone"), new LegacyBlock(25, "note_block"), + new LegacyBlock(26, "bed_block"), new LegacyBlock(27, "powered_rail"), + new LegacyBlock(28, "detector_rail"), + new LegacyBlock(29, "piston_sticky_base", "sticky_piston"), + new LegacyBlock(30, "web", "cobweb"), new LegacyBlock(31, "long_grass", "dead_bush"), + new LegacyBlock(31, 1, "long_grass", "grass"), + new LegacyBlock(31, 2, "long_grass", "fern"), new LegacyBlock(32, "dead_bush"), + new LegacyBlock(33, "piston_base", "piston"), + new LegacyBlock(34, "piston_extension", "piston_head"), + new LegacyBlock(35, "wool", "white_wool"), + new LegacyBlock(35, 1, "wool", "orange_wool"), + new LegacyBlock(35, 2, "wool", "magenta_wool"), + new LegacyBlock(35, 3, "wool", "light_blue_wool"), + new LegacyBlock(35, 4, "wool", "yellow_wool"), + new LegacyBlock(35, 5, "wool", "lime_wool"), + new LegacyBlock(35, 6, "wool", "pink_wool"), + new LegacyBlock(35, 7, "wool", "gray_wool"), + new LegacyBlock(35, 8, "wool", "light_gray_wool"), + new LegacyBlock(35, 9, "wool", "cyan_wool"), + new LegacyBlock(35, 10, "wool", "purple_wool"), + new LegacyBlock(35, 11, "wool", "blue_wool"), + new LegacyBlock(35, 12, "wool", "brown_wool"), + new LegacyBlock(35, 13, "wool", "green_wool"), + new LegacyBlock(35, 14, "wool", "red_wool"), + new LegacyBlock(35, 15, "wool", "black_wool"), + new LegacyBlock(36, "piston_moving_piece", "moving_piston"), + new LegacyBlock(37, "yellow_flower", "dandelion"), + new LegacyBlock(38, "red_rose", "poppy"), + new LegacyBlock(38, 1, "red_rose", "blue_orchid"), + new LegacyBlock(38, 2, "red_rose", "allium"), + new LegacyBlock(38, 3, "red_rose", "azure_bluet"), + new LegacyBlock(38, 4, "red_rose", "red_tulip"), + new LegacyBlock(38, 5, "red_rose", "orange_tulip"), + new LegacyBlock(38, 6, "red_rose", "white_tulip"), + new LegacyBlock(38, 7, "red_rose", "pink_tulip"), + new LegacyBlock(38, 8, "red_rose", "oxeye_daisy"), + new LegacyBlock(39, "brown_mushroom"), new LegacyBlock(40, "red_mushroom"), + new LegacyBlock(41, "gold_block"), new LegacyBlock(42, "iron_block"), + new LegacyBlock(43, "double_step"), + new LegacyBlock(43, 6, "double_step", "smooth_quartz"), + new LegacyBlock(43, 8, "double_step", "smooth_stone"), + new LegacyBlock(43, 9, "double_step", "smooth_sandstone"), + new LegacyBlock(44, "step", "stone_slab"), + new LegacyBlock(44, 1, "step", "sandstone_slab"), + new LegacyBlock(44, 2, "step", "petrified_oak_slab"), + new LegacyBlock(44, 3, "step", "cobblestone_slab"), + new LegacyBlock(44, 4, "step", "brick_slab"), + new LegacyBlock(44, 5, "step", "stone_brick_slab"), + new LegacyBlock(44, 6, "step", "nether_brick_slab"), + new LegacyBlock(44, 7, "step", "quartz_slab"), new LegacyBlock(45, "brick", "bricks"), + new LegacyBlock(46, "tnt"), new LegacyBlock(47, "bookshelf"), + new LegacyBlock(48, "mossy_cobblestone"), new LegacyBlock(49, "obsidian"), + new LegacyBlock(50, "torch"), new LegacyBlock(50, 1, "torch", "wall_torch"), + new LegacyBlock(50, 2, "torch", "wall_torch"), + new LegacyBlock(50, 3, "torch", "wall_torch"), + new LegacyBlock(50, 4, "torch", "wall_torch"), new LegacyBlock(50, 5, "torch"), + new LegacyBlock(51, "fire"), new LegacyBlock(52, "mob_spawner"), + new LegacyBlock(53, "wood_stairs", "oak_stairs"), new LegacyBlock(54, "chest", "chest"), + new LegacyBlock(55, "redstone_wire"), new LegacyBlock(56, "diamond_ore"), + new LegacyBlock(57, "diamond_block"), + new LegacyBlock(58, "workbench", "crafting_table"), + new LegacyBlock(59, "crops", "wheat"), new LegacyBlock(60, "soil", "farmland"), + new LegacyBlock(61, "furnace"), new LegacyBlock(62, "burning_furnace"), + new LegacyBlock(63, "sign_post", "sign"), + new LegacyBlock(64, "wooden_door", "oak_door"), new LegacyBlock(65, "ladder"), + new LegacyBlock(66, "rails", "rail"), new LegacyBlock(67, "cobblestone_stairs"), + new LegacyBlock(68, "wall_sign"), new LegacyBlock(69, "lever"), + new LegacyBlock(70, "stone_plate", "stone_pressure_plate"), + new LegacyBlock(71, "iron_door_block", "iron_door"), + new LegacyBlock(72, "wood_plate", "oak_pressure_plate"), + new LegacyBlock(73, "redstone_ore"), new LegacyBlock(74, "glowing_redstone_ore"), + new LegacyBlock(75, "redstone_torch_off"), + new LegacyBlock(76, "redstone_torch_on", "redstone_torch"), + new LegacyBlock(76, 1, "redstone_torch_on", "redstone_wall_torch"), + new LegacyBlock(76, 2, "redstone_torch_on", "redstone_wall_torch"), + new LegacyBlock(76, 3, "redstone_torch_on", "redstone_wall_torch"), + new LegacyBlock(76, 4, "redstone_torch_on", "redstone_wall_torch"), + new LegacyBlock(76, 5, "redstone_torch_on", "redstone_torch"), + new LegacyBlock(77, "stone_button"), new LegacyBlock(78, "snow"), + new LegacyBlock(79, "ice"), new LegacyBlock(80, "snow_block"), + new LegacyBlock(81, "cactus"), new LegacyBlock(82, "clay"), + new LegacyBlock(83, "sugar_cane_block", "sugar_cane"), new LegacyBlock(84, "jukebox"), + new LegacyBlock(85, "fence", "oak_fence"), + new LegacyBlock(86, "pumpkin", "carved_pumpkin"), new LegacyBlock(87, "netherrack"), + new LegacyBlock(88, "soul_sand"), new LegacyBlock(89, "glowstone"), + new LegacyBlock(90, "portal"), new LegacyBlock(91, "jack_o_lantern"), + new LegacyBlock(92, "cake_block", "cake"), new LegacyBlock(93, "diode_block_off"), + new LegacyBlock(94, "diode_block_on", "repeater"), + new LegacyBlock(95, "stained_glass", "white_stained_glass"), + new LegacyBlock(95, 1, "stained_glass", "orange_stained_glass"), + new LegacyBlock(95, 2, "stained_glass", "magenta_stained_glass"), + new LegacyBlock(95, 3, "stained_glass", "light_blue_stained_glass"), + new LegacyBlock(95, 4, "stained_glass", "yellow_stained_glass"), + new LegacyBlock(95, 5, "stained_glass", "lime_stained_glass"), + new LegacyBlock(95, 6, "stained_glass", "pink_stained_glass"), + new LegacyBlock(95, 7, "stained_glass", "gray_stained_glass"), + new LegacyBlock(95, 8, "stained_glass", "light_gray_stained_glass"), + new LegacyBlock(95, 9, "stained_glass", "cyan_stained_glass"), + new LegacyBlock(95, 10, "stained_glass", "purple_stained_glass"), + new LegacyBlock(95, 11, "stained_glass", "blue_stained_glass"), + new LegacyBlock(95, 12, "stained_glass", "brown_stained_glass"), + new LegacyBlock(95, 13, "stained_glass", "green_stained_glass"), + new LegacyBlock(95, 14, "stained_glass", "red_stained_glass"), + new LegacyBlock(95, 15, "stained_glass", "black_stained_glass"), + new LegacyBlock(96, "trap_door", "oak_trapdoor"), + new LegacyBlock(97, "monster_eggs", "infested_stone"), + new LegacyBlock(97, 1, "monster_eggs", "infested_coblestone"), + new LegacyBlock(97, 2, "monster_eggs", "infested_stone_bricks"), + new LegacyBlock(97, 3, "monster_eggs", "infested_mossy_stone_bricks"), + new LegacyBlock(97, 4, "monster_eggs", "infested_crcked_stone_bricks"), + new LegacyBlock(97, 5, "monster_eggs", "infested_chiseled_stone_bricks"), + new LegacyBlock(98, "smooth_brick", "stone_bricks"), + new LegacyBlock(98, 1, "smooth_brick", "mossy_stone_bricks"), + new LegacyBlock(98, 2, "smooth_brick", "cracked_stone_bricks"), + new LegacyBlock(98, 3, "smooth_brick", "chiseled_bricks"), + new LegacyBlock(99, "huge_mushroom_1", "brown_mushroom_block"), + new LegacyBlock(99, 1, "huge_mushroom_1"), new LegacyBlock(99, 2, "huge_mushroom_1"), + new LegacyBlock(99, 3, "huge_mushroom_1"), new LegacyBlock(99, 4, "huge_mushroom_1"), + new LegacyBlock(99, 5, "huge_mushroom_1"), new LegacyBlock(99, 6, "huge_mushroom_1"), + new LegacyBlock(99, 7, "huge_mushroom_1"), new LegacyBlock(99, 8, "huge_mushroom_1"), + new LegacyBlock(99, 9, "huge_mushroom_1"), + new LegacyBlock(99, 10, "huge_mushroom_1", "mushroom_stem"), + new LegacyBlock(99, 14, "huge_mushroom_1"), new LegacyBlock(99, 15, "huge_mushroom_1"), + new LegacyBlock(100, "huge_mushroom_2", "red_mushroom_block"), + new LegacyBlock(100, 1, "huge_mushroom_2"), new LegacyBlock(100, 2, "huge_mushroom_2"), + new LegacyBlock(100, 3, "huge_mushroom_2"), new LegacyBlock(100, 4, "huge_mushroom_2"), + new LegacyBlock(100, 5, "huge_mushroom_2"), new LegacyBlock(100, 6, "huge_mushroom_2"), + new LegacyBlock(100, 7, "huge_mushroom_2"), new LegacyBlock(100, 8, "huge_mushroom_2"), + new LegacyBlock(100, 9, "huge_mushroom_2"), + new LegacyBlock(100, 10, "huge_mushroom_2", "mushroom_stem"), + new LegacyBlock(100, 14, "huge_mushroom_2"), + new LegacyBlock(100, 15, "huge_mushroom_2"), + new LegacyBlock(101, "iron_fence", "ironbars"), + new LegacyBlock(102, "thin_glass", "glass_pane"), new LegacyBlock(103, "melon_block"), + new LegacyBlock(104, "pumpkin_stem"), new LegacyBlock(105, "melon_stem"), + new LegacyBlock(106, "vine"), new LegacyBlock(107, "fence_gate", "oak_fence_gate"), + new LegacyBlock(108, "brick_stairs"), + new LegacyBlock(109, "smooth_stairs", "stone_brick_stairs"), + new LegacyBlock(110, "mycel", "mycelium"), + new LegacyBlock(111, "water_lily", "lily_pad"), + new LegacyBlock(112, "nether_brick", "nether_bricks"), + new LegacyBlock(113, "nether_fence", "nether_brick_fence"), + new LegacyBlock(114, "nether_brick_stairs"), + new LegacyBlock(115, "nether_warts", "nether_wart"), + new LegacyBlock(116, "enchantment_table", "enchanting_table"), + new LegacyBlock(117, "brewing_stand"), new LegacyBlock(118, "cauldron"), + new LegacyBlock(119, "ender_portal", "end_portal"), + new LegacyBlock(120, "ender_portal_frame", "end_portal_frame"), + new LegacyBlock(121, "ender_stone", "end_stone"), new LegacyBlock(122, "dragon_egg"), + new LegacyBlock(123, "redstone_lamp_off"), + new LegacyBlock(124, "redstone_lamp_on", "redstone_lamp"), + new LegacyBlock(125, "wood_double_step"), new LegacyBlock(125, 1, "wood_double_step"), + new LegacyBlock(125, 2, "wood_double_step"), + new LegacyBlock(125, 3, "wood_double_step"), + new LegacyBlock(125, 4, "wood_double_step"), + new LegacyBlock(125, 5, "wood_double_step"), + new LegacyBlock(126, "wood_step", "oak_slab"), + new LegacyBlock(126, 1, "wood_step", "spruce_slab"), + new LegacyBlock(126, 2, "wood_step", "birch_slab"), + new LegacyBlock(126, 3, "wood_step", "jungle_slab"), + new LegacyBlock(126, 4, "wood_step", "acacia_slab"), + new LegacyBlock(126, 5, "wood_step", "dark_oak_slab"), new LegacyBlock(127, "cocoa"), + new LegacyBlock(128, "sandstone_stairs"), new LegacyBlock(129, "emerald_ore"), + new LegacyBlock(130, "ender_chest"), new LegacyBlock(131, "tripwire_hook"), + new LegacyBlock(132, "tripwire"), new LegacyBlock(133, "emerald_block"), + new LegacyBlock(134, "spruce_wood_stairs", "spruce_stairs"), + new LegacyBlock(135, "birch_wood_stairs", "birch_stairs"), + new LegacyBlock(136, "jungle_wood_stairs", "jungle_stairs"), + new LegacyBlock(137, "command", "command_block"), new LegacyBlock(138, "beacon"), + new LegacyBlock(139, "cobble_wall", "cobblestone_wall"), + new LegacyBlock(139, 1, "cobble_wall", "mossy_cobblestone_wall"), + new LegacyBlock(140, "flower_pot"), new LegacyBlock(141, "carrot", "carrots"), + new LegacyBlock(142, "potato", "potatoes"), + new LegacyBlock(143, "wood_button", "oak_button"), + new LegacyBlock(144, "skull", "skeleton_skull"), + new LegacyBlock(144, 1, "skull", "skeleton_wall_skull"), + new LegacyBlock(144, 2, "skull", "skeleton_wall_skull"), + new LegacyBlock(144, 3, "skull", "skeleton_wall_skull"), + new LegacyBlock(144, 4, "skull", "skeleton_wall_skull"), + new LegacyBlock(144, 5, "skull", "skeleton_wall_skull"), new LegacyBlock(145, "anvil"), + new LegacyBlock(145, 1, "anvil", "chipped_anvil"), + new LegacyBlock(145, 2, "anvil", "damaged_anvil"), + new LegacyBlock(146, "trapped_chest"), + new LegacyBlock(147, "gold_plate", "light_weighted_pressure_plate"), + new LegacyBlock(148, "iron_plate", "heavy_weighted_pressure_plate"), + new LegacyBlock(149, "redstone_comparator_off"), + new LegacyBlock(150, "redstone_comparator_on", "comparator"), + new LegacyBlock(151, "daylight_detector"), new LegacyBlock(152, "redstone_block"), + new LegacyBlock(153, "quartz_ore", "nether_quartz_ore"), new LegacyBlock(154, "hopper"), + new LegacyBlock(155, "quartz_block"), new LegacyBlock(156, "quartz_stairs"), + new LegacyBlock(157, "activator_rail"), new LegacyBlock(158, "dropper"), + new LegacyBlock(159, "stained_clay", "white_terracotta"), + new LegacyBlock(159, 1, "stained_clay", "orange_terracotta"), + new LegacyBlock(159, 2, "stained_clay", "magenta_terracotta"), + new LegacyBlock(159, 3, "stained_clay", "light_blue_terracotta"), + new LegacyBlock(159, 4, "stained_clay", "yellow_terracotta"), + new LegacyBlock(159, 5, "stained_clay", "lime_terracotta"), + new LegacyBlock(159, 6, "stained_clay", "pink_terracotta"), + new LegacyBlock(159, 7, "stained_clay", "gray_terracotta"), + new LegacyBlock(159, 8, "stained_clay", "light_gray_terracotta"), + new LegacyBlock(159, 9, "stained_clay", "cyan_terracotta"), + new LegacyBlock(159, 10, "stained_clay", "purple_terracotta"), + new LegacyBlock(159, 11, "stained_clay", "blue_terracotta"), + new LegacyBlock(159, 12, "stained_clay", "brown_terracotta"), + new LegacyBlock(159, 13, "stained_clay", "green_terracotta"), + new LegacyBlock(159, 14, "stained_clay", "red_terracotta"), + new LegacyBlock(159, 15, "stained_clay", "black_terracotta"), + new LegacyBlock(160, "stained_glass_pane", "white_stained_glass_pane"), + new LegacyBlock(160, 1, "stained_glass_pane", "orange_stained_glass_pane"), + new LegacyBlock(160, 2, "stained_glass_pane", "magenta_stained_glass_pane"), + new LegacyBlock(160, 3, "stained_glass_pane", "light_blue_stained_glass_pane"), + new LegacyBlock(160, 4, "stained_glass_pane", "yellow_stained_glass_pane"), + new LegacyBlock(160, 5, "stained_glass_pane", "lime_stained_glass_pane"), + new LegacyBlock(160, 6, "stained_glass_pane", "pink_stained_glass_pane"), + new LegacyBlock(160, 7, "stained_glass_pane", "gray_stained_glass_pane"), + new LegacyBlock(160, 8, "stained_glass_pane", "light_gray_stained_glass_pane"), + new LegacyBlock(160, 9, "stained_glass_pane", "cyan_stained_glass_pane"), + new LegacyBlock(160, 10, "stained_glass_pane", "purple_stained_glass_pane"), + new LegacyBlock(160, 11, "stained_glass_pane", "blue_stained_glass_pane"), + new LegacyBlock(160, 12, "stained_glass_pane", "brown_stained_glass_pane"), + new LegacyBlock(160, 13, "stained_glass_pane", "green_stained_glass_pane"), + new LegacyBlock(160, 14, "stained_glass_pane", "red_stained_glass_pane"), + new LegacyBlock(160, 15, "stained_glass_pane", "black_stained_glass_pane"), + new LegacyBlock(161, "leaves_2", "acacia_leaves"), + new LegacyBlock(161, 1, "leaves_2", "dark_oak_leaves"), + new LegacyBlock(162, "log_2", "acacia_log"), + new LegacyBlock(162, 1, "log_2", "spruce_log"), + new LegacyBlock(162, 2, "log_2", "birch_log"), + new LegacyBlock(162, 3, "log_2", "jungle_log"), + new LegacyBlock(163, "acacia_stairs", "acacia_stairs"), + new LegacyBlock(164, "dark_oak_stairs", "dark_oak_stairs"), + new LegacyBlock(165, "slime_block", "slime_block"), + new LegacyBlock(166, "barrier", "barrier"), + new LegacyBlock(167, "iron_trapdoor", "iron_trapdoor"), + new LegacyBlock(168, "prismarine"), + new LegacyBlock(168, 1, "prismarine", "prismarine_bricks"), + new LegacyBlock(168, 2, "prismarine", "dark_prismarine"), + new LegacyBlock(169, "sea_lantern"), new LegacyBlock(170, "hay_block"), + new LegacyBlock(171, "carpet", "white_carpet"), + new LegacyBlock(171, 1, "carpet", "orange_carpet"), + new LegacyBlock(171, 2, "carpet", "magenta_carpet"), + new LegacyBlock(171, 3, "carpet", "light_blue_carpet"), + new LegacyBlock(171, 4, "carpet", "yellow_carpet"), + new LegacyBlock(171, 5, "carpet", "lime_carpet"), + new LegacyBlock(171, 6, "carpet", "pink_carpet"), + new LegacyBlock(171, 7, "carpet", "gray_carpet"), + new LegacyBlock(171, 8, "carpet", "light_gray_carpet"), + new LegacyBlock(171, 9, "carpet", "cyan_carpet"), + new LegacyBlock(171, 10, "carpet", "purple_carpet"), + new LegacyBlock(171, 11, "carpet", "blue_carpet"), + new LegacyBlock(171, 12, "carpet", "brown_carpet"), + new LegacyBlock(171, 13, "carpet", "green_carpet"), + new LegacyBlock(171, 14, "carpet", "red_carpet"), + new LegacyBlock(171, 15, "carpet", "black_carpet"), + new LegacyBlock(172, "hard_clay", "terracotta"), new LegacyBlock(173, "coal_block"), + new LegacyBlock(174, "packed_ice"), new LegacyBlock(175, "double_plant", "sunflower"), + new LegacyBlock(175, 1, "double_plant", "lilac"), + new LegacyBlock(175, 2, "double_plant", "tall_grass"), + new LegacyBlock(175, 3, "double_plant", "large_fern"), + new LegacyBlock(175, 4, "double_plant", "rose_bush"), + new LegacyBlock(175, 5, "double_plant", "peony"), + new LegacyBlock(176, "standing_banner"), new LegacyBlock(177, "wall_banner"), + new LegacyBlock(178, "daylight_detector_inverted"), + new LegacyBlock(179, "red_sandstone", "red_sandstone"), + new LegacyBlock(179, 1, "red_sandstone", "chiseled_red_sandstone"), + new LegacyBlock(179, 2, "red_sandstone", "cut_red_sandstone"), + new LegacyBlock(180, "red_sandstone_stairs"), + new LegacyBlock(181, "double_stone_slab2"), + new LegacyBlock(181, 8, "double_stone_slab2", "smooth_red_sandstone"), + new LegacyBlock(182, "stone_slab2", "red_sandstone_slab"), + new LegacyBlock(183, "spruce_fence_gate"), new LegacyBlock(184, "birch_fence_gate"), + new LegacyBlock(185, "jungle_fence_gate"), new LegacyBlock(186, "dark_oak_fence_gate"), + new LegacyBlock(187, "acacia_fence_gate"), new LegacyBlock(188, "spruce_fence"), + new LegacyBlock(189, "birch_fence"), new LegacyBlock(190, "jungle_fence"), + new LegacyBlock(191, "dark_oak_fence"), new LegacyBlock(192, "acacia_fence"), + new LegacyBlock(193, "spruce_door"), new LegacyBlock(194, "birch_door"), + new LegacyBlock(195, "jungle_door"), new LegacyBlock(196, "acacia_door"), + new LegacyBlock(197, "dark_oak_door"), new LegacyBlock(198, "end_rod"), + new LegacyBlock(199, "chorus_plant"), new LegacyBlock(200, "chorus_flower"), + new LegacyBlock(201, "purpur_block"), new LegacyBlock(202, "purpur_pillar"), + new LegacyBlock(203, "purpur_stairs"), new LegacyBlock(204, "purpur_double_slab"), + new LegacyBlock(205, "purpur_slab"), + new LegacyBlock(206, "end_bricks", "end_stone_bricks"), + new LegacyBlock(207, "beetroot_block", "beetroots"), new LegacyBlock(208, "grass_path"), + new LegacyBlock(209, "end_gateway"), + new LegacyBlock(210, "command_repeating", "repeating_command_block"), + new LegacyBlock(211, "command_chain", "chain_command_block"), + new LegacyBlock(212, "frosted_ice"), new LegacyBlock(213, "magma", "magma_block"), + new LegacyBlock(214, "nether_wart_block"), + new LegacyBlock(215, "red_nether_brick", "red_nether_bricks"), + new LegacyBlock(216, "bone_block"), new LegacyBlock(217, "structure_void"), + new LegacyBlock(218, "observer"), new LegacyBlock(219, "white_shulker_box"), + new LegacyBlock(220, "orange_shulker_box"), new LegacyBlock(221, "magenta_shulker_box"), + new LegacyBlock(222, "light_blue_shulker_box"), + new LegacyBlock(223, "yellow_shulker_box"), new LegacyBlock(224, "lime_shulker_box"), + new LegacyBlock(225, "pink_shulker_box"), new LegacyBlock(226, "gray_shulker_box"), + new LegacyBlock(227, "silver_shulker_box", "light_gray_shulker_box"), + new LegacyBlock(228, "cyan_shulker_box"), new LegacyBlock(229, "purple_shulker_box"), + new LegacyBlock(230, "blue_shulker_box"), new LegacyBlock(231, "brown_shulker_box"), + new LegacyBlock(232, "green_shulker_box"), new LegacyBlock(233, "red_shulker_box"), + new LegacyBlock(234, "black_shulker_box"), + new LegacyBlock(235, "white_glazed_terracotta"), + new LegacyBlock(236, "orange_glazed_terracotta"), + new LegacyBlock(237, "magenta_glazed_terracotta"), + new LegacyBlock(238, "light_blue_glazed_terracotta"), + new LegacyBlock(239, "yellow_glazed_terracotta"), + new LegacyBlock(240, "lime_glazed_terracotta"), + new LegacyBlock(241, "pink_glazed_terracotta"), + new LegacyBlock(242, "gray_glazed_terracotta"), + new LegacyBlock(243, "silver_glazed_terracotta", "light_gray_glazed_terracotta"), + new LegacyBlock(244, "cyan_glazed_terracotta"), + new LegacyBlock(245, "purple_glazed_terracotta"), + new LegacyBlock(246, "blue_glazed_terracotta"), + new LegacyBlock(247, "brown_glazed_terracotta"), + new LegacyBlock(248, "green_glazed_terracotta"), + new LegacyBlock(249, "red_glazed_terracotta"), + new LegacyBlock(250, "black_glazed_terracotta"), + new LegacyBlock(251, "concrete", "white_concrete"), + new LegacyBlock(251, 1, "concrete", "orange_concrete"), + new LegacyBlock(251, 2, "concrete", "magenta_concrete"), + new LegacyBlock(251, 3, "concrete", "light_blue_concrete"), + new LegacyBlock(251, 4, "concrete", "yellow_concrete"), + new LegacyBlock(251, 5, "concrete", "lime_concrete"), + new LegacyBlock(251, 6, "concrete", "pink_concrete"), + new LegacyBlock(251, 7, "concrete", "gray_concrete"), + new LegacyBlock(251, 8, "concrete", "light_gray_concrete"), + new LegacyBlock(251, 9, "concrete", "cyan_concrete"), + new LegacyBlock(251, 10, "concrete", "purple_concrete"), + new LegacyBlock(251, 11, "concrete", "blue_concrete"), + new LegacyBlock(251, 12, "concrete", "brown_concrete"), + new LegacyBlock(251, 13, "concrete", "green_concrete"), + new LegacyBlock(251, 14, "concrete", "red_concrete"), + new LegacyBlock(251, 15, "concrete", "black_concrete"), + new LegacyBlock(252, "concrete_powder", "white_concrete_powder"), + new LegacyBlock(252, 1, "concrete_powder", "orange_concrete_powder"), + new LegacyBlock(252, 2, "concrete_powder", "magenta_concrete_powder"), + new LegacyBlock(252, 3, "concrete_powder", "light_blue_concrete_powder"), + new LegacyBlock(252, 4, "concrete_powder", "yellow_concrete_powder"), + new LegacyBlock(252, 5, "concrete_powder", "lime_concrete_powder"), + new LegacyBlock(252, 6, "concrete_powder", "pink_concrete_powder"), + new LegacyBlock(252, 7, "concrete_powder", "gray_concrete_powder"), + new LegacyBlock(252, 8, "concrete_powder", "light_gray_concrete_powder"), + new LegacyBlock(252, 9, "concrete_powder", "cyan_concrete_powder"), + new LegacyBlock(252, 10, "concrete_powder", "purple_concrete_powder"), + new LegacyBlock(252, 11, "concrete_powder", "blue_concrete_powder"), + new LegacyBlock(252, 12, "concrete_powder", "brown_concrete_powder"), + new LegacyBlock(252, 13, "concrete_powder", "green_concrete_powder"), + new LegacyBlock(252, 14, "concrete_powder", "red_concrete_powder"), + new LegacyBlock(252, 15, "concrete_powder", "black_concrete_powder"), + new LegacyBlock(255, "structure_block"), + new LegacyBlock(256, "iron_spade", "iron_shovel"), new LegacyBlock(257, "iron_pickaxe"), + new LegacyBlock(258, "iron_axe"), new LegacyBlock(259, "flint_and_steel"), + new LegacyBlock(260, "apple"), new LegacyBlock(261, "bow"), + new LegacyBlock(262, "arrow"), new LegacyBlock(263, "coal"), + new LegacyBlock(263, 1, "coal", "charcoal"), new LegacyBlock(264, "diamond"), + new LegacyBlock(265, "iron_ingot"), new LegacyBlock(266, "gold_ingot"), + new LegacyBlock(267, "iron_sword"), new LegacyBlock(268, "wood_sword", "wooden_sword"), + new LegacyBlock(269, "wood_spade", "wooden_shovel"), + new LegacyBlock(270, "wood_pickaxe", "wooden_pickaxe"), + new LegacyBlock(271, "wood_axe", "wooden_axe"), new LegacyBlock(272, "stone_sword"), + new LegacyBlock(273, "stone_spade", "stone_shovel"), + new LegacyBlock(274, "stone_pickaxe"), new LegacyBlock(275, "stone_axe"), + new LegacyBlock(276, "diamond_sword"), + new LegacyBlock(277, "diamond_spade", "diamond_shovel"), + new LegacyBlock(278, "diamond_pickaxe"), new LegacyBlock(279, "diamond_axe"), + new LegacyBlock(280, "stick"), new LegacyBlock(281, "bowl"), + new LegacyBlock(282, "mushroom_soup", "mushroom_stew"), + new LegacyBlock(283, "gold_sword", "golden_sword"), + new LegacyBlock(284, "gold_spade", "golden_shovel"), + new LegacyBlock(285, "gold_pickaxe", "golden_pickaxe"), + new LegacyBlock(286, "gold_axe", "golden_axe"), new LegacyBlock(287, "string"), + new LegacyBlock(288, "feather"), new LegacyBlock(289, "sulphur", "gunpowder"), + new LegacyBlock(290, "wood_hoe", "wooden_hoe"), new LegacyBlock(291, "stone_hoe"), + new LegacyBlock(292, "iron_hoe"), new LegacyBlock(293, "diamond_hoe"), + new LegacyBlock(294, "gold_hoe", "golden_hoe"), + new LegacyBlock(295, "seeds", "wheat_seeds"), new LegacyBlock(296, "wheat"), + new LegacyBlock(297, "bread"), new LegacyBlock(298, "leather_helmet"), + new LegacyBlock(299, "leather_chestplate"), new LegacyBlock(300, "leather_leggings"), + new LegacyBlock(301, "leather_boots"), new LegacyBlock(302, "chainmail_helmet"), + new LegacyBlock(303, "chainmail_chestplate"), + new LegacyBlock(304, "chainmail_leggings"), new LegacyBlock(305, "chainmail_boots"), + new LegacyBlock(306, "iron_helmet"), new LegacyBlock(307, "iron_chestplate"), + new LegacyBlock(308, "iron_leggings"), new LegacyBlock(309, "iron_boots"), + new LegacyBlock(310, "diamond_helmet"), new LegacyBlock(311, "diamond_chestplate"), + new LegacyBlock(312, "diamond_leggings"), new LegacyBlock(313, "diamond_boots"), + new LegacyBlock(314, "gold_helmet", "golden_helmet"), + new LegacyBlock(315, "gold_chestplate", "golden_chestplate"), + new LegacyBlock(316, "gold_leggings", "golden_leggings"), + new LegacyBlock(317, "gold_boots", "golden_boots"), new LegacyBlock(318, "flint"), + new LegacyBlock(319, "pork", "porkchop"), + new LegacyBlock(320, "grilled_pork", "cooked_porkchop"), + new LegacyBlock(321, "painting"), new LegacyBlock(322, "golden_apple", "golden_apple"), + new LegacyBlock(322, 1, "golden_apple", "enchanted_golden_apple"), + new LegacyBlock(323, "sign"), new LegacyBlock(324, "wood_door", "oak_door"), + new LegacyBlock(325, "bucket"), new LegacyBlock(326, "water_bucket"), + new LegacyBlock(327, "lava_bucket"), new LegacyBlock(328, "minecart"), + new LegacyBlock(329, "saddle"), new LegacyBlock(330, "iron_door"), + new LegacyBlock(331, "redstone"), new LegacyBlock(332, "snow_ball", "snowball"), + new LegacyBlock(333, "boat", "oak_boat"), new LegacyBlock(334, "leather"), + new LegacyBlock(335, "milk_bucket"), new LegacyBlock(336, "clay_brick", "brick"), + new LegacyBlock(337, "clay_ball"), new LegacyBlock(338, "sugar_cane"), + new LegacyBlock(339, "paper"), new LegacyBlock(340, "book"), + new LegacyBlock(341, "slime_ball"), + new LegacyBlock(342, "storage_minecart", "chest_minecart"), + new LegacyBlock(343, "powered_minecart", "furnace_minecart"), + new LegacyBlock(344, "egg"), new LegacyBlock(345, "compass"), + new LegacyBlock(346, "fishing_rod"), new LegacyBlock(347, "watch", "clock"), + new LegacyBlock(348, "glowstone_dust"), new LegacyBlock(349, "raw_fish", "cod"), + new LegacyBlock(349, 1, "raw_fish", "salmon"), + new LegacyBlock(349, 2, "raw_fish", "tropical_fish"), + new LegacyBlock(349, 3, "raw_fish", "pufferfish"), + new LegacyBlock(350, "cooked_fish", "cooked_cod"), + new LegacyBlock(350, 1, "cooked_fish", "cooked_salmon"), + new LegacyBlock(351, "ink_sack", "ink_sac"), + new LegacyBlock(351, 1, "ink_sack", "rose_red"), + new LegacyBlock(351, 2, "ink_sack", "cactus_green"), + new LegacyBlock(351, 3, "ink_sack", "cocoa_beans"), + new LegacyBlock(351, 4, "ink_sack", "lapis_lazuli"), + new LegacyBlock(351, 5, "ink_sack", "purple_dye"), + new LegacyBlock(351, 6, "ink_sack", "cyan_dye"), + new LegacyBlock(351, 7, "ink_sack", "light_gray_dye"), + new LegacyBlock(351, 8, "ink_sack", "gray_dye"), + new LegacyBlock(351, 9, "ink_sack", "pink_dye"), + new LegacyBlock(351, 10, "ink_sack", "lime_dye"), + new LegacyBlock(351, 11, "ink_sack", "dandelion_yellow"), + new LegacyBlock(351, 12, "ink_sack", "light_blue_dye"), + new LegacyBlock(351, 13, "ink_sack", "magenta_dye"), + new LegacyBlock(351, 14, "ink_sack", "orange_dye"), + new LegacyBlock(351, 15, "ink_sack", "bone_meal"), new LegacyBlock(352, "bone"), + new LegacyBlock(353, "sugar", "sugar"), new LegacyBlock(354, "cake", "cake"), + new LegacyBlock(355, "bed", "white_bed"), new LegacyBlock(355, 1, "bed", "orange_bed"), + new LegacyBlock(355, 2, "bed", "magenta_bed"), + new LegacyBlock(355, 3, "bed", "light_blue_bed"), + new LegacyBlock(355, 4, "bed", "yellow_bed"), + new LegacyBlock(355, 5, "bed", "lime_bed"), new LegacyBlock(355, 6, "bed", "pink_bed"), + new LegacyBlock(355, 7, "bed", "gray_bed"), + new LegacyBlock(355, 8, "bed", "light_gray_bed"), + new LegacyBlock(355, 9, "bed", "cyan_bed"), + new LegacyBlock(355, 10, "bed", "purple_bed"), + new LegacyBlock(355, 11, "bed", "blue_bed"), + new LegacyBlock(355, 12, "bed", "brown_bed"), + new LegacyBlock(355, 13, "bed", "green_bed"), + new LegacyBlock(355, 14, "bed", "red_bed"), + new LegacyBlock(355, 15, "bed", "black_bed"), new LegacyBlock(356, "diode", "repeater"), + new LegacyBlock(357, "cookie", "cookie"), new LegacyBlock(358, "map"), + new LegacyBlock(359, "shears"), new LegacyBlock(360, "melon", "melon"), + new LegacyBlock(361, "pumpkin_seeds", "pumpkin_seeds"), + new LegacyBlock(362, "melon_seeds", "melon_seeds"), + new LegacyBlock(363, "raw_beef", "beef"), new LegacyBlock(364, "cooked_beef"), + new LegacyBlock(365, "raw_chicken", "chicken"), new LegacyBlock(366, "cooked_chicken"), + new LegacyBlock(367, "rotten_flesh"), new LegacyBlock(368, "ender_pearl"), + new LegacyBlock(369, "blaze_rod"), new LegacyBlock(370, "ghast_tear"), + new LegacyBlock(371, "gold_nugget"), + new LegacyBlock(372, "nether_stalk", "nether_wart"), + new LegacyBlock(373, "potion", "potion"), new LegacyBlock(374, "glass_bottle"), + new LegacyBlock(375, "spider_eye"), new LegacyBlock(376, "fermented_spider_eye"), + new LegacyBlock(377, "blaze_powder"), new LegacyBlock(378, "magma_cream"), + new LegacyBlock(379, "brewing_stand_item", "brewing_stand"), + new LegacyBlock(380, "cauldron_item", "cauldron"), + new LegacyBlock(381, "eye_of_ender", "ender_eye"), + new LegacyBlock(382, "speckled_melon"), new LegacyBlock(383, "monster_egg"), + new LegacyBlock(383, 4, "monster_egg", "elder_guardian_spawn_egg"), + new LegacyBlock(383, 5, "monster_egg", "wither_skeleton_spawn_egg"), + new LegacyBlock(383, 6, "monster_egg", "stray_spawn_egg"), + new LegacyBlock(383, 23, "monster_egg", "husk_spawn_egg"), + new LegacyBlock(383, 27, "monster_egg", "zombe_villager_spawn_egg"), + new LegacyBlock(383, 28, "monster_egg", "skeleton_horse_spawn_egg"), + new LegacyBlock(383, 29, "monster_egg", "zombie_horse_spawn_egg"), + new LegacyBlock(383, 31, "monster_egg", "donkey_spawn_egg"), + new LegacyBlock(383, 32, "monster_egg", "mule_spawn_egg"), + new LegacyBlock(383, 34, "monster_egg", "evocation_illager_spawn_egg"), + new LegacyBlock(383, 35, "monster_egg", "vex_spawn_egg"), + new LegacyBlock(383, 36, "monster_egg", "vindication_illager_spawn_egg"), + new LegacyBlock(383, 50, "monster_egg", "creeper_spawn_egg"), + new LegacyBlock(383, 51, "monster_egg", "skeleton_spawn_egg"), + new LegacyBlock(383, 52, "monster_egg", "spider_spawn_egg"), + new LegacyBlock(383, 54, "monster_egg", "zombie_spawn_egg"), + new LegacyBlock(383, 55, "monster_egg", "slime_spawn_egg"), + new LegacyBlock(383, 56, "monster_egg", "ghast_spawn_egg"), + new LegacyBlock(383, 57, "monster_egg", "zombie_pigman_spawn_egg"), + new LegacyBlock(383, 58, "monster_egg", "enderman_spawn_egg"), + new LegacyBlock(383, 59, "monster_egg", "cave_spider_spawn_egg"), + new LegacyBlock(383, 60, "monster_egg", "silverfish_spawn_egg"), + new LegacyBlock(383, 61, "monster_egg", "blaze_spawn_egg"), + new LegacyBlock(383, 62, "monster_egg", "magma_cube_spawn_egg"), + new LegacyBlock(383, 65, "monster_egg", "bat_spawn_egg"), + new LegacyBlock(383, 66, "monster_egg", "witch_spawn_egg"), + new LegacyBlock(383, 67, "monster_egg", "endermite_spawn_egg"), + new LegacyBlock(383, 68, "monster_egg", "guardian_spawn_egg"), + new LegacyBlock(383, 69, "monster_egg", "shulker_spawn_egg"), + new LegacyBlock(383, 90, "monster_egg", "pig_spawn_egg"), + new LegacyBlock(383, 91, "monster_egg", "sheep_spawn_egg"), + new LegacyBlock(383, 92, "monster_egg", "cow_spawn_egg"), + new LegacyBlock(383, 93, "monster_egg", "chicken_spawn_egg"), + new LegacyBlock(383, 94, "monster_egg", "squid_spawn_egg"), + new LegacyBlock(383, 95, "monster_egg", "wolf_spawn_egg"), + new LegacyBlock(383, 96, "monster_egg", "mooshroom_spawn_egg"), + new LegacyBlock(383, 98, "monster_egg", "ocelot_spawn_egg"), + new LegacyBlock(383, 100, "monster_egg", "horse_spawn_egg"), + new LegacyBlock(383, 101, "monster_egg", "rabbit_spawn_egg"), + new LegacyBlock(383, 102, "monster_egg", "polar_bear_spawn_egg"), + new LegacyBlock(383, 103, "monster_egg", "llama_spawn_egg"), + new LegacyBlock(383, 120, "monster_egg", "villager_spawn_egg"), + new LegacyBlock(384, "exp_bottle", "experience_bottle"), + new LegacyBlock(385, "fireball", "fire_charge"), + new LegacyBlock(386, "book_and_quill", "writable_book"), + new LegacyBlock(387, "written_book"), new LegacyBlock(388, "emerald"), + new LegacyBlock(389, "item_frame"), + new LegacyBlock(390, "flower_pot_item", "flower_pot"), + new LegacyBlock(391, "carrot_item", "carrot"), + new LegacyBlock(392, "potato_item", "potato"), new LegacyBlock(393, "baked_potato"), + new LegacyBlock(394, "poisonous_potato"), new LegacyBlock(395, "empty_map", "map"), + new LegacyBlock(396, "golden_carrot"), + new LegacyBlock(397, "skull_item", "skeleton_skull"), + new LegacyBlock(397, 1, "skull_item", "wither_skeleton_skull"), + new LegacyBlock(397, 2, "skull_item", "zombie_head"), + new LegacyBlock(397, 3, "skull_item", "player_head"), + new LegacyBlock(397, 4, "skull_item", "creeper_head"), + new LegacyBlock(397, 5, "skull_item", "dragon_head"), + new LegacyBlock(398, "carrot_stick"), new LegacyBlock(399, "nether_star"), + new LegacyBlock(400, "pumpkin_pie"), + new LegacyBlock(401, "firework", "firework_rocket"), + new LegacyBlock(402, "firework_charge", "firework_star"), + new LegacyBlock(403, "enchanted_book"), + new LegacyBlock(404, "redstone_comparator", "comparator"), + new LegacyBlock(405, "nether_brick_item", "nether_brick"), + new LegacyBlock(406, "quartz"), + new LegacyBlock(407, "explosive_minecart", "tnt_minecart"), + new LegacyBlock(408, "hopper_minecart"), new LegacyBlock(409, "prismarine_shard"), + new LegacyBlock(410, "prismarine_crystals"), new LegacyBlock(411, "rabbit"), + new LegacyBlock(412, "cooked_rabbit"), new LegacyBlock(413, "rabbit_stew"), + new LegacyBlock(414, "rabbit_foot"), new LegacyBlock(415, "rabbit_hide"), + new LegacyBlock(416, "armor_stand"), + new LegacyBlock(417, "iron_barding", "iron_horse_armor"), + new LegacyBlock(418, "gold_barding", "gold_horse_armor"), + new LegacyBlock(419, "diamond_barding", "diamond_horse_armor"), + new LegacyBlock(420, "leash", "lead"), new LegacyBlock(421, "name_tag"), + new LegacyBlock(422, "command_minecart", "command_block_minecart"), + new LegacyBlock(423, "mutton"), new LegacyBlock(424, "cooked_mutton"), + new LegacyBlock(425, "banner", "white_banner"), + new LegacyBlock(425, 1, "banner", "orange_banner"), + new LegacyBlock(425, 2, "banner", "magenta_banner"), + new LegacyBlock(425, 3, "banner", "light_blue_banner"), + new LegacyBlock(425, 4, "banner", "yellow_banner"), + new LegacyBlock(425, 5, "banner", "lime_banner"), + new LegacyBlock(425, 6, "banner", "pink_banner"), + new LegacyBlock(425, 7, "banner", "gray_banner"), + new LegacyBlock(425, 8, "banner", "light_gray_banner"), + new LegacyBlock(425, 9, "banner", "cyan_banner"), + new LegacyBlock(425, 10, "banner", "purple_banner"), + new LegacyBlock(425, 11, "banner", "blue_banner"), + new LegacyBlock(425, 12, "banner", "brown_banner"), + new LegacyBlock(425, 13, "banner", "green_banner"), + new LegacyBlock(425, 14, "banner", "red_banner"), + new LegacyBlock(425, 15, "banner", "black_banner"), new LegacyBlock(426, "end_crystal"), + new LegacyBlock(427, "spruce_door_item", "spruce_door"), + new LegacyBlock(428, "birch_door_item", "birch_door"), + new LegacyBlock(429, "jungle_door_item", "jungle_door"), + new LegacyBlock(430, "acacia_door_item", "acacia_door"), + new LegacyBlock(431, "dark_oak_door_item", "dark_oak_door"), + new LegacyBlock(432, "chorus_fruit"), new LegacyBlock(433, "chorus_fruit_popped"), + new LegacyBlock(434, "beetroot"), new LegacyBlock(435, "beetroot_seeds"), + new LegacyBlock(436, "beetroot_soup"), + new LegacyBlock(437, "dragons_breath", "dragon_breath"), + new LegacyBlock(438, "splash_potion"), new LegacyBlock(439, "spectral_arrow"), + new LegacyBlock(440, "tipped_arrow"), new LegacyBlock(441, "lingering_potion"), + new LegacyBlock(442, "shield"), new LegacyBlock(443, "elytra"), + new LegacyBlock(444, "boat_spruce", "spruce_boat"), + new LegacyBlock(445, "boat_birch", "birch_boat"), + new LegacyBlock(446, "boat_jungle", "jungle_boat"), + new LegacyBlock(447, "boat_acacia", "acacia_boat"), + new LegacyBlock(448, "boat_dark_oak", "dark_oak_boat"), + new LegacyBlock(449, "totem", "totem_of_undying"), + new LegacyBlock(450, "shulker_shell"), new LegacyBlock(452, "iron_nugget"), + new LegacyBlock(453, "knowledge_book"), + new LegacyBlock(2256, "gold_record", "music_disc_13"), + new LegacyBlock(2257, "green_record", "music_disc_cat"), + new LegacyBlock(2258, "record_3", "music_disc_blocks"), + new LegacyBlock(2259, "record_4", "music_disc_chirp"), + new LegacyBlock(2260, "record_5", "music_disc_far"), + new LegacyBlock(2261, "record_6", "music_disc_mall"), + new LegacyBlock(2262, "record_7", "music_disc_mellohi"), + new LegacyBlock(2263, "record_8", "music_disc_stal"), + new LegacyBlock(2264, "record_9", "music_disc_strad"), + new LegacyBlock(2265, "record_10", "music_disc_ward"), + new LegacyBlock(2266, "record_11", "music_disc_11"), + new LegacyBlock(2267, "record_12", "music_disc_wait")}; + + private static final Map LEGACY_ID_TO_STRING_PLOT_BLOCK = new HashMap<>(); + private static final Map LEGACY_ID_AND_DATA_TO_STRING_PLOT_BLOCK = + new HashMap<>(); + private static final Map NEW_STRING_TO_LEGACY_PLOT_BLOCK = new HashMap<>(); + private static final Map OLD_STRING_TO_STRING_PLOT_BLOCK = new HashMap<>(); + + public BukkitLegacyMappings() { + for (final LegacyBlock legacyBlock : BLOCKS) { + LEGACY_ID_TO_STRING_PLOT_BLOCK + .put(legacyBlock.getNumericalId(), legacyBlock.toStringPlotBlock()); + if (legacyBlock.getDataValue() != 0) { + LEGACY_ID_AND_DATA_TO_STRING_PLOT_BLOCK + .put(new IdDataPair(legacyBlock.getNumericalId(), legacyBlock.getDataValue()), + legacyBlock.toStringPlotBlock()); + } + NEW_STRING_TO_LEGACY_PLOT_BLOCK + .put(legacyBlock.getLegacyName(), legacyBlock.toStringPlotBlock()); + OLD_STRING_TO_STRING_PLOT_BLOCK + .put(legacyBlock.getNewName(), legacyBlock.toLegacyPlotBlock()); + Material material; + try { + material = Material.valueOf(legacyBlock.getNewName()); + } catch (final Exception e) { + material = Material.getMaterial(legacyBlock.getLegacyName(), true); + } + legacyBlock.material = material; + } + } + + public Collection getPlotBlocks() { + return Arrays.stream(BLOCKS).map(block -> PlotBlock.get(block.getNewName())) + .collect(Collectors.toList()); + } + + public StringComparison.ComparisonResult getClosestsMatch( + @NonNull final String string) { + final StringComparison comparison = + new StringComparison<>(string, getPlotBlocks()); + return comparison.getBestMatchAdvanced(); + } + + /** + * Try to find a legacy plot block by any means possible. + * Strategy: + * - Check if the name contains a namespace, if so, strip it + * - Check if there's a (new) material matching the name + * - Check if there's a legacy material matching the name + * - Check if there's a numerical ID matching the name + * - Return null if everything else fails + * + * @param string String ID + * @return LegacyBlock if found, else null + */ + public PlotBlock fromAny(@NonNull final String string) { + String workingString = string; + String[] parts = null; + if (string.contains(":")) { + parts = string.split(":"); + if (parts.length > 1) { + if (parts[0].equalsIgnoreCase("minecraft")) { + workingString = parts[1]; + } else { + workingString = parts[0]; + } + } + } + PlotBlock plotBlock = fromStringToLegacy(workingString); + if (plotBlock != null) { + return plotBlock; + } else if ((plotBlock = fromLegacyToString(workingString)) != null) { + return plotBlock; + } else { + try { + if (parts != null && parts.length > 1) { + final int id = Integer.parseInt(parts[0]); + final int data = Integer.parseInt(parts[1]); + return fromLegacyToString(id, data); + } else { + return fromLegacyToString(Integer.parseInt(workingString)); + } + } catch (final Throwable exception) { + return null; + } + } + } + + public PlotBlock fromLegacyToString(final int id) { + return LEGACY_ID_TO_STRING_PLOT_BLOCK.get(id); + } + + public PlotBlock fromLegacyToString(final int id, final int data) { + if (data == 0) { + return fromLegacyToString(id); + } + return LEGACY_ID_AND_DATA_TO_STRING_PLOT_BLOCK.get(new IdDataPair(id, data)); + } + + public PlotBlock fromLegacyToString(final String id) { + return NEW_STRING_TO_LEGACY_PLOT_BLOCK.get(id); + } + + public PlotBlock fromStringToLegacy(final String id) { + return OLD_STRING_TO_STRING_PLOT_BLOCK.get(id.toLowerCase(Locale.ENGLISH)); + } + + @Getter @EqualsAndHashCode @ToString @RequiredArgsConstructor + private static final class IdDataPair { + private final int id; + private final int data; + } + + + @Getter @RequiredArgsConstructor(access = AccessLevel.PRIVATE) + public static final class LegacyBlock { + + private final int numericalId; + private final int dataValue; + private final String legacyName; + private final String newName; + + private Material material; + + LegacyBlock(final int numericalId, final int dataValue, @NonNull final String legacyName) { + this(numericalId, dataValue, legacyName, legacyName); + } + + LegacyBlock(final int numericalId, @NonNull final String legacyName, + @NonNull final String newName) { + this(numericalId, 0, legacyName, newName); + } + + LegacyBlock(final int numericalId, @NonNull final String legacyName) { + this(numericalId, legacyName, legacyName); + } + + PlotBlock toStringPlotBlock() { + return StringPlotBlock.get(newName); + } + + PlotBlock toLegacyPlotBlock() { + return LegacyPlotBlock.get(numericalId, dataValue); + } + + @Override public String toString() { + return this.newName; + } + } + +} diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSchematicHandler.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSchematicHandler.java new file mode 100644 index 000000000..ea115b14a --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSchematicHandler.java @@ -0,0 +1,220 @@ +package com.github.intellectualsites.plotsquared.bukkit.util; + +import com.github.intellectualsites.plotsquared.bukkit.object.schematic.StateWrapper; +import com.github.intellectualsites.plotsquared.plot.object.ChunkLoc; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.RegionWrapper; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; +import com.sk89q.jnbt.*; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.regions.CuboidRegion; +import com.sk89q.worldedit.world.block.BaseBlock; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.World; + +import java.io.ByteArrayOutputStream; +import java.util.*; + +/** + * Schematic Handler. + */ +public class BukkitSchematicHandler extends SchematicHandler { + + @Override public void getCompoundTag(final String world, final Set regions, + final RunnableVal whenDone) { + // async + TaskManager.runTaskAsync(new Runnable() { + @Override public void run() { + // Main positions + Location[] corners = MainUtil.getCorners(world, regions); + final Location bot = corners[0]; + Location top = corners[1]; + + CuboidRegion cuboidRegion = + new CuboidRegion(BukkitUtil.IMP.getWeWorld(world), bot.getBlockVector3(), + top.getBlockVector3()); + + final int width = top.getX() - bot.getX() + 1; + int height = top.getY() - bot.getY() + 1; + final int length = top.getZ() - bot.getZ() + 1; + Map schematic = new HashMap<>(); + schematic.put("Version", new IntTag(1)); + + Map metadata = new HashMap<>(); + metadata.put("WEOffsetX", new IntTag(0)); + metadata.put("WEOffsetY", new IntTag(0)); + metadata.put("WEOffsetZ", new IntTag(0)); + + schematic.put("Metadata", new CompoundTag(metadata)); + + schematic.put("Width", new ShortTag((short) width)); + schematic.put("Height", new ShortTag((short) height)); + schematic.put("Length", new ShortTag((short) length)); + + // The Sponge format Offset refers to the 'min' points location in the world. That's our 'Origin' + schematic.put("Offset", new IntArrayTag(new int[] {0, 0, 0,})); + + final int[] paletteMax = {0}; + Map palette = new HashMap<>(); + + List tileEntities = new ArrayList<>(); + ByteArrayOutputStream buffer = new ByteArrayOutputStream(width * height * length); + // Queue + final ArrayDeque queue = new ArrayDeque<>(regions); + TaskManager.runTask(new Runnable() { + @Override public void run() { + if (queue.isEmpty()) { + TaskManager.runTaskAsync(new Runnable() { + @Override public void run() { + schematic.put("PaletteMax", new IntTag(paletteMax[0])); + + Map paletteTag = new HashMap<>(); + palette.forEach( + (key, value) -> paletteTag.put(key, new IntTag(value))); + + schematic.put("Palette", new CompoundTag(paletteTag)); + schematic + .put("BlockData", new ByteArrayTag(buffer.toByteArray())); + schematic.put("TileEntities", + new ListTag(CompoundTag.class, tileEntities)); + whenDone.value = new CompoundTag(schematic); + TaskManager.runTask(whenDone); + System.gc(); + System.gc(); + } + }); + return; + } + final Runnable regionTask = this; + RegionWrapper region = queue.poll(); + Location pos1 = new Location(world, region.minX, region.minY, region.minZ); + Location pos2 = new Location(world, region.maxX, region.maxY, region.maxZ); + final int bx = bot.getX(); + final int bz = bot.getZ(); + final int p1x = pos1.getX(); + final int p1z = pos1.getZ(); + final int p2x = pos2.getX(); + final int p2z = pos2.getZ(); + final int bcx = p1x >> 4; + final int bcz = p1z >> 4; + final int tcx = p2x >> 4; + final int tcz = p2z >> 4; + final int sy = pos1.getY(); + final int ey = pos2.getY(); + // Generate list of chunks + final ArrayList chunks = new ArrayList<>(); + for (int x = bcx; x <= tcx; x++) { + for (int z = bcz; z <= tcz; z++) { + chunks.add(new ChunkLoc(x, z)); + } + } + final World worldObj = Bukkit.getWorld(world); + // Main thread + TaskManager.runTask(new Runnable() { + @Override public void run() { + long start = System.currentTimeMillis(); + while (!chunks.isEmpty() + && System.currentTimeMillis() - start < 20) { + // save schematics + ChunkLoc chunk = chunks.remove(0); + Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z); + if (!bc.load(false)) { + continue; + } + int X = chunk.x; + int Z = chunk.z; + int xxb = X << 4; + int zzb = Z << 4; + int xxt = xxb + 15; + int zzt = zzb + 15; + + if (X == bcx) { + xxb = p1x; + } + if (X == tcx) { + xxt = p2x; + } + if (Z == bcz) { + zzb = p1z; + } + if (Z == tcz) { + zzt = p2z; + } + for (int y = sy; y <= Math.min(255, ey); y++) { + int ry = y - sy; + int i1 = ry * width * length; + for (int z = zzb; z <= zzt; z++) { + int rz = z - bz; + int i2 = i1 + rz * width; + for (int x = xxb; x <= xxt; x++) { + int rx = x - bx; + int index = i2 + rx; + BlockVector3 point = BlockVector3.at(x, y, z); + BaseBlock block = + cuboidRegion.getWorld().getFullBlock(point); + if (block.getNbtData() != null) { + Map values = new HashMap<>(); + for (Map.Entry entry : block + .getNbtData().getValue().entrySet()) { + values + .put(entry.getKey(), entry.getValue()); + } + + values.remove( + "id"); // Remove 'id' if it exists. We want 'Id' + + // Positions are kept in NBT, we don't want that. + values.remove("x"); + values.remove("y"); + values.remove("z"); + + values + .put("Id", new StringTag(block.getNbtId())); + values.put("Pos", + new IntArrayTag(new int[] {x, y, z})); + + tileEntities.add(new CompoundTag(values)); + } + String blockKey = + block.toImmutableState().getAsString(); + int blockId; + if (palette.containsKey(blockKey)) { + blockId = palette.get(blockKey); + } else { + blockId = paletteMax[0]; + palette.put(blockKey, blockId); + paletteMax[0]++; + } + + while ((blockId & -128) != 0) { + buffer.write(blockId & 127 | 128); + blockId >>>= 7; + } + buffer.write(blockId); + } + } + } + } + if (!chunks.isEmpty()) { + TaskManager.runTaskLater(this, 1); + } else { + regionTask.run(); + } + } + }); + } + }); + } + }); + } + + @Override + public boolean restoreTile(LocalBlockQueue queue, CompoundTag ct, int x, int y, int z) { + return new StateWrapper(ct).restoreTag(queue.getWorld(), x, y, z); + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java similarity index 67% rename from Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java index 04d1b2d07..efdb034cd 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java @@ -1,33 +1,29 @@ -package com.plotsquared.bukkit.util; +package com.github.intellectualsites.plotsquared.bukkit.util; + +import com.github.intellectualsites.plotsquared.bukkit.generator.BukkitPlotGenerator; +import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection; +import com.github.intellectualsites.plotsquared.configuration.file.YamlConfiguration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.ConfigurationNode; +import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.SetupObject; +import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; +import org.bukkit.*; +import org.bukkit.World.Environment; +import org.bukkit.entity.Player; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.plugin.Plugin; -import com.intellectualcrafters.configuration.ConfigurationSection; -import com.intellectualcrafters.configuration.file.YamlConfiguration; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.ConfigurationNode; -import com.intellectualcrafters.plot.generator.GeneratorWrapper; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.SetupObject; -import com.intellectualcrafters.plot.util.SetupUtils; -import com.plotsquared.bukkit.generator.BukkitPlotGenerator; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map.Entry; import java.util.Objects; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.World; -import org.bukkit.World.Environment; -import org.bukkit.WorldCreator; -import org.bukkit.WorldType; -import org.bukkit.entity.Player; -import org.bukkit.generator.ChunkGenerator; -import org.bukkit.plugin.Plugin; public class BukkitSetupUtils extends SetupUtils { - @Override - public void updateGenerators() { + @Override public void updateGenerators() { if (!SetupUtils.generators.isEmpty()) { return; } @@ -37,7 +33,7 @@ public class BukkitSetupUtils extends SetupUtils { if (plugin.isEnabled()) { ChunkGenerator generator = plugin.getDefaultWorldGenerator(testWorld, ""); if (generator != null) { - PS.get().removePlotAreas(testWorld); + PlotSquared.get().removePlotAreas(testWorld); String name = plugin.getDescription().getName(); GeneratorWrapper wrapped; if (generator instanceof GeneratorWrapper) { @@ -54,8 +50,7 @@ public class BukkitSetupUtils extends SetupUtils { } } - @Override - public void unload(String worldName, boolean save) { + @Override public void unload(String worldName, boolean save) { World world = Bukkit.getWorld(worldName); if (world == null) { return; @@ -76,8 +71,7 @@ public class BukkitSetupUtils extends SetupUtils { Bukkit.unloadWorld(world, false); } - @Override - public String setupWorld(SetupObject object) { + @Override public String setupWorld(SetupObject object) { SetupUtils.manager.updateGenerators(); ConfigurationNode[] steps = object.step == null ? new ConfigurationNode[0] : object.step; String world = object.world; @@ -86,16 +80,18 @@ public class BukkitSetupUtils extends SetupUtils { switch (type) { case 2: { if (object.id != null) { - if (!PS.get().worlds.contains(worldPath)) { - PS.get().worlds.createSection(worldPath); + if (!PlotSquared.get().worlds.contains(worldPath)) { + PlotSquared.get().worlds.createSection(worldPath); } - ConfigurationSection worldSection = PS.get().worlds.getConfigurationSection(worldPath); + ConfigurationSection worldSection = + PlotSquared.get().worlds.getConfigurationSection(worldPath); String areaName = object.id + "-" + object.min + "-" + object.max; String areaPath = "areas." + areaName; if (!worldSection.contains(areaPath)) { worldSection.createSection(areaPath); } - ConfigurationSection areaSection = worldSection.getConfigurationSection(areaPath); + ConfigurationSection areaSection = + worldSection.getConfigurationSection(areaPath); HashMap options = new HashMap<>(); for (ConfigurationNode step : steps) { options.put(step.getConstant(), step.getValue()); @@ -103,7 +99,8 @@ public class BukkitSetupUtils extends SetupUtils { options.put("generator.type", object.type); options.put("generator.terrain", object.terrain); options.put("generator.plugin", object.plotManager); - if (object.setupGenerator != null && !object.setupGenerator.equals(object.plotManager)) { + if (object.setupGenerator != null && !object.setupGenerator + .equals(object.plotManager)) { options.put("generator.init", object.setupGenerator); } for (Entry entry : options.entrySet()) { @@ -126,18 +123,23 @@ public class BukkitSetupUtils extends SetupUtils { break; } case 1: { - if (!PS.get().worlds.contains(worldPath)) { - PS.get().worlds.createSection(worldPath); + if (!PlotSquared.get().worlds.contains(worldPath)) { + PlotSquared.get().worlds.createSection(worldPath); } - ConfigurationSection worldSection = PS.get().worlds.getConfigurationSection(worldPath); + ConfigurationSection worldSection = + PlotSquared.get().worlds.getConfigurationSection(worldPath); for (ConfigurationNode step : steps) { worldSection.set(step.getConstant(), step.getValue()); } - PS.get().worlds.set("worlds." + world + ".generator.type", object.type); - PS.get().worlds.set("worlds." + world + ".generator.terrain", object.terrain); - PS.get().worlds.set("worlds." + world + ".generator.plugin", object.plotManager); - if (object.setupGenerator != null && !object.setupGenerator.equals(object.plotManager)) { - PS.get().worlds.set("worlds." + world + ".generator.init", object.setupGenerator); + PlotSquared.get().worlds.set("worlds." + world + ".generator.type", object.type); + PlotSquared.get().worlds + .set("worlds." + world + ".generator.terrain", object.terrain); + PlotSquared.get().worlds + .set("worlds." + world + ".generator.plugin", object.plotManager); + if (object.setupGenerator != null && !object.setupGenerator + .equals(object.plotManager)) { + PlotSquared.get().worlds + .set("worlds." + world + ".generator.init", object.setupGenerator); } GeneratorWrapper gen = SetupUtils.generators.get(object.setupGenerator); if (gen != null && gen.isFull()) { @@ -147,10 +149,11 @@ public class BukkitSetupUtils extends SetupUtils { } case 0: { if (steps.length != 0) { - if (!PS.get().worlds.contains(worldPath)) { - PS.get().worlds.createSection(worldPath); + if (!PlotSquared.get().worlds.contains(worldPath)) { + PlotSquared.get().worlds.createSection(worldPath); } - ConfigurationSection worldSection = PS.get().worlds.getConfigurationSection(worldPath); + ConfigurationSection worldSection = + PlotSquared.get().worlds.getConfigurationSection(worldPath); for (ConfigurationNode step : steps) { worldSection.set(step.getConstant(), step.getValue()); } @@ -159,22 +162,24 @@ public class BukkitSetupUtils extends SetupUtils { } } try { - PS.get().worlds.save(PS.get().worldsFile); + PlotSquared.get().worlds.save(PlotSquared.get().worldsFile); } catch (IOException e) { e.printStackTrace(); } if (object.setupGenerator != null) { - if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit.getPluginManager().getPlugin("Multiverse-Core") - .isEnabled()) { - Bukkit.getServer() - .dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal -g " + object.setupGenerator); + if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit + .getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), + "mv create " + world + " normal -g " + object.setupGenerator); setGenerator(world, object.setupGenerator); if (Bukkit.getWorld(world) != null) { return world; } } - if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) { - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world + " plugin:" + object.setupGenerator); + if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit + .getPluginManager().getPlugin("MultiWorld").isEnabled()) { + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), + "mw create " + world + " plugin:" + object.setupGenerator); setGenerator(world, object.setupGenerator); if (Bukkit.getWorld(world) != null) { return world; @@ -187,20 +192,24 @@ public class BukkitSetupUtils extends SetupUtils { Bukkit.createWorld(wc); setGenerator(world, object.setupGenerator); } else { - if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit.getPluginManager().getPlugin("Multiverse-Core") - .isEnabled()) { - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal"); + if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit + .getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), + "mv create " + world + " normal"); if (Bukkit.getWorld(world) != null) { return world; } } - if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) { - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world); + if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit + .getPluginManager().getPlugin("MultiWorld").isEnabled()) { + Bukkit.getServer() + .dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world); if (Bukkit.getWorld(world) != null) { return world; } } - World bw = Bukkit.createWorld(new WorldCreator(object.world).environment(Environment.NORMAL)); + World bw = + Bukkit.createWorld(new WorldCreator(object.world).environment(Environment.NORMAL)); } return object.world; } @@ -219,8 +228,7 @@ public class BukkitSetupUtils extends SetupUtils { } } - @Override - public String getGenerator(PlotArea plotArea) { + @Override public String getGenerator(PlotArea plotArea) { if (SetupUtils.generators.isEmpty()) { updateGenerators(); } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitTaskManager.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitTaskManager.java new file mode 100644 index 000000000..56448ff34 --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitTaskManager.java @@ -0,0 +1,50 @@ +package com.github.intellectualsites.plotsquared.bukkit.util; + +import com.github.intellectualsites.plotsquared.bukkit.BukkitMain; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import org.bukkit.Bukkit; + +public class BukkitTaskManager extends TaskManager { + + private final BukkitMain bukkitMain; + + public BukkitTaskManager(BukkitMain bukkitMain) { + this.bukkitMain = bukkitMain; + } + + @Override public int taskRepeat(Runnable runnable, int interval) { + return this.bukkitMain.getServer().getScheduler() + .scheduleSyncRepeatingTask(this.bukkitMain, runnable, interval, interval); + } + + @SuppressWarnings("deprecation") @Override + public int taskRepeatAsync(Runnable runnable, int interval) { + return this.bukkitMain.getServer().getScheduler() + .scheduleAsyncRepeatingTask(this.bukkitMain, runnable, interval, interval); + } + + @Override public void taskAsync(Runnable runnable) { + this.bukkitMain.getServer().getScheduler().runTaskAsynchronously(this.bukkitMain, runnable) + .getTaskId(); + } + + @Override public void task(Runnable runnable) { + this.bukkitMain.getServer().getScheduler().runTask(this.bukkitMain, runnable).getTaskId(); + } + + @Override public void taskLater(Runnable runnable, int delay) { + this.bukkitMain.getServer().getScheduler().runTaskLater(this.bukkitMain, runnable, delay) + .getTaskId(); + } + + @Override public void taskLaterAsync(Runnable runnable, int delay) { + this.bukkitMain.getServer().getScheduler() + .runTaskLaterAsynchronously(this.bukkitMain, runnable, delay); + } + + @Override public void cancelTask(int task) { + if (task != -1) { + Bukkit.getScheduler().cancelTask(task); + } + } +} diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitUtil.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitUtil.java new file mode 100644 index 000000000..f3981c152 --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitUtil.java @@ -0,0 +1,471 @@ +package com.github.intellectualsites.plotsquared.bukkit.util; + +import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.schematic.PlotItem; +import com.github.intellectualsites.plotsquared.plot.util.*; +import com.sk89q.worldedit.bukkit.BukkitWorld; +import lombok.NonNull; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.World; +import org.bukkit.block.Biome; +import org.bukkit.block.Block; +import org.bukkit.block.BlockState; +import org.bukkit.block.Sign; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; +import org.bukkit.material.*; + +import javax.annotation.Nullable; +import java.util.*; + +@SuppressWarnings({"unused", "WeakerAccess"}) public class BukkitUtil extends WorldUtil { + + private static String lastString = null; + private static World lastWorld = null; + + private static Player lastPlayer = null; + private static PlotPlayer lastPlotPlayer = null; + + public static void removePlayer(String player) { + lastPlayer = null; + lastPlotPlayer = null; + } + + public static PlotPlayer getPlayer(@NonNull final OfflinePlayer op) { + if (op.isOnline()) { + return getPlayer(op.getPlayer()); + } + final Player player = OfflinePlayerUtil.loadPlayer(op); + player.loadData(); + return new BukkitPlayer(player, true); + } + + /** + * Get a plot based on the location. + * + * @param location the location to check + * @return plot if found, otherwise it creates a temporary plot + * @see Plot + */ + public static Plot getPlot(org.bukkit.Location location) { + if (location == null) { + return null; + } + return getLocation(location).getPlot(); + } + + /** + * Get a plot based on the player location. + * + * @param player the player to check + * @return plot if found, otherwise it creates a temporary plot + * @see #getPlot(org.bukkit.Location) + * @see Plot + */ + public static Plot getPlot(Player player) { + return getPlot(player.getLocation()); + } + + /** + * Get home location. + * + * @param plot Plot that you want to get the location for + * @return plot bottom location + * @see Plot + */ + public static org.bukkit.Location getHomeLocation(Plot plot) { + return BukkitUtil.getLocation(plot.getHome()); + } + + /** + * Get the PlotPlayer for an offline player. + * + *

Note that this will work if the player is offline, however not all + * functionality will work. + * + * @param player the player to wrap + * @return a {@code PlotPlayer} + * @see PlotPlayer#wrap(Object) + */ + public static PlotPlayer wrapPlayer(OfflinePlayer player) { + return PlotPlayer.wrap(player); + } + + /** + * Gets the PlotPlayer for a player. The PlotPlayer is usually cached and + * will provide useful functions relating to players. + * + * @param player the player to wrap + * @return a {@code PlotPlayer} + * @see PlotPlayer#wrap(Object) + */ + public static PlotPlayer wrapPlayer(Player player) { + return PlotPlayer.wrap(player); + } + + /** + * Gets the number of plots, which the player is able to build in. + * + * @param player player, for whom we're getting the plots + * @return the number of allowed plots + */ + public static int getAllowedPlots(Player player) { + PlotPlayer plotPlayer = PlotPlayer.wrap(player); + return plotPlayer.getAllowedPlots(); + } + + /** + * Check whether or not a player is in a plot. + * + * @param player who we're checking for + * @return true if the player is in a plot, false if not- + */ + public static boolean isInPlot(Player player) { + return getPlot(player) != null; + } + + /** + * Gets a collection containing the players plots. + * + * @param world Specify the world we want to select the plots from + * @param player Player, for whom we're getting the plots + * @return a set containing the players plots + * @see Plot + */ + public static Set getPlayerPlots(String world, Player player) { + if (world == null) { + return new HashSet<>(); + } + return PlotPlayer.wrap(player).getPlots(world); + } + + /** + * Send a message to a player. The message supports color codes. + * + * @param player the recipient of the message + * @param string the message + * @see MainUtil#sendMessage(PlotPlayer, String) + */ + public static void sendMessage(Player player, String string) { + MainUtil.sendMessage(BukkitUtil.getPlayer(player), string); + } + + /** + * Gets the player plot count. + * + * @param world Specify the world we want to select the plots from + * @param player Player, for whom we're getting the plot count + * @return the number of plots the player has + */ + public static int getPlayerPlotCount(String world, Player player) { + if (world == null) { + return 0; + } + return BukkitUtil.getPlayer(player).getPlotCount(world); + } + + /** + * Send a message to a player. + * + * @param player the recipient of the message + * @param caption the message + * @see MainUtil#sendMessage(PlotPlayer, C, String...) + */ + public static void sendMessage(Player player, C caption) { + MainUtil.sendMessage(BukkitUtil.getPlayer(player), caption); + } + + public static PlotPlayer getPlayer(@NonNull final Player player) { + if (player == lastPlayer) { + return lastPlotPlayer; + } + final String name = player.getName(); + final PlotPlayer plotPlayer = UUIDHandler.getPlayer(name); + if (plotPlayer != null) { + return plotPlayer; + } + lastPlotPlayer = new BukkitPlayer(player); + UUIDHandler.getPlayers().put(name, lastPlotPlayer); + lastPlayer = player; + return lastPlotPlayer; + } + + public static Location getLocation(@NonNull final org.bukkit.Location location) { + return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()), + MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ())); + } + + public static org.bukkit.Location getLocation(@NonNull final Location location) { + return new org.bukkit.Location(getWorld(location.getWorld()), location.getX(), + location.getY(), location.getZ()); + } + + public static World getWorld(@NonNull final String string) { + return Bukkit.getWorld(string); + } + + public static String getWorld(@NonNull final Entity entity) { + return entity.getWorld().getName(); + } + + public static List getEntities(@NonNull final String worldName) { + World world = getWorld(worldName); + return world != null ? world.getEntities() : new ArrayList(); + } + + public static Location getLocation(@NonNull final Entity entity) { + final org.bukkit.Location location = entity.getLocation(); + String world = location.getWorld().getName(); + return new Location(world, location.getBlockX(), location.getBlockY(), + location.getBlockZ()); + } + + public static Location getLocationFull(@NonNull final Entity entity) { + final org.bukkit.Location location = entity.getLocation(); + return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()), + MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()), location.getYaw(), + location.getPitch()); + } + + public static BukkitLegacyMappings getBukkitLegacyMappings() { + return (BukkitLegacyMappings) PlotSquared.imp().getLegacyMappings(); + } + + public static Material getMaterial(@NonNull final PlotBlock plotBlock) { + if (plotBlock instanceof StringPlotBlock) { + return Material + .getMaterial(((StringPlotBlock) plotBlock).getItemId().toUpperCase(Locale.ENGLISH)); + } else { + final LegacyPlotBlock legacyPlotBlock = (LegacyPlotBlock) plotBlock; + return getBukkitLegacyMappings() + .fromLegacyToString(legacyPlotBlock.getId(), legacyPlotBlock.getData()) + .to(Material.class); + } + } + + @Override public boolean isBlockSame(PlotBlock block1, PlotBlock block2) { + if (block1.equals(block2)) { + return true; + } + Material mat1 = getMaterial(block1), mat2 = getMaterial(block2); + return mat1 == mat2; + } + + @Override public boolean isWorld(@NonNull final String worldName) { + return getWorld(worldName) != null; + } + + @Override public String getBiome(String world, int x, int z) { + return getWorld(world).getBiome(x, z).name(); + } + + @Override @SuppressWarnings("deprecation") + public void setSign(@NonNull final String worldName, final int x, final int y, final int z, + @NonNull final String[] lines) { + final World world = getWorld(worldName); + final Block block = world.getBlockAt(x, y, z); + // block.setType(Material.AIR); + final Material type = block.getType(); + if (type != Material.SIGN && type != Material.WALL_SIGN) { + int data = 2; + if (world.getBlockAt(x, y, z + 1).getType().isSolid()) + data = 2; + else if (world.getBlockAt(x + 1, y, z).getType().isSolid()) + data = 4; + else if (world.getBlockAt(x, y, z - 1).getType().isSolid()) + data = 3; + else if (world.getBlockAt(x - 1, y, z).getType().isSolid()) + data = 5; + block.setType(Material.WALL_SIGN, false); + final Sign sign = (Sign) block.getBlockData(); + sign.setRawData((byte) data); + } + final BlockState blockstate = block.getState(); + if (blockstate instanceof Sign) { + final Sign sign = (Sign) blockstate; + for (int i = 0; i < lines.length; i++) { + sign.setLine(i, lines[i]); + } + sign.update(true); + } + } + + @Override @Nullable public String[] getSign(@NonNull final Location location) { + Block block = getWorld(location.getWorld()) + .getBlockAt(location.getX(), location.getY(), location.getZ()); + if (block != null) { + if (block.getState() instanceof Sign) { + Sign sign = (Sign) block.getState(); + return sign.getLines(); + } + } + return null; + } + + @Override public Location getSpawn(@NonNull final PlotPlayer player) { + return getLocation(((BukkitPlayer) player).player.getBedSpawnLocation()); + } + + @Override public Location getSpawn(@NonNull 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 void setSpawn(@NonNull final Location location) { + final World world = getWorld(location.getWorld()); + if (world != null) { + world.setSpawnLocation(location.getX(), location.getY(), location.getZ()); + } + } + + @Override public void saveWorld(@NonNull final String worldName) { + final World world = getWorld(worldName); + if (world != null) { + world.save(); + } + } + + @Override public int getHighestBlock(@NonNull final String world, final int x, final int z) { + final World bukkitWorld = getWorld(world); + // Skip top and bottom block + int air = 1; + for (int y = bukkitWorld.getMaxHeight() - 1; y >= 0; y--) { + Block block = bukkitWorld.getBlockAt(x, y, z); + if (block != null) { + Material type = block.getType(); + if (type.isSolid()) { + if (air > 1) + return y; + air = 0; + } else { + switch (type) { + case WATER: + case LAVA: + return y; + } + air++; + } + } + } + return bukkitWorld.getMaxHeight() - 1; + } + + @Override public int getBiomeFromString(@NonNull final String biomeString) { + try { + final Biome biome = Biome.valueOf(biomeString.toUpperCase()); + return Arrays.asList(Biome.values()).indexOf(biome); + } catch (IllegalArgumentException ignored) { + return -1; + } + } + + @Override public String[] getBiomeList() { + final Biome[] biomes = Biome.values(); + final String[] list = new String[biomes.length]; + for (int i = 0; i < biomes.length; i++) { + list[i] = biomes[i].name(); + } + return list; + } + + @Override + public boolean addItems(@NonNull final String worldName, @NonNull final PlotItem items) { + final World world = getWorld(worldName); + final Block block = world.getBlockAt(items.x, items.y, items.z); + if (block == null) { + return false; + } + final BlockState state = block.getState(); + if (state instanceof InventoryHolder) { + InventoryHolder holder = (InventoryHolder) state; + Inventory inv = holder.getInventory(); + for (int i = 0; i < items.types.length; i++) { + // ItemStack item = new ItemStack(LegacyMappings.fromLegacyId(items.id[i]).getMaterial(), items.amount[i], items.data[i]); + ItemStack item = new ItemStack(items.types[i].to(Material.class), items.amount[i]); + inv.addItem(item); + } + state.update(true); + return true; + } + return false; + } + + @Override public boolean isBlockSolid(@NonNull final PlotBlock block) { + try { + final Material material = getMaterial(block); + if (material.isBlock() && material.isSolid() && !material.hasGravity()) { + Class 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) { + case NOTE_BLOCK: + case SPAWNER: + return false; + default: + return true; + } + } + } + return false; + } catch (Exception ignored) { + return false; + } + } + + @Override public String getClosestMatchingName(@NonNull final PlotBlock block) { + try { + return getMaterial(block).name(); + } catch (Exception ignored) { + return null; + } + } + + @Override @Nullable + public StringComparison.ComparisonResult getClosestBlock(String name) { + final PlotBlock plotBlock = BukkitUtil.getBukkitLegacyMappings().fromAny(name); + if (plotBlock != null) { + return new StringComparison().new ComparisonResult(1, plotBlock); + } + return BukkitUtil.getBukkitLegacyMappings().getClosestsMatch(name); + } + + @Override + public void setBiomes(@NonNull final String worldName, @NonNull final RegionWrapper region, + @NonNull final String biomeString) { + final World world = getWorld(worldName); + final Biome biome = Biome.valueOf(biomeString.toUpperCase()); + for (int x = region.minX; x <= region.maxX; x++) { + for (int z = region.minZ; z <= region.maxZ; z++) { + world.setBiome(x, z, biome); + } + } + } + + public com.sk89q.worldedit.world.World getWeWorld(String world) { + return new BukkitWorld(Bukkit.getWorld(world)); + } + + @Override public PlotBlock getBlock(@NonNull final Location location) { + final World world = getWorld(location.getWorld()); + final Block block = world.getBlockAt(location.getX(), location.getY(), location.getZ()); + if (block == null) { + return StringPlotBlock.EVERYTHING; + } + return PlotBlock.get(block.getType().name()); + } + + @Override public String getMainWorld() { + return Bukkit.getWorlds().get(0).getName(); + } +} diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitVersion.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitVersion.java new file mode 100644 index 000000000..8bfa3da59 --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitVersion.java @@ -0,0 +1,7 @@ +package com.github.intellectualsites.plotsquared.bukkit.util; + +public class BukkitVersion { + public static int[] v1_13_2 = {1, 13, 2}; + public static int[] v1_13_1 = {1, 13, 1}; + public static int[] v1_13_0 = {1, 13, 0}; +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/Metrics.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/Metrics.java similarity index 82% rename from Bukkit/src/main/java/com/plotsquared/bukkit/util/Metrics.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/Metrics.java index d1b30c50c..1dea71d41 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/Metrics.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/Metrics.java @@ -1,4 +1,4 @@ -package com.plotsquared.bukkit.util; +package com.github.intellectualsites.plotsquared.bukkit.util; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -6,12 +6,7 @@ import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.scheduler.BukkitTask; -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; +import java.io.*; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.net.URLConnection; @@ -22,19 +17,33 @@ import java.util.zip.GZIPOutputStream; public class Metrics { - /** The current revision number. */ + /** + * The current revision number. + */ private static final int REVISION = 7; - /** The base url of the metrics domain.*/ + /** + * The base url of the metrics domain. + */ private static final String BASE_URL = "http://report.mcstats.org"; - /** The url used to report a server's status. */ + /** + * The url used to report a server's status. + */ private static final String REPORT_URL = "/plugin/%s"; - /** Interval of time to ping (in minutes). */ + /** + * Interval of time to ping (in minutes). + */ private static final int PING_INTERVAL = 15; - /** The plugin this metrics submits for. */ + /** + * The plugin this metrics submits for. + */ private final Plugin plugin; - /** Unique server id. */ + /** + * Unique server id. + */ private final String guid; - /** The scheduled task. */ + /** + * The scheduled task. + */ private volatile BukkitTask task = null; public Metrics(Plugin plugin) { @@ -46,7 +55,6 @@ public class Metrics { * GZip compress a string of bytes. * * @param input - * * @return byte[] the file as a byte array */ public static byte[] gzip(String input) { @@ -61,7 +69,8 @@ public class Metrics { if (gzos != null) { try { gzos.close(); - } catch (IOException ignore) {} + } catch (IOException ignore) { + } } } return baos.toByteArray(); @@ -73,7 +82,6 @@ public class Metrics { * @param json * @param key * @param value - * */ private static void appendJSONPair(StringBuilder json, String key, String value) { boolean isValueNumeric = false; @@ -101,7 +109,6 @@ public class Metrics { * Escape a string to create a valid JSON string * * @param text - * * @return String */ private static String escapeJSON(String text) { @@ -145,7 +152,6 @@ public class Metrics { * Encode text as UTF-8 * * @param text the text to encode - * * @return the encoded text, as UTF-8 */ private static String urlEncode(String text) throws UnsupportedEncodingException { @@ -165,22 +171,22 @@ public class Metrics { return true; } // Begin hitting the server with glorious data - this.task = this.plugin.getServer().getScheduler().runTaskTimerAsynchronously(this.plugin, new Runnable() { - private boolean firstPost = true; + this.task = this.plugin.getServer().getScheduler() + .runTaskTimerAsynchronously(this.plugin, new Runnable() { + private boolean firstPost = true; - @Override - public void run() { - try { - postPlugin(!this.firstPost); - // After the first post we set firstPost to - // false - // Each post thereafter will be a ping - this.firstPost = false; - } catch (IOException e) { - e.printStackTrace(); + @Override public void run() { + try { + postPlugin(!this.firstPost); + // After the first post we set firstPost to + // false + // Each post thereafter will be a ping + this.firstPost = false; + } catch (IOException e) { + e.printStackTrace(); + } } - } - }, 0, PING_INTERVAL * 1200); + }, 0, PING_INTERVAL * 1200); return true; } @@ -196,10 +202,15 @@ public class Metrics { String serverVersion = Bukkit.getVersion(); int playersOnline = 0; try { - if (Bukkit.class.getMethod("getOnlinePlayers", new Class[0]).getReturnType() == Collection.class) { - playersOnline = ((Collection) Bukkit.class.getMethod("getOnlinePlayers", new Class[0]).invoke(null)).size(); + if (Bukkit.class.getMethod("getOnlinePlayers", new Class[0]).getReturnType() + == Collection.class) { + playersOnline = + ((Collection) Bukkit.class.getMethod("getOnlinePlayers", new Class[0]) + .invoke(null)).size(); } else { - playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class[0]).invoke(null)).length; + playersOnline = + ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class[0]) + .invoke(null)).length; } } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { ex.printStackTrace(); @@ -256,7 +267,8 @@ public class Metrics { os.flush(); } String response; - try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(connection.getInputStream()))) { response = reader.readLine(); } if (response == null || response.startsWith("ERR") || response.startsWith("7")) { @@ -267,6 +279,7 @@ public class Metrics { } throw new IOException(response); } - } catch (IOException ignored) {} + } catch (IOException ignored) { + } } -} \ No newline at end of file +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/NbtFactory.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/NbtFactory.java similarity index 83% rename from Bukkit/src/main/java/com/plotsquared/bukkit/util/NbtFactory.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/NbtFactory.java index 69690cc8c..ffc69edfc 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/NbtFactory.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/NbtFactory.java @@ -1,4 +1,4 @@ -package com.plotsquared.bukkit.util; +package com.github.intellectualsites.plotsquared.bukkit.util; import com.google.common.base.Splitter; import com.google.common.collect.BiMap; @@ -8,36 +8,18 @@ import com.google.common.collect.MapMaker; import com.google.common.io.ByteSink; import com.google.common.io.Closeables; import com.google.common.primitives.Primitives; -import java.io.BufferedInputStream; -import java.io.DataInput; -import java.io.DataInputStream; -import java.io.DataOutput; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.AbstractList; -import java.util.AbstractMap; -import java.util.AbstractSet; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.inventory.ItemStack; +import java.io.*; +import java.lang.reflect.*; +import java.util.*; +import java.util.concurrent.ConcurrentMap; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + public class NbtFactory { // Convert between NBT type and the equivalent class in java @@ -73,14 +55,16 @@ public class NbtFactory { ClassLoader loader = NbtFactory.class.getClassLoader(); String packageName = getPackageName(); - String craftpackageName = getCraftPackageName(); + String craftpackageName = getCraftPackageName(); Class offlinePlayer = loader.loadClass(packageName + ".CraftOfflinePlayer"); // Prepare NBT - this.COMPOUND_CLASS = getMethod(0, Modifier.STATIC, offlinePlayer, "getData").getReturnType(); + this.COMPOUND_CLASS = + getMethod(0, Modifier.STATIC, offlinePlayer, "getData").getReturnType(); this.BASE_CLASS = loader.loadClass(craftpackageName + ".NBTBase"); this.NBT_GET_TYPE = getMethod(0, Modifier.STATIC, this.BASE_CLASS, "getTypeId"); - this.NBT_CREATE_TAG = getMethod(Modifier.STATIC, 0, this.BASE_CLASS, "createTag", byte.class); + this.NBT_CREATE_TAG = + getMethod(Modifier.STATIC, 0, this.BASE_CLASS, "createTag", byte.class); // Prepare CraftItemStack this.CRAFT_STACK = loader.loadClass(packageName + ".inventory.CraftItemStack"); @@ -92,11 +76,14 @@ public class NbtFactory { initializeNMS(loader, nmsPackage); if (this.READ_LIMITER_CLASS != null) { - this.LOAD_COMPOUND = new LoadMethodSkinUpdate(this.STREAM_TOOLS, this.READ_LIMITER_CLASS); + this.LOAD_COMPOUND = + new LoadMethodSkinUpdate(this.STREAM_TOOLS, this.READ_LIMITER_CLASS); } else { this.LOAD_COMPOUND = new LoadMethodWorldUpdate(this.STREAM_TOOLS); } - this.SAVE_COMPOUND = getMethod(Modifier.STATIC, 0, this.STREAM_TOOLS, null, this.BASE_CLASS, DataOutput.class); + this.SAVE_COMPOUND = + getMethod(Modifier.STATIC, 0, this.STREAM_TOOLS, null, this.BASE_CLASS, + DataOutput.class); } catch (ClassNotFoundException e) { throw new IllegalStateException("Unable to find offline player.", e); @@ -106,6 +93,7 @@ public class NbtFactory { /** * Retrieve or construct a shared NBT factory. + * * @return The factory. */ private static NbtFactory get() { @@ -117,6 +105,7 @@ public class NbtFactory { /** * Construct a new NBT list of an unspecified type. + * * @return The NBT list. */ public static NbtList createList(Object... content) { @@ -125,6 +114,7 @@ public class NbtFactory { /** * Construct a new NBT list of an unspecified type. + * * @return The NBT list. */ public static NbtList createList(Iterable iterable) { @@ -148,6 +138,7 @@ public class NbtFactory { /** * Construct a new NBT wrapper from a list. + * * @param nmsList - the NBT list. * @return The wrapper. */ @@ -158,12 +149,13 @@ public class NbtFactory { /** * Load the content of a file from a stream. * - * @param input - the stream. + * @param input - the stream. * @param option - whether or not to decompress the input stream. * @return The decoded NBT compound. * @throws IOException If anything went wrong. */ - public static NbtCompound fromStream(InputStream input, StreamOptions option) throws IOException { + public static NbtCompound fromStream(InputStream input, StreamOptions option) + throws IOException { DataInputStream data = null; boolean suppress = true; @@ -195,14 +187,16 @@ public class NbtFactory { * @param option - whether or not to compress the output. * @throws IOException If anything went wrong. */ - public static void saveStream(NbtCompound source, ByteSink stream, StreamOptions option) throws IOException { + public static void saveStream(NbtCompound source, ByteSink stream, StreamOptions option) + throws IOException { OutputStream output = null; DataOutputStream data = null; boolean suppress = true; try { output = stream.openStream(); - data = new DataOutputStream(option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output); + data = new DataOutputStream( + option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output); invokeMethod(get().SAVE_COMPOUND, null, source.getHandle(), data); suppress = false; @@ -218,6 +212,7 @@ public class NbtFactory { /** * Construct a new NBT wrapper from a compound. + * * @param nmsCompound - the NBT compound. * @return The wrapper. */ @@ -228,7 +223,8 @@ public class NbtFactory { /** * Set the NBT compound tag of a given item stack. *

- * @param stack - the item stack, cannot be air. + * + * @param stack - the item stack, cannot be air. * @param compound - the new NBT compound, or NULL to remove it. * @throws IllegalArgumentException If the stack is not a CraftItemStack, or it represents air. */ @@ -246,6 +242,7 @@ public class NbtFactory { * material, damage value or count. *

* The item stack must be a wrapper for a CraftItemStack. + * * @param stack - the item stack. * @return A wrapper for its NBT tag. */ @@ -265,6 +262,7 @@ public class NbtFactory { /** * Retrieve a CraftItemStack version of the stack. + * * @param stack - the stack to convert. * @return The CraftItemStack version. */ @@ -279,12 +277,14 @@ public class NbtFactory { caller.setAccessible(true); return (ItemStack) caller.newInstance(stack); } catch (Exception ignored) { - throw new IllegalStateException("Unable to convert " + stack + " + to a CraftItemStack."); + throw new IllegalStateException( + "Unable to convert " + stack + " + to a CraftItemStack."); } } /** * Ensure that the given stack can store arbitrary NBT information. + * * @param stack - the stack to check. */ private static void checkItemStack(ItemStack stack) { @@ -295,12 +295,14 @@ public class NbtFactory { throw new IllegalArgumentException("Stack must be a CraftItemStack."); } if (stack.getType() == Material.AIR) { - throw new IllegalArgumentException("ItemStacks representing air cannot store NMS information."); + throw new IllegalArgumentException( + "ItemStacks representing air cannot store NMS information."); } } /** * Invoke a method on the given target instance using the provided parameters. + * * @param method - the method to invoke. * @param target - the target. * @param params - the parameters to supply. @@ -332,22 +334,23 @@ public class NbtFactory { /** * Search for the first publicly and privately defined method of the given name and parameter count. + * * @param requireMod - modifiers that are required. - * @param bannedMod - modifiers that are banned. - * @param clazz - a class to start with. + * @param bannedMod - modifiers that are banned. + * @param clazz - a class to start with. * @param methodName - the method name, or NULL to skip. - * @param params - the expected parameters. + * @param params - the expected parameters. * @return The first method by this name. * @throws IllegalStateException If we cannot find this method. */ - private static Method getMethod(int requireMod, int bannedMod, Class clazz, String methodName, - Class... params) { + private static Method getMethod(int requireMod, int bannedMod, Class clazz, + String methodName, Class... params) { for (Method method : clazz.getDeclaredMethods()) { // Limitation: Doesn't handle overloads - if (((method.getModifiers() & requireMod) == requireMod) - && ((method.getModifiers() & bannedMod) == 0) - && ((methodName == null) || method.getName().equals(methodName)) - && Arrays.equals(method.getParameterTypes(), params)) { + if (((method.getModifiers() & requireMod) == requireMod) && ( + (method.getModifiers() & bannedMod) == 0) && ((methodName == null) || method + .getName().equals(methodName)) && Arrays + .equals(method.getParameterTypes(), params)) { method.setAccessible(true); return method; @@ -357,13 +360,15 @@ public class NbtFactory { if (clazz.getSuperclass() != null) { return getMethod(requireMod, bannedMod, clazz.getSuperclass(), methodName, params); } - throw new IllegalStateException(String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params))); + throw new IllegalStateException( + String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params))); } /** * Search for the first publicly and privately defined field of the given name. - * @param instance - an instance of the class with the field. - * @param clazz - an optional class to start with, or NULL to deduce it from instance. + * + * @param instance - an instance of the class with the field. + * @param clazz - an optional class to start with, or NULL to deduce it from instance. * @param fieldName - the field name. * @return The first field by this name. * @throws IllegalStateException If we cannot find this field. @@ -390,7 +395,8 @@ public class NbtFactory { try { this.STREAM_TOOLS = loader.loadClass(nmsPackage + ".NBTCompressedStreamTools"); this.READ_LIMITER_CLASS = loader.loadClass(nmsPackage + ".NBTReadLimiter"); - } catch (ClassNotFoundException ignored) {} + } catch (ClassNotFoundException ignored) { + } } private String getPackageName() { @@ -404,24 +410,25 @@ public class NbtFactory { return "org.bukkit.craftbukkit.v1_13_R1"; } } - - private String getCraftPackageName() { - String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; - return "net.minecraft.server." + version; + + private String getCraftPackageName() { + String version = + Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; + return "net.minecraft.server." + version; } - @SuppressWarnings("unchecked") - private Map getDataMap(Object handle) { - return (Map) getFieldValue(getDataField(NbtType.TAG_COMPOUND, handle), handle); + @SuppressWarnings("unchecked") private Map getDataMap(Object handle) { + return (Map) getFieldValue(getDataField(NbtType.TAG_COMPOUND, handle), + handle); } - @SuppressWarnings("unchecked") - private List getDataList(Object handle) { + @SuppressWarnings("unchecked") private List getDataList(Object handle) { return (List) getFieldValue(getDataField(NbtType.TAG_LIST, handle), handle); } /** * Convert wrapped List and Map objects into their respective NBT counterparts. + * * @param value - the value of the element to create. Can be a List or a Map. * @return The NBT element. */ @@ -444,6 +451,7 @@ public class NbtFactory { /** * Convert a given NBT element to a primitive wrapper or List/Map equivalent. *

All changes to any mutable objects will be reflected in the underlying NBT element(s). + * * @param nms - the NBT element. * @return The wrapper equivalent. */ @@ -470,7 +478,8 @@ public class NbtFactory { /** * Construct a new NMS NBT tag initialized with the given value. - * @param type - the NBT type. + * + * @param type - the NBT type. * @param value - the value, or NULL to keep the original value. * @return The created tag. */ @@ -485,8 +494,9 @@ public class NbtFactory { /** * Retrieve the field where the NBT class stores its value. + * * @param type - the NBT type. - * @param nms - the NBT class instance. + * @param nms - the NBT class instance. * @return The corresponding field. */ private Field getDataField(NbtType type, Object nms) { @@ -498,6 +508,7 @@ public class NbtFactory { /** * Retrieve the NBT type from a given NMS NBT tag. + * * @param nms - the native NBT tag. * @return The corresponding type. */ @@ -508,40 +519,38 @@ public class NbtFactory { /** * Retrieve the nearest NBT type for a given primitive type. + * * @param primitive - the primitive type. * @return The corresponding type. */ private NbtType getPrimitiveType(Object primitive) { - NbtType type = NBT_ENUM.get(NBT_CLASS.inverse().get(Primitives.unwrap(primitive.getClass()))); + NbtType type = + NBT_ENUM.get(NBT_CLASS.inverse().get(Primitives.unwrap(primitive.getClass()))); // Display the illegal value at least if (type == null) { - throw new IllegalArgumentException(String.format("Illegal type: %s (%s)", primitive.getClass(), primitive)); + throw new IllegalArgumentException( + String.format("Illegal type: %s (%s)", primitive.getClass(), primitive)); } return type; } /** * Whether or not to enable stream compression. + * * @author Kristian */ public enum StreamOptions { NO_COMPRESSION, GZIP_COMPRESSION, } + private enum NbtType { - TAG_END(0, Void.class), - TAG_BYTE(1, byte.class), - TAG_SHORT(2, short.class), - TAG_INT(3, int.class), - TAG_LONG(4, long.class), - TAG_FLOAT(5, float.class), - TAG_DOUBLE(6, double.class), - TAG_BYTE_ARRAY(7, byte[].class), - TAG_INT_ARRAY(11, int[].class), - TAG_STRING(8, String.class), - TAG_LIST(9, List.class), - TAG_COMPOUND(10, Map.class); + TAG_END(0, Void.class), TAG_BYTE(1, byte.class), TAG_SHORT(2, short.class), TAG_INT(3, + int.class), TAG_LONG(4, long.class), TAG_FLOAT(5, float.class), TAG_DOUBLE(6, + double.class), TAG_BYTE_ARRAY(7, byte[].class), TAG_INT_ARRAY(11, + int[].class), TAG_STRING(8, String.class), TAG_LIST(9, List.class), TAG_COMPOUND(10, + Map.class); // Unique NBT type public final int id; @@ -563,21 +572,26 @@ public class NbtFactory { } } + /** * Represents an object that provides a view of a native NMS class. + * * @author Kristian */ public interface Wrapper { /** * Retrieve the underlying native NBT tag. + * * @return The underlying NBT. */ Object getHandle(); } + /** * Represents a method for loading an NBT compound. + * * @author Kristian */ private static abstract class LoadCompoundMethod { @@ -591,12 +605,14 @@ public class NbtFactory { /** * Load an NBT compound from a given stream. + * * @param input - the input stream. * @return The loaded NBT compound. */ public abstract Object loadNbt(DataInput input); } + /** * Load an NBT compound from the NBTCompressedStreamTools static method in 1.7.2 - 1.7.5 */ @@ -606,12 +622,12 @@ public class NbtFactory { setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class)); } - @Override - public Object loadNbt(DataInput input) { + @Override public Object loadNbt(DataInput input) { return invokeMethod(this.staticMethod, null, input); } } + /** * Load an NBT compound from the NBTCompressedStreamTools static method in 1.7.8 */ @@ -620,7 +636,8 @@ public class NbtFactory { private Object readLimiter; LoadMethodSkinUpdate(Class streamClass, Class readLimiterClass) { - setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class, readLimiterClass)); + setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class, + readLimiterClass)); // Find the unlimited read limiter for (Field field : readLimiterClass.getDeclaredFields()) { @@ -634,27 +651,28 @@ public class NbtFactory { } } - @Override - public Object loadNbt(DataInput input) { + @Override public Object loadNbt(DataInput input) { return invokeMethod(this.staticMethod, null, input, this.readLimiter); } } + /** * Represents a root NBT compound. *

All changes to this map will be reflected in the underlying NBT compound. Values may only be one of the following: *

    - *
  • Primitive types
  • - *
  • {@link String String}
  • - *
  • {@link NbtList}
  • - *
  • {@link NbtCompound}
  • + *
  • Primitive types
  • + *
  • {@link String String}
  • + *
  • {@link NbtList}
  • + *
  • {@link NbtCompound}
  • *
*

* See also: *

    - *
  • {@link NbtFactory#createCompound()}
  • - *
  • {@link NbtFactory#fromCompound(Object)}
  • + *
  • {@link NbtFactory#createCompound()}
  • + *
  • {@link NbtFactory#fromCompound(Object)}
  • *
+ * * @author Kristian */ public final class NbtCompound extends ConvertedMap { @@ -702,7 +720,8 @@ public class NbtFactory { /** * Retrieve the list by the given name. - * @param key - the name of the list. + * + * @param key - the name of the list. * @param createNew - whether or not to create a new list if its missing. * @return An existing list, a new list or NULL. */ @@ -717,7 +736,8 @@ public class NbtFactory { /** * Retrieve the map by the given name. - * @param key - the name of the map. + * + * @param key - the name of the map. * @param createNew - whether or not to create a new map if its missing. * @return An existing map, a new map or NULL. */ @@ -732,7 +752,8 @@ public class NbtFactory { *

* Every element of the path (except the end) are assumed to be compounds, and will * be created if they are missing. - * @param path - the path to the entry. + * + * @param path - the path to the entry. * @param value - the new value of this entry. * @return This compound, for chaining. */ @@ -749,11 +770,11 @@ public class NbtFactory { *

* Every element of the path (except the end) are assumed to be compounds. The * retrieval operation will be cancelled if any of them are missing. + * * @param path - path to the entry. * @return The value, or NULL if not found. */ - @SuppressWarnings("unchecked") - public T getPath(String path) { + @SuppressWarnings("unchecked") public T getPath(String path) { List entries = getPathElements(path); NbtCompound map = getMap(entries.subList(0, entries.size() - 1), false); @@ -765,6 +786,7 @@ public class NbtFactory { /** * Save the content of a NBT compound to a stream. + * * @param stream - the output stream. * @param option - whether or not to compress the output. * @throws IOException If anything went wrong. @@ -775,7 +797,8 @@ public class NbtFactory { /** * Retrieve a map from a given path. - * @param path - path of compounds to look up. + * + * @param path - path of compounds to look up. * @param createNew - whether or not to create new compounds on the way. * @return The map at this location. */ @@ -798,6 +821,7 @@ public class NbtFactory { /** * Split the path into separate elements. + * * @param path - the path to split. * @return The elements. */ @@ -806,13 +830,15 @@ public class NbtFactory { } } + /** * Represents a root NBT list. * See also: *

    - *
  • {@link NbtFactory#createList(Iterable)}}
  • - *
  • {@link NbtFactory#fromList(Object)}
  • + *
  • {@link NbtFactory#createList(Iterable)}}
  • + *
  • {@link NbtFactory#fromList(Object)}
  • *
+ * * @author Kristian */ public final class NbtList extends ConvertedList { @@ -822,8 +848,10 @@ public class NbtFactory { } } + /** * Represents a class for caching wrappers. + * * @author Kristian */ private final class CachedNativeWrapper { @@ -846,9 +874,11 @@ public class NbtFactory { } } + /** * Represents a map that wraps another map and automatically * converts entries of its type and another exposed type. + * * @author Kristian */ private class ConvertedMap extends AbstractMap implements Wrapper { @@ -873,32 +903,26 @@ public class NbtFactory { } // Modification - @Override - public Object put(String key, Object value) { + @Override public Object put(String key, Object value) { return wrapOutgoing(this.original.put(key, unwrapIncoming(value))); } // Performance - @Override - public Object get(Object key) { + @Override public Object get(Object key) { return wrapOutgoing(this.original.get(key)); } - @Override - public Object remove(Object key) { + @Override public Object remove(Object key) { return wrapOutgoing(this.original.remove(key)); } - @Override - public boolean containsKey(Object key) { + @Override public boolean containsKey(Object key) { return this.original.containsKey(key); } - @Override - public Set> entrySet() { + @Override public Set> entrySet() { return new AbstractSet>() { - @Override - public boolean add(Entry e) { + @Override public boolean add(Entry e) { String key = e.getKey(); Object value = e.getValue(); @@ -906,13 +930,11 @@ public class NbtFactory { return true; } - @Override - public int size() { + @Override public int size() { return ConvertedMap.this.original.size(); } - @Override - public Iterator> iterator() { + @Override public Iterator> iterator() { return ConvertedMap.this.iterator(); } }; @@ -922,34 +944,33 @@ public class NbtFactory { final Iterator> proxy = this.original.entrySet().iterator(); return new Iterator>() { - @Override - public boolean hasNext() { + @Override public boolean hasNext() { return proxy.hasNext(); } - @Override - public Entry next() { + @Override public Entry next() { Entry entry = proxy.next(); - return new SimpleEntry(entry.getKey(), wrapOutgoing(entry.getValue())); + return new SimpleEntry(entry.getKey(), + wrapOutgoing(entry.getValue())); } - @Override - public void remove() { + @Override public void remove() { proxy.remove(); } }; } - @Override - public Object getHandle() { + @Override public Object getHandle() { return this.handle; } } + /** * Represents a list that wraps another list and converts elements * of its type and another exposed type. + * * @author Kristian */ private class ConvertedList extends AbstractList implements Wrapper { @@ -975,44 +996,38 @@ public class NbtFactory { return unwrapValue(wrapped); } - @Override - public Object get(int index) { + @Override public Object get(int index) { return wrapOutgoing(this.original.get(index)); } - @Override - public int size() { + @Override public int size() { return this.original.size(); } - @Override - public Object set(int index, Object element) { + @Override public Object set(int index, Object element) { return wrapOutgoing(this.original.set(index, unwrapIncoming(element))); } - @Override - public void add(int index, Object element) { + @Override public void add(int index, Object element) { Object nbt = unwrapIncoming(element); // Set the list type if its the first element if (size() == 0) { - setFieldValue(NbtFactory.this.NBT_LIST_TYPE, this.handle, (byte) getNbtType(nbt).id); + setFieldValue(NbtFactory.this.NBT_LIST_TYPE, this.handle, + (byte) getNbtType(nbt).id); } this.original.add(index, nbt); } - @Override - public Object remove(int index) { + @Override public Object remove(int index) { return wrapOutgoing(this.original.remove(index)); } - @Override - public boolean remove(Object o) { + @Override public boolean remove(Object o) { return this.original.remove(unwrapIncoming(o)); } - @Override - public Object getHandle() { + @Override public Object getHandle() { return this.handle; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/OfflinePlayerUtil.java similarity index 73% rename from Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/OfflinePlayerUtil.java index ae235b3b0..f1bc97bb1 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/OfflinePlayerUtil.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/OfflinePlayerUtil.java @@ -1,12 +1,4 @@ -package com.plotsquared.bukkit.util; - -import static com.intellectualcrafters.plot.util.ReflectionUtils.callConstructor; -import static com.intellectualcrafters.plot.util.ReflectionUtils.callMethod; -import static com.intellectualcrafters.plot.util.ReflectionUtils.getCbClass; -import static com.intellectualcrafters.plot.util.ReflectionUtils.getNmsClass; -import static com.intellectualcrafters.plot.util.ReflectionUtils.getUtilClass; -import static com.intellectualcrafters.plot.util.ReflectionUtils.makeConstructor; -import static com.intellectualcrafters.plot.util.ReflectionUtils.makeMethod; +package com.github.intellectualsites.plotsquared.bukkit.util; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; @@ -17,6 +9,8 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.UUID; +import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.*; + public class OfflinePlayerUtil { public static Player loadPlayer(String name) { @@ -43,10 +37,12 @@ public class OfflinePlayerUtil { Object worldServer = getWorldServer(); Object profile = newGameProfile(id, name); Class entityPlayerClass = getNmsClass("EntityPlayer"); - Constructor entityPlayerConstructor = makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"), getNmsClass("WorldServer"), - getUtilClass("com.mojang.authlib.GameProfile"), + Constructor entityPlayerConstructor = + makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"), + getNmsClass("WorldServer"), getUtilClass("com.mojang.authlib.GameProfile"), getNmsClass("PlayerInteractManager")); - Object entityPlayer = callConstructor(entityPlayerConstructor, server, worldServer, profile, interactManager); + Object entityPlayer = + callConstructor(entityPlayerConstructor, server, worldServer, profile, interactManager); return (Player) getBukkitEntity(entityPlayer); } @@ -55,7 +51,8 @@ public class OfflinePlayerUtil { if (gameProfileClass == null) { //Before uuids return name; } - Constructor gameProfileConstructor = makeConstructor(gameProfileClass, UUID.class, String.class); + Constructor gameProfileConstructor = + makeConstructor(gameProfileClass, UUID.class, String.class); if (gameProfileConstructor == null) { //Version has string constructor gameProfileConstructor = makeConstructor(gameProfileClass, String.class, String.class); return callConstructor(gameProfileConstructor, id.toString(), name); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/SendChunk.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SendChunk.java similarity index 63% rename from Bukkit/src/main/java/com/plotsquared/bukkit/util/SendChunk.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SendChunk.java index 2a68579ce..f0987b219 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/SendChunk.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SendChunk.java @@ -1,19 +1,17 @@ -package com.plotsquared.bukkit.util; +package com.github.intellectualsites.plotsquared.bukkit.util; -import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; - -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.object.ChunkLoc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass; -import com.intellectualcrafters.plot.util.ReflectionUtils.RefConstructor; -import com.intellectualcrafters.plot.util.ReflectionUtils.RefField; -import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.plotsquared.bukkit.object.BukkitPlayer; +import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.object.ChunkLoc; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefClass; +import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefConstructor; +import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefField; +import com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.RefMethod; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.World; @@ -25,6 +23,8 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; +import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass; + /** * An utility that can be used to send chunks, rather than using bukkit code * to do so (uses heavy NMS). @@ -50,16 +50,7 @@ public class SendChunk { RefClass classChunk = getRefClass("{nms}.Chunk"); this.methodInitLighting = classChunk.getMethod("initLighting"); RefClass classMapChunk = getRefClass("{nms}.PacketPlayOutMapChunk"); - if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_9_4)) { - //this works for 1.9.4 and 1.10 - tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(),int.class); - } else { - try { - tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), boolean.class, int.class); - } catch (NoSuchMethodException ignored) { - tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(),boolean.class, int.class, int.class); - } - } + tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), int.class); this.mapChunk = tempMapChunk; RefClass classEntityPlayer = getRefClass("{nms}.EntityPlayer"); this.connection = classEntityPlayer.getField("playerConnection"); @@ -116,39 +107,30 @@ public class SendChunk { chunks.remove(chunk); Object con = this.connection.of(entity).get(); Object packet = null; - if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_9_4)) { - try { - packet = this.mapChunk.create(c,65535); - } catch (Exception ignored) {} - } else { - try { - packet = this.mapChunk.create(c, true, 65535); - } catch (ReflectiveOperationException | IllegalArgumentException e) { - try { - packet = this.mapChunk.create(c, true, 65535, 5); - } catch (ReflectiveOperationException | IllegalArgumentException e1) { - e1.printStackTrace(); - } - } + try { + packet = this.mapChunk.create(c, 65535); + } catch (Exception ignored) { } if (packet == null) { - PS.debug("Error with PacketPlayOutMapChunk reflection."); + PlotSquared.debug("Error with PacketPlayOutMapChunk reflection."); } this.send.of(con).call(packet); } } for (final Chunk chunk : chunks) { TaskManager.runTask(new Runnable() { - @Override - public void run() { + @Override public void run() { try { chunk.unload(true, false); } catch (Throwable ignored) { String worldName = chunk.getWorld().getName(); - PS.debug("$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";" + chunk.getZ()); - PS.debug("$3 - $4File may be open in another process (e.g. MCEdit)"); - PS.debug("$3 - $4" + worldName + "/level.dat or " + worldName - + "/level_old.dat may be corrupt (try repairing or removing these)"); + PlotSquared.debug( + "$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";" + + chunk.getZ()); + PlotSquared + .debug("$3 - $4File may be open in another process (e.g. MCEdit)"); + PlotSquared.debug("$3 - $4" + worldName + "/level.dat or " + worldName + + "/level_old.dat may be corrupt (try repairing or removing these)"); } } }); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/SetGenCB.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SetGenCB.java similarity index 76% rename from Bukkit/src/main/java/com/plotsquared/bukkit/util/SetGenCB.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SetGenCB.java index f8c4ece83..110635f2d 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/SetGenCB.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SetGenCB.java @@ -1,9 +1,9 @@ -package com.plotsquared.bukkit.util; +package com.github.intellectualsites.plotsquared.bukkit.util; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.generator.GeneratorWrapper; -import com.intellectualcrafters.plot.util.SetupUtils; -import com.plotsquared.bukkit.generator.BukkitAugmentedGenerator; +import com.github.intellectualsites.plotsquared.bukkit.generator.BukkitAugmentedGenerator; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; +import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; import org.bukkit.World; import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.ChunkGenerator; @@ -16,7 +16,7 @@ public class SetGenCB { public static void setGenerator(World world) throws Exception { SetupUtils.manager.updateGenerators(); - PS.get().removePlotAreas(world.getName()); + PlotSquared.get().removePlotAreas(world.getName()); ChunkGenerator gen = world.getGenerator(); if (gen == null) { return; @@ -52,6 +52,7 @@ public class SetGenCB { } } } - PS.get().loadWorld(world.getName(), PS.get().IMP.getGenerator(world.getName(), null)); + PlotSquared.get() + .loadWorld(world.getName(), PlotSquared.get().IMP.getGenerator(world.getName(), null)); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/BukkitLocalQueue.java similarity index 55% rename from Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/BukkitLocalQueue.java index 0e0b296da..30f853573 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/BukkitLocalQueue.java @@ -1,68 +1,72 @@ -package com.plotsquared.bukkit.util.block; +package com.github.intellectualsites.plotsquared.bukkit.util.block; -import com.intellectualcrafters.plot.object.PlotBlock; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue; -import java.lang.reflect.Field; -import java.lang.reflect.Method; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.object.LegacyPlotBlock; +import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; +import com.github.intellectualsites.plotsquared.plot.object.StringPlotBlock; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.block.BasicLocalBlockQueue; +import lombok.NonNull; import org.bukkit.Bukkit; import org.bukkit.Chunk; +import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.block.Block; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Locale; + public class BukkitLocalQueue extends BasicLocalBlockQueue { + private Field fieldNeighbors; + private Method chunkGetHandle; + public BukkitLocalQueue(String world) { super(world); } - @Override - public LocalChunk getLocalChunk(int x, int z) { + @Override public LocalChunk getLocalChunk(int x, int z) { return (LocalChunk) new BasicLocalChunk(this, x, z) { // Custom stuff? }; } - @Override - public void optimize() { + @Override public void optimize() { } - @Override - public PlotBlock getBlock(int x, int y, int z) { + @Override public PlotBlock getBlock(int x, int y, int z) { World worldObj = Bukkit.getWorld(getWorld()); Block block = worldObj.getBlockAt(x, y, z); if (block == null) { return PlotBlock.get(0, 0); } - int id = block.getTypeId(); - if (id == 0) { - return PlotBlock.get(0, 0); - } - return PlotBlock.get(id, block.getData()); + // int id = block.getTypeId(); + // if (id == 0) { + // return PlotBlock.get(0, 0); + // } + // return PlotBlock.get(id, block.getData()); + return PlotBlock.get(block.getType().toString()); } - @Override - public void refreshChunk(int x, int z) { + @Override public void refreshChunk(int x, int z) { World worldObj = Bukkit.getWorld(getWorld()); worldObj.refreshChunk(x, z); } - @Override - public void fixChunkLighting(int x, int z) { + @Override public void fixChunkLighting(int x, int z) { // Do nothing } - @Override - public final void regenChunk(int x, int z) { + @Override public final void regenChunk(int x, int z) { World worldObj = Bukkit.getWorld(getWorld()); worldObj.regenerateChunk(x, z); } - @Override - public final void setComponents(LocalChunk lc) { + @Override public final void setComponents(LocalChunk lc) { setBlocks(lc); setBiomes(lc); } @@ -89,22 +93,53 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { int y = MainUtil.y_loc[layer][j]; int z = MainUtil.z_loc[layer][j]; Block existing = chunk.getBlock(x, y, z); - int existingId = existing.getTypeId(); - if (existingId == block.id) { - if (existingId == 0) { - continue; - } - if (existing.getData() == block.data) { - continue; - } + // int existingId = existing.getTypeId(); + // if (existingId == block.id) { + // if (existingId == 0) { + // continue; + // } + // if (existing.getData() == block.data) { + // continue; + // } + //} + if (equals(block, existing)) { + continue; } - existing.setTypeIdAndData(block.id, block.data, false); + setMaterial(block, existing); } } } } } + private void setMaterial(@NonNull final PlotBlock plotBlock, @NonNull final Block block) { + if (plotBlock instanceof StringPlotBlock) { + final Material material = Material + .getMaterial(((StringPlotBlock) plotBlock).getItemId().toLowerCase(Locale.ENGLISH)); + if (material == null) { + throw new IllegalStateException( + String.format("Could not find material that matches %s", block.toString())); + } + block.setType(material, false); + } else { + final LegacyPlotBlock legacyPlotBlock = (LegacyPlotBlock) plotBlock; + block.setType(Material.getMaterial(PlotSquared.get().IMP.getLegacyMappings() + .fromLegacyToString(legacyPlotBlock.getId(), legacyPlotBlock.getData()) + .toString())); + // block.setTypeIdAndData(legacyPlotBlock.getId(), legacyPlotBlock.getData(), false); + } + } + + private boolean equals(@NonNull final PlotBlock plotBlock, @NonNull final Block block) { + if (plotBlock instanceof StringPlotBlock) { + return ((StringPlotBlock) plotBlock).idEquals(block.getType().name()); + } + final LegacyPlotBlock legacyPlotBlock = (LegacyPlotBlock) plotBlock; + return Material.getMaterial(PlotSquared.get().IMP.getLegacyMappings() + .fromLegacyToString(((LegacyPlotBlock) plotBlock).id).toString()) == block.getType() + && (legacyPlotBlock.id == 0 || legacyPlotBlock.data == block.getData()); + } + public void setBiomes(LocalChunk lc) { if (lc.biomes != null) { World worldObj = Bukkit.getWorld(getWorld()); @@ -129,13 +164,11 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { } } - private Field fieldNeighbors; - private Method chunkGetHandle; - /** * Exploiting a bug in the vanilla lighting algorithm for faster block placement - * - Could have been achieved without reflection by force unloading specific chunks - * - Much faster just setting the variable manually though + * - Could have been achieved without reflection by force unloading specific chunks + * - Much faster just setting the variable manually though + * * @param chunk * @return */ @@ -153,7 +186,8 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { Object value = fieldNeighbors.get(nmsChunk); fieldNeighbors.set(nmsChunk, 0); return new Object[] {nmsChunk, value}; - } catch (Throwable ignore) {} + } catch (Throwable ignore) { + } return null; } @@ -181,7 +215,8 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { if (disableResult != null) { try { fieldNeighbors.set(disableResult[0], 0x739C0); - } catch (Throwable ignore) {} + } catch (Throwable ignore) { + } } } -} \ No newline at end of file +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/GenChunk.java similarity index 82% rename from Bukkit/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/GenChunk.java index 13d4394ce..e700a3433 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/GenChunk.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/GenChunk.java @@ -1,12 +1,11 @@ -package com.plotsquared.bukkit.util.block; +package com.github.intellectualsites.plotsquared.bukkit.util.block; -import com.intellectualcrafters.plot.object.ChunkWrapper; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.PlotBlock; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue; -import com.plotsquared.bukkit.util.BukkitUtil; -import java.util.Arrays; +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil; +import com.github.intellectualsites.plotsquared.plot.object.ChunkWrapper; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue; import org.bukkit.Chunk; import org.bukkit.Material; import org.bukkit.World; @@ -15,6 +14,8 @@ import org.bukkit.generator.ChunkGenerator.BiomeGrid; import org.bukkit.generator.ChunkGenerator.ChunkData; import org.bukkit.material.MaterialData; +import java.util.Arrays; + public class GenChunk extends ScopedLocalBlockQueue { public final Biome[] biomes; @@ -37,13 +38,6 @@ public class GenChunk extends ScopedLocalBlockQueue { this.chunk = chunk; } - public void setChunk(ChunkWrapper wrap) { - chunk = null; - world = wrap.world; - cx = wrap.x; - cz = wrap.z; - } - public Chunk getChunk() { if (chunk == null) { World worldObj = BukkitUtil.getWorld(world); @@ -54,6 +48,13 @@ public class GenChunk extends ScopedLocalBlockQueue { return chunk; } + public void setChunk(ChunkWrapper wrap) { + chunk = null; + world = wrap.world; + cx = wrap.x; + cz = wrap.z; + } + public ChunkWrapper getChunkWrapper() { if (chunk == null) { return new ChunkWrapper(world, cx, cz); @@ -61,8 +62,7 @@ public class GenChunk extends ScopedLocalBlockQueue { return new ChunkWrapper(chunk.getWorld().getName(), chunk.getX(), chunk.getZ()); } - @Override - public void fillBiome(String biomeName) { + @Override public void fillBiome(String biomeName) { if (grid == null) { return; } @@ -74,9 +74,9 @@ public class GenChunk extends ScopedLocalBlockQueue { } } - @Override - public void setCuboid(Location pos1, Location pos2, PlotBlock block) { - if (block.data == 0 && result != null && pos1.getX() == 0 && pos1.getZ() == 0 && pos2.getX() == 15 && pos2.getZ() == 15) { + @Override public void setCuboid(Location pos1, Location pos2, PlotBlock block) { + if (block.data == 0 && result != null && pos1.getX() == 0 && pos1.getZ() == 0 + && pos2.getX() == 15 && pos2.getZ() == 15) { for (int y = pos1.getY(); y <= pos2.getY(); y++) { int layer = y >> 4; short[] data = result[layer]; @@ -92,8 +92,7 @@ public class GenChunk extends ScopedLocalBlockQueue { } } - @Override - public boolean setBiome(int x, int z, String biome) { + @Override public boolean setBiome(int x, int z, String biome) { return setBiome(x, z, Biome.valueOf(biome.toUpperCase())); } @@ -113,8 +112,7 @@ public class GenChunk extends ScopedLocalBlockQueue { return false; } - @Override - public boolean setBlock(int x, int y, int z, int id, int data) { + @Override public boolean setBlock(int x, int y, int z, int id, int data) { if (this.result == null) { this.cd.setBlock(x, y, z, new MaterialData(Material.getMaterial(id), (byte) data)); return true; @@ -136,8 +134,7 @@ public class GenChunk extends ScopedLocalBlockQueue { return true; } - @Override - public PlotBlock getBlock(int x, int y, int z) { + @Override public PlotBlock getBlock(int x, int y, int z) { int i = MainUtil.CACHE_I[y][x][z]; if (result == null) { MaterialData md = cd.getTypeAndData(x, y, z); @@ -167,23 +164,21 @@ public class GenChunk extends ScopedLocalBlockQueue { return chunk == null ? cz : chunk.getZ(); } - @Override - public String getWorld() { + @Override public String getWorld() { return chunk == null ? world : chunk.getWorld().getName(); } - @Override - public Location getMax() { + @Override public Location getMax() { return new Location(getWorld(), 15 + (getX() << 4), 255, 15 + (getZ() << 4)); } - @Override - public Location getMin() { + @Override public Location getMin() { return new Location(getWorld(), getX() << 4, 0, getZ() << 4); } public GenChunk clone() { - GenChunk toReturn = new GenChunk(chunk, new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ())); + GenChunk toReturn = + new GenChunk(chunk, new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ())); if (this.result != null) { for (int i = 0; i < this.result.length; i++) { short[] matrix = this.result[i]; diff --git a/Nukkit/src/main/java/com/plotsquared/nukkit/uuid/DatFileFilter.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/DatFileFilter.java similarity index 55% rename from Nukkit/src/main/java/com/plotsquared/nukkit/uuid/DatFileFilter.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/DatFileFilter.java index c2bb3b938..2fb0892a7 100644 --- a/Nukkit/src/main/java/com/plotsquared/nukkit/uuid/DatFileFilter.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/DatFileFilter.java @@ -1,12 +1,11 @@ -package com.plotsquared.nukkit.uuid; +package com.github.intellectualsites.plotsquared.bukkit.uuid; import java.io.File; import java.io.FilenameFilter; public class DatFileFilter implements FilenameFilter { - @Override - public boolean accept(File dir, String name) { + @Override public boolean accept(File dir, String name) { return name.endsWith(".dat"); } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java new file mode 100644 index 000000000..3660bef92 --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java @@ -0,0 +1,43 @@ +package com.github.intellectualsites.plotsquared.bukkit.uuid; + +import com.github.intellectualsites.plotsquared.bukkit.object.BukkitOfflinePlayer; +import com.github.intellectualsites.plotsquared.bukkit.object.BukkitPlayer; +import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; + +import java.util.UUID; + +public class DefaultUUIDWrapper extends UUIDWrapper { + + @Override public UUID getUUID(PlotPlayer player) { + return ((BukkitPlayer) player).player.getUniqueId(); + } + + @Override public UUID getUUID(OfflinePlotPlayer player) { + return player.getUUID(); + } + + @Override public OfflinePlotPlayer getOfflinePlayer(UUID uuid) { + return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(uuid)); + } + + @Override public UUID getUUID(String name) { + return Bukkit.getOfflinePlayer(name).getUniqueId(); + } + + @Override public OfflinePlotPlayer[] getOfflinePlayers() { + OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); + BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; + for (int i = 0; i < ops.length; i++) { + toReturn[i] = new BukkitOfflinePlayer(ops[i]); + } + return toReturn; + } + + @Override public OfflinePlotPlayer getOfflinePlayer(String name) { + return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(name)); + } +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/FileUUIDHandler.java similarity index 70% rename from Bukkit/src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/FileUUIDHandler.java index 15cf9b6ad..2223feceb 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/FileUUIDHandler.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/FileUUIDHandler.java @@ -1,20 +1,23 @@ -package com.plotsquared.bukkit.uuid; +package com.github.intellectualsites.plotsquared.bukkit.uuid; +import com.github.intellectualsites.plotsquared.bukkit.util.NbtFactory; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.object.StringWrapper; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandlerImplementation; +import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; +import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper; import com.google.common.collect.HashBiMap; import com.google.common.collect.Sets; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.object.OfflinePlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.StringWrapper; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.UUIDHandlerImplementation; -import com.intellectualcrafters.plot.util.expiry.ExpireManager; -import com.intellectualcrafters.plot.uuid.UUIDWrapper; -import com.plotsquared.bukkit.util.NbtFactory; +import org.bukkit.Bukkit; +import org.bukkit.World; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -24,9 +27,6 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.UUID; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.entity.Player; public class FileUUIDHandler extends UUIDHandlerImplementation { @@ -34,8 +34,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { super(wrapper); } - @Override - public boolean startCaching(Runnable whenDone) { + @Override public boolean startCaching(Runnable whenDone) { return super.startCaching(whenDone) && cache(whenDone); } @@ -49,13 +48,13 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { world = worlds.get(0).getName(); } TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { - PS.debug(C.PREFIX + "&6Starting player data caching for: " + world); - File uuidFile = new File(PS.get().IMP.getDirectory(), "uuids.txt"); + @Override public void run() { + PlotSquared.debug(C.PREFIX + "&6Starting player data caching for: " + world); + File uuidFile = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt"); if (uuidFile.exists()) { try { - List lines = Files.readAllLines(uuidFile.toPath(), StandardCharsets.UTF_8); + List lines = + Files.readAllLines(uuidFile.toPath(), StandardCharsets.UTF_8); for (String line : lines) { try { line = line.trim(); @@ -65,7 +64,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); String[] split = line.split("\\|"); String name = split[0]; - if (name.isEmpty() || (name.length() > 16) || !StringMan.isAlphanumericUnd(name)) { + if (name.isEmpty() || (name.length() > 16) || !StringMan + .isAlphanumericUnd(name)) { continue; } UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); @@ -81,11 +81,13 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { e.printStackTrace(); } } - HashBiMap toAdd = HashBiMap.create(new HashMap()); + HashBiMap toAdd = + HashBiMap.create(new HashMap()); if (Settings.UUID.NATIVE_UUID_PROVIDER) { HashSet all = UUIDHandler.getAllUUIDS(); - PS.debug("&aFast mode UUID caching enabled!"); - File playerDataFolder = new File(container, world + File.separator + "playerdata"); + PlotSquared.debug("&aFast mode UUID caching enabled!"); + File playerDataFolder = + new File(container, world + File.separator + "playerdata"); String[] dat = playerDataFolder.list(new DatFileFilter()); boolean check = all.isEmpty(); if (dat != null) { @@ -95,11 +97,15 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { UUID uuid = UUID.fromString(s); if (check || all.remove(uuid)) { File file = new File(playerDataFolder, current); - NbtFactory.NbtCompound compound = NbtFactory.fromStream(new FileInputStream(file), NbtFactory.StreamOptions.GZIP_COMPRESSION); + NbtFactory.NbtCompound compound = NbtFactory + .fromStream(new FileInputStream(file), + NbtFactory.StreamOptions.GZIP_COMPRESSION); if (!compound.containsKey("bukkit")) { - PS.debug("ERROR: Player data (" + uuid.toString() + ".dat) does not contain the the key \"bukkit\""); + PlotSquared.debug("ERROR: Player data (" + uuid.toString() + + ".dat) does not contain the the key \"bukkit\""); } else { - NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit"); + NbtFactory.NbtCompound bukkit = + (NbtFactory.NbtCompound) compound.get("bukkit"); String name = (String) bukkit.get("lastKnownName"); long last = (long) bukkit.get("lastPlayed"); long first = (long) bukkit.get("firstPlayed"); @@ -112,7 +118,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { } } catch (Exception e) { e.printStackTrace(); - PS.debug(C.PREFIX + "Invalid playerdata: " + current); + PlotSquared.debug(C.PREFIX + "Invalid playerdata: " + current); } } } @@ -123,7 +129,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { } return; } else { - PS.debug("Failed to cache: " + all.size() + " uuids - slowly processing all files"); + PlotSquared.debug("Failed to cache: " + all.size() + + " uuids - slowly processing all files"); } } HashSet worlds = Sets.newHashSet(world, "world"); @@ -132,7 +139,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { File playerDataFolder = null; for (String worldName : worlds) { // Getting UUIDs - playerDataFolder = new File(container, worldName + File.separator + "playerdata"); + playerDataFolder = + new File(container, worldName + File.separator + "playerdata"); String[] dat = playerDataFolder.list(new DatFileFilter()); if ((dat != null) && (dat.length != 0)) { for (String current : dat) { @@ -141,7 +149,7 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { UUID uuid = UUID.fromString(s); uuids.add(uuid); } catch (Exception ignored) { - PS.debug(C.PREFIX + "Invalid PlayerData: " + current); + PlotSquared.debug(C.PREFIX + "Invalid PlayerData: " + current); } } break; @@ -158,22 +166,28 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { } for (UUID uuid : uuids) { try { - File file = new File(playerDataFolder + File.separator + uuid.toString() + ".dat"); + File file = + new File(playerDataFolder + File.separator + uuid.toString() + ".dat"); if (!file.exists()) { continue; } - NbtFactory.NbtCompound compound = NbtFactory.fromStream(new FileInputStream(file), NbtFactory.StreamOptions.GZIP_COMPRESSION); + NbtFactory.NbtCompound compound = NbtFactory + .fromStream(new FileInputStream(file), + NbtFactory.StreamOptions.GZIP_COMPRESSION); if (!compound.containsKey("bukkit")) { - PS.debug("ERROR: Player data (" + uuid.toString() + ".dat) does not contain the the key \"bukkit\""); + PlotSquared.debug("ERROR: Player data (" + uuid.toString() + + ".dat) does not contain the the key \"bukkit\""); } else { - NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit"); + NbtFactory.NbtCompound bukkit = + (NbtFactory.NbtCompound) compound.get("bukkit"); String name = (String) bukkit.get("lastKnownName"); StringWrapper wrap = new StringWrapper(name); if (!toAdd.containsKey(wrap)) { long last = (long) bukkit.get("lastPlayed"); long first = (long) bukkit.get("firstPlayed"); if (Settings.UUID.OFFLINE) { - if (Settings.UUID.FORCE_LOWERCASE && !name.toLowerCase().equals(name)) { + if (Settings.UUID.FORCE_LOWERCASE && !name.toLowerCase() + .equals(name)) { uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); } else { long most = (long) compound.get("UUIDMost"); @@ -189,7 +203,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { } } } catch (Exception ignored) { - PS.debug(C.PREFIX + "&6Invalid PlayerData: " + uuid.toString() + ".dat"); + PlotSquared + .debug(C.PREFIX + "&6Invalid PlayerData: " + uuid.toString() + ".dat"); } } for (String name : names) { @@ -199,7 +214,8 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { } if (getUUIDMap().isEmpty()) { - for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper.getOfflinePlayers()) { + for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper + .getOfflinePlayers()) { long last = op.getLastPlayed(); if (last != 0) { String name = op.getName(); @@ -223,11 +239,9 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { return true; } - @Override - public void fetchUUID(final String name, final RunnableVal ifFetch) { + @Override public void fetchUUID(final String name, final RunnableVal ifFetch) { TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name); TaskManager.runTask(ifFetch); } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java new file mode 100644 index 000000000..55e2039a0 --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java @@ -0,0 +1,32 @@ +package com.github.intellectualsites.plotsquared.bukkit.uuid; + +import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.google.common.base.Charsets; +import org.bukkit.OfflinePlayer; + +import java.util.UUID; + +public class LowerOfflineUUIDWrapper extends OfflineUUIDWrapper { + + @Override public UUID getUUID(PlotPlayer player) { + return UUID.nameUUIDFromBytes( + ("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); + } + + @Override public UUID getUUID(OfflinePlotPlayer player) { + return UUID.nameUUIDFromBytes( + ("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); + } + + @Override public UUID getUUID(OfflinePlayer player) { + return UUID.nameUUIDFromBytes( + ("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); + } + + @Override public UUID getUUID(String name) { + return UUID + .nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8)); + } + +} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java similarity index 65% rename from Bukkit/src/main/java/com/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java index 273ff8fc1..c44fa6e72 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java @@ -1,14 +1,14 @@ -package com.plotsquared.bukkit.uuid; +package com.github.intellectualsites.plotsquared.bukkit.uuid; +import com.github.intellectualsites.plotsquared.bukkit.object.BukkitOfflinePlayer; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.StringWrapper; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper; import com.google.common.base.Charsets; import com.google.common.collect.BiMap; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.object.OfflinePlotPlayer; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.StringWrapper; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.uuid.UUIDWrapper; -import com.plotsquared.bukkit.object.BukkitOfflinePlayer; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.Server; @@ -32,22 +32,22 @@ public class OfflineUUIDWrapper extends UUIDWrapper { } } - @Override - public UUID getUUID(PlotPlayer player) { - return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); + @Override public UUID getUUID(PlotPlayer player) { + return UUID + .nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); } - @Override - public UUID getUUID(OfflinePlotPlayer player) { - return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); + @Override public UUID getUUID(OfflinePlotPlayer player) { + return UUID + .nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); } public UUID getUUID(OfflinePlayer player) { - return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); + return UUID + .nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); } - @Override - public OfflinePlotPlayer getOfflinePlayer(UUID uuid) { + @Override public OfflinePlotPlayer getOfflinePlayer(UUID uuid) { BiMap map = UUIDHandler.getUuidMap().inverse(); String name = null; if (map.containsKey(uuid)) { @@ -77,24 +77,23 @@ public class OfflineUUIDWrapper extends UUIDWrapper { if (players instanceof Player[]) { return (Player[]) players; } else { - @SuppressWarnings("unchecked") Collection p = (Collection) players; + @SuppressWarnings("unchecked") Collection p = + (Collection) players; return p.toArray(new Player[p.size()]); } } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ignored) { - PS.debug("Failed to resolve online players"); + PlotSquared.debug("Failed to resolve online players"); this.getOnline = null; Collection onlinePlayers = Bukkit.getOnlinePlayers(); return onlinePlayers.toArray(new Player[onlinePlayers.size()]); } } - @Override - public UUID getUUID(String name) { + @Override public UUID getUUID(String name) { return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); } - @Override - public OfflinePlotPlayer[] getOfflinePlayers() { + @Override public OfflinePlotPlayer[] getOfflinePlayers() { OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; for (int i = 0; i < ops.length; i++) { @@ -103,8 +102,7 @@ public class OfflineUUIDWrapper extends UUIDWrapper { return toReturn; } - @Override - public OfflinePlotPlayer getOfflinePlayer(String name) { + @Override public OfflinePlotPlayer getOfflinePlayer(String name) { return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(name)); } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/SQLUUIDHandler.java similarity index 63% rename from Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java rename to Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/SQLUUIDHandler.java index d5d61d030..1c9a30bba 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/SQLUUIDHandler.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/SQLUUIDHandler.java @@ -1,17 +1,22 @@ -package com.plotsquared.bukkit.uuid; +package com.github.intellectualsites.plotsquared.bukkit.uuid; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.database.SQLite; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.object.StringWrapper; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandlerImplementation; +import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper; import com.google.common.collect.HashBiMap; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.SQLite; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.StringWrapper; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.UUIDHandlerImplementation; -import com.intellectualcrafters.plot.uuid.UUIDWrapper; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -26,22 +31,20 @@ import java.util.ArrayDeque; import java.util.Collections; import java.util.HashMap; import java.util.UUID; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; public class SQLUUIDHandler extends UUIDHandlerImplementation { final int MAX_REQUESTS = 500; - private final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/"; + private final String PROFILE_URL = + "https://sessionserver.mojang.com/session/minecraft/profile/"; private final int INTERVAL = 12000; private final JSONParser jsonParser = new JSONParser(); private final SQLite sqlite; public SQLUUIDHandler(UUIDWrapper wrapper) { super(wrapper); - this.sqlite = new SQLite(MainUtil.getFile(PS.get().IMP.getDirectory(), "usercache.db")); + this.sqlite = + new SQLite(MainUtil.getFile(PlotSquared.get().IMP.getDirectory(), "usercache.db")); try { this.sqlite.openConnection(); } catch (ClassNotFoundException | SQLException e) { @@ -49,8 +52,8 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } try (PreparedStatement stmt = getConnection().prepareStatement( - "CREATE TABLE IF NOT EXISTS `usercache` (uuid VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, PRIMARY KEY (uuid, username)" - + ')')) { + "CREATE TABLE IF NOT EXISTS `usercache` (uuid VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, PRIMARY KEY (uuid, username)" + + ')')) { stmt.execute(); } catch (SQLException e) { e.printStackTrace(); @@ -64,20 +67,21 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } } - @Override - public boolean startCaching(final Runnable whenDone) { + @Override public boolean startCaching(final Runnable whenDone) { if (!super.startCaching(whenDone)) { return false; } TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { try { - HashBiMap toAdd = HashBiMap.create(new HashMap()); - try (PreparedStatement statement = getConnection().prepareStatement("SELECT `uuid`, `username` FROM `usercache`"); - ResultSet resultSet = statement.executeQuery()) { + HashBiMap toAdd = + HashBiMap.create(new HashMap()); + try (PreparedStatement statement = getConnection() + .prepareStatement("SELECT `uuid`, `username` FROM `usercache`"); + ResultSet resultSet = statement.executeQuery()) { while (resultSet.next()) { - StringWrapper username = new StringWrapper(resultSet.getString("username")); + StringWrapper username = + new StringWrapper(resultSet.getString("username")); UUID uuid = UUID.fromString(resultSet.getString("uuid")); toAdd.put(new StringWrapper(username.value), uuid); } @@ -96,10 +100,10 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } return; } - FileUUIDHandler fileHandler = new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper); + FileUUIDHandler fileHandler = + new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper); fileHandler.startCaching(new Runnable() { - @Override - public void run() { + @Override public void run() { // If the file based UUID handler didn't cache it, then we can't cache offline mode // Also, trying to cache based on files again, is useless as that's what the file based uuid cacher does if (Settings.UUID.OFFLINE) { @@ -110,18 +114,24 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { while (!toFetch.isEmpty()) { try { - for (int i = 0; i < Math.min(500, toFetch.size()); i++) { + for (int i = 0; + i < Math.min(500, toFetch.size()); i++) { UUID uuid = toFetch.pop(); HttpURLConnection connection = - (HttpURLConnection) new URL(SQLUUIDHandler.this.PROFILE_URL + uuid.toString().replace("-", "")) - .openConnection(); - try (InputStream con = connection.getInputStream()) { - InputStreamReader reader = new InputStreamReader(con); - JSONObject response = (JSONObject) SQLUUIDHandler.this.jsonParser.parse(reader); + (HttpURLConnection) new URL( + SQLUUIDHandler.this.PROFILE_URL + uuid + .toString().replace("-", "")) + .openConnection(); + try (InputStream con = connection + .getInputStream()) { + InputStreamReader reader = + new InputStreamReader(con); + JSONObject response = + (JSONObject) SQLUUIDHandler.this.jsonParser + .parse(reader); String name = (String) response.get("name"); if (name != null) { add(new StringWrapper(name), uuid); @@ -129,8 +139,9 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } connection.disconnect(); } - }catch(IOException | ParseException e){ - PS.debug("Invalid response from Mojang: Some UUIDs will be cached later. (`unknown` until then or player joins)"); + } catch (IOException | ParseException e) { + PlotSquared.debug( + "Invalid response from Mojang: Some UUIDs will be cached later. (`unknown` until then or player joins)"); } try { Thread.sleep(INTERVAL * 50); @@ -155,15 +166,14 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { return true; } - @Override - public void fetchUUID(final String name, final RunnableVal ifFetch) { - PS.debug(C.PREFIX + "UUID for '" + name + "' was null. We'll cache this from the Mojang servers!"); + @Override public void fetchUUID(final String name, final RunnableVal ifFetch) { + PlotSquared.debug(C.PREFIX + "UUID for '" + name + + "' was null. We'll cache this from the Mojang servers!"); if (ifFetch == null) { return; } TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { try { URL url = new URL(SQLUUIDHandler.this.PROFILE_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); @@ -177,13 +187,14 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { stream.write(body.getBytes()); stream.flush(); stream.close(); - JSONArray array = (JSONArray) SQLUUIDHandler.this.jsonParser.parse(new InputStreamReader(connection.getInputStream())); + JSONArray array = (JSONArray) SQLUUIDHandler.this.jsonParser + .parse(new InputStreamReader(connection.getInputStream())); JSONObject jsonProfile = (JSONObject) array.get(0); String id = (String) jsonProfile.get("id"); String name = (String) jsonProfile.get("name"); ifFetch.value = UUID.fromString( - id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16) + '-' + id.substring(16, 20) + '-' + id - .substring(20, 32)); + id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16) + + '-' + id.substring(16, 20) + '-' + id.substring(20, 32)); } catch (IOException | ParseException e) { e.printStackTrace(); } @@ -192,8 +203,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { }); } - @Override - public void handleShutdown() { + @Override public void handleShutdown() { super.handleShutdown(); try { getConnection().close(); @@ -202,18 +212,18 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } } - @Override - public boolean add(final StringWrapper name, final UUID uuid) { + @Override public boolean add(final StringWrapper name, final UUID uuid) { // Ignoring duplicates if (super.add(name, uuid)) { TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { - try (PreparedStatement statement = getConnection().prepareStatement("REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) { + @Override public void run() { + try (PreparedStatement statement = getConnection().prepareStatement( + "REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) { statement.setString(1, uuid.toString()); statement.setString(2, name.toString()); statement.execute(); - PS.debug(C.PREFIX + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'"); + PlotSquared + .debug(C.PREFIX + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'"); } catch (SQLException e) { e.printStackTrace(); } @@ -227,17 +237,17 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { /** * This is useful for name changes */ - @Override - public void rename(final UUID uuid, final StringWrapper name) { + @Override public void rename(final UUID uuid, final StringWrapper name) { super.rename(uuid, name); TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { - try (PreparedStatement statement = getConnection().prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) { + @Override public void run() { + try (PreparedStatement statement = getConnection() + .prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) { statement.setString(1, name.value); statement.setString(2, uuid.toString()); statement.execute(); - PS.debug(C.PREFIX + "Name change for '" + uuid + "' to '" + name.value + '\''); + PlotSquared.debug( + C.PREFIX + "Name change for '" + uuid + "' to '" + name.value + '\''); } catch (SQLException e) { e.printStackTrace(); } diff --git a/Bukkit/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java b/Bukkit/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java deleted file mode 100644 index 519de20ef..000000000 --- a/Bukkit/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java +++ /dev/null @@ -1,733 +0,0 @@ -package com.intellectualcrafters.plot.api; - -import com.intellectualcrafters.configuration.file.YamlConfiguration; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.commands.SubCommand; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotManager; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.block.GlobalBlockQueue; -import com.intellectualcrafters.plot.uuid.UUIDWrapper; -import com.plotsquared.bukkit.util.BukkitUtil; -import org.bukkit.Location; -import org.bukkit.OfflinePlayer; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; - -/** - * PlotSquared API. - * - *

Useful classes: - *

    - *
  • {@link BukkitUtil}
  • - *
  • {@link PlotPlayer}
  • - *
  • {@link Plot}
  • - *
  • {@link com.intellectualcrafters.plot.object.Location}
  • - *
  • {@link PlotArea}
  • - *
  • {@link PS}
  • - *
- * @version 3.3.3 - */ -public class PlotAPI { - - /** - * Deprecated, does nothing. - * @param plugin not needed - * @deprecated Not needed - */ - @Deprecated - public PlotAPI(JavaPlugin plugin) {} - - public PlotAPI(){} - - /** - * Get all plots. - * - * @return all plots - * - * @see PS#getPlots() - */ - public Set getAllPlots() { - return PS.get().getPlots(); - } - - /** - * Return all plots for a player. - * - * @param player Player, whose plots to search for - * - * @return all plots that a player owns - */ - public Set getPlayerPlots(Player player) { - return PS.get().getPlots(BukkitUtil.getPlayer(player)); - } - - /** - * Add a plot world. - * - * @param plotArea Plot World Object - * @see PS#addPlotArea(PlotArea) - */ - public void addPlotArea(PlotArea plotArea) { - PS.get().addPlotArea(plotArea); - } - - /** - * Returns the PlotSquared configurations file. - * @return main configuration - * - * @see PS#config - */ - public YamlConfiguration getConfig() { - return PS.get().config; - } - - /** - * Get the PlotSquared storage file. - * @return storage configuration - * - * @see PS#storage - */ - public YamlConfiguration getStorage() { - return PS.get().storage; - } - - /** - * Get the main class for this plugin. Only use this if you really need it. - * - * @return PlotSquared PlotSquared Main Class - * - * @see PS - */ - public PS getMain() { - return PS.get(); - } - - /** - * ChunkManager class contains several useful methods. - *
    - *
  • Chunk deletion
  • - *
  • Moving or copying regions
  • - *
  • Plot swapping
  • - *
  • Entity Tracking
  • - *
  • Region Regeneration
  • - *
- * - * @return ChunkManager - * - * @see ChunkManager - */ - public ChunkManager getChunkManager() { - return ChunkManager.manager; - } - - /** - * Get the block/biome set queue - * @return GlobalBlockQueue.IMP - */ - public GlobalBlockQueue getBlockQueue() { - return GlobalBlockQueue.IMP; - } - - /** - * UUIDWrapper class has basic methods for getting UUIDS. It's recommended - * to use the UUIDHandler class instead. - * - * @return UUIDWrapper - * - * @see UUIDWrapper - */ - public UUIDWrapper getUUIDWrapper() { - return UUIDHandler.getUUIDWrapper(); - } - - /** - * Do not use this. Instead use FlagManager.[method] in your code. - * - Flag related stuff - * - * @return FlagManager - * - * @deprecated Use {@link FlagManager} directly - */ - @Deprecated - public FlagManager getFlagManager() { - return new FlagManager(); - } - - /** - * Do not use this. Instead use MainUtil.[method] in your code. - * - * @return MainUtil - * @deprecated Use {@link MainUtil} directly - */ - @Deprecated - public MainUtil getMainUtil() { - return new MainUtil(); - } - - /** - * Do not use this. Instead use C.PERMISSION_[method] in your code. - * - * @return Array of strings - * - * @see Permissions - * @deprecated Use {@link C} to list all the permissions - */ - @Deprecated - public String[] getPermissions() { - ArrayList perms = new ArrayList<>(); - for (C caption : C.values()) { - if ("static.permissions".equals(caption.getCategory())) { - perms.add(caption.s()); - } - } - return perms.toArray(new String[perms.size()]); - } - - /** - * SchematicHandler class contains methods related to pasting, reading - * and writing schematics. - * - * @return SchematicHandler - * - * @see SchematicHandler - */ - public SchematicHandler getSchematicHandler() { - return SchematicHandler.manager; - } - - /** - * Use C.[caption] instead - * - * @return C - * @deprecated Use {@link C} - */ - @Deprecated - public C[] getCaptions() { - return C.values(); - } - - /** - * Get the plot manager for a world. Most of these methods can be accessed - * through the MainUtil. - * - * @param world the world to retrieve the manager from - * - * @return PlotManager - * - * @see PlotManager - * @see PS#getPlotManager(Plot) - */ - @SuppressWarnings("deprecation") - @Deprecated - public PlotManager getPlotManager(World world) { - if (world == null) { - return null; - } - return getPlotManager(world.getName()); - } - - /** - * Get a list of PlotAreas in the world. - * @param world The world to check for plot areas - * @return A set of PlotAreas - */ - public Set getPlotAreas(World world) { - if (world == null) { - return Collections.emptySet(); - } - return PS.get().getPlotAreas(world.getName()); - } - - /** - * Get the plot manager for a world. Contains useful low level methods for - * plot merging, clearing, and tessellation. - * - * @param world The world - * - * @return PlotManager - * - * @see PS#getPlotManager(Plot) - * @see PlotManager - */ - @Deprecated - public PlotManager getPlotManager(String world) { - Set areas = PS.get().getPlotAreas(world); - switch (areas.size()) { - case 0: - return null; - case 1: - return areas.iterator().next().manager; - default: - PS.debug("PlotAPI#getPlotManager(org.bukkit.World) is deprecated and doesn't support multi plot area worlds."); - return null; - } - } - - /** - * Get the settings for a world (settings bundled in PlotArea class). You - * will need to downcast for the specific settings a Generator has. e.g. - * DefaultPlotWorld class implements PlotArea - * - * @param world The World - * - * @return The {@link PlotArea} for the world or null if not in plotworld - * - * @see #getPlotAreas(World) - * @see PlotArea - */ - @SuppressWarnings("deprecation") - @Deprecated - public PlotArea getWorldSettings(World world) { - if (world == null) { - return null; - } - return getWorldSettings(world.getName()); - } - - /** - * Get the settings for a world. - * - * @param world the world to retrieve settings from - * - * @return The {@link PlotArea} for the world or null if not in plotworld - * - * @see PS#getPlotArea(String, String) - * @see PlotArea - */ - @Deprecated - public PlotArea getWorldSettings(String world) { - if (world == null) { - return null; - } - Set areas = PS.get().getPlotAreas(world); - switch (areas.size()) { - case 0: - return null; - case 1: - return areas.iterator().next(); - default: - PS.debug("PlotAPI#getWorldSettings(org.bukkit.World) is deprecated and doesn't support multi plot area worlds."); - return null; - } - } - - /** - * Send a message to a player. - * - * @param player the recipient of the message - * @param caption the message - * - * @see MainUtil#sendMessage(PlotPlayer, C, String...) - */ - public void sendMessage(Player player, C caption) { - MainUtil.sendMessage(BukkitUtil.getPlayer(player), caption); - } - - /** - * Send a message to a player. The message supports color codes. - * - * @param player the recipient of the message - * @param string the message - * - * @see MainUtil#sendMessage(PlotPlayer, String) - */ - public void sendMessage(Player player, String string) { - MainUtil.sendMessage(BukkitUtil.getPlayer(player), string); - } - - /** - * Send a message to the console. The message supports color codes. - * - * @param message the message - * - * @see MainUtil#sendConsoleMessage(C, String...) - */ - public void sendConsoleMessage(String message) { - PS.log(message); - } - - /** - * Send a message to the console. - * - * @param caption the message - * - * @see #sendConsoleMessage(String) - * @see C - */ - public void sendConsoleMessage(C caption) { - sendConsoleMessage(caption.s()); - } - - /** - * Registers a flag for use in plots. - * - * @param flag the flag to register - * - */ - public void addFlag(Flag flag) { - Flags.registerFlag(flag); - } - - /** - * Gets a plot based on the ID. - * - * @param world the world the plot is located in - * @param x The PlotID x coordinate - * @param z The PlotID y coordinate - * - * @return plot, null if ID is wrong - * - * @see PlotArea#getPlot(PlotId) - */ - @SuppressWarnings("deprecation") - @Deprecated - public Plot getPlot(World world, int x, int z) { - if (world == null) { - return null; - } - PlotArea area = getWorldSettings(world); - if (area == null) { - return null; - } - return area.getPlot(new PlotId(x, z)); - } - - /** - * Get a plot based on the location. - * - * @param location the location to check - * - * @return plot if found, otherwise it creates a temporary plot - * - * @see Plot - */ - public Plot getPlot(Location location) { - if (location == null) { - return null; - } - return BukkitUtil.getLocation(location).getPlot(); - } - - /** - * Get a plot based on the player location. - * - * @param player the player to check - * - * @return plot if found, otherwise it creates a temporary plot - * - * @see #getPlot(Location) - * @see Plot - */ - public Plot getPlot(Player player) { - return this.getPlot(player.getLocation()); - } - - /** - * Check whether or not a player has a plot. - * - * @param player Player that you want to check for - * @param world The world to check - * @return true if player has a plot, false if not. - * - * @see #getPlots(World, Player, boolean) - */ - @SuppressWarnings("deprecation") - @Deprecated - public boolean hasPlot(World world, Player player) { - return getPlots(world, player, true).length > 0; - } - - /** - * Get all plots for the player. - * - * @param world The world to retrieve plots from - * @param player The player to search for - * @param justOwner should we just search for owner? Or with rights? - * @return An array of plots for the player - */ - @Deprecated - public Plot[] getPlots(World world, Player player, boolean justOwner) { - ArrayList pPlots = new ArrayList<>(); - UUID uuid = BukkitUtil.getPlayer(player).getUUID(); - for (Plot plot : PS.get().getPlots(world.getName())) { - if (justOwner) { - if (plot.hasOwner() && plot.isOwner(uuid)) { - pPlots.add(plot); - } - } else if (plot.isAdded(uuid)) { - pPlots.add(plot); - } - } - return pPlots.toArray(new Plot[pPlots.size()]); - } - - /** - * Get all plots for the world. - * - * @param world to get plots of - * - * @return Plot[] - array of plot objects in world - * - * @see PS#getPlots(String) - * @see Plot - */ - @Deprecated - public Plot[] getPlots(World world) { - if (world == null) { - return new Plot[0]; - } - Collection plots = PS.get().getPlots(world.getName()); - return plots.toArray(new Plot[plots.size()]); - } - - /** - * Get all plot worlds. - * - * @return World[] - array of plot worlds - * - */ - @SuppressWarnings("deprecation") - @Deprecated - public String[] getPlotWorlds() { - Set plotWorldStrings = PS.get().getPlotWorldStrings(); - return plotWorldStrings.toArray(new String[plotWorldStrings.size()]); - } - - /** - * Get if plotworld. - * - * @param world The world to check - * - * @return boolean (if plot world or not) - * - * @see PS#hasPlotArea(String) - */ - @Deprecated - public boolean isPlotWorld(World world) { - return PS.get().hasPlotArea(world.getName()); - } - - /** - * Get plot locations. - * - * @param plot Plot to get the locations for - * - * @return [0] = bottomLc, [1] = topLoc, [2] = home - * - * @deprecated As merged plots may not have a rectangular shape - * - * @see Plot - */ - @SuppressWarnings("deprecation") - @Deprecated - public Location[] getLocations(Plot plot) { - Location bukkitBottom = BukkitUtil.getLocation(plot.getCorners()[0]); - Location bukkitTop = BukkitUtil.getLocation(plot.getCorners()[1]); - Location bukkitHome = BukkitUtil.getLocation(plot.getHome()); - return new Location[]{bukkitBottom, bukkitTop, bukkitHome}; - } - - /** - * Get home location. - * - * @param plot Plot that you want to get the location for - * - * @return plot bottom location - * - * @see Plot - */ - public Location getHomeLocation(Plot plot) { - return BukkitUtil.getLocation(plot.getHome()); - } - - /** - * Get Bottom Location (min, min, min). - * - * @param plot Plot that you want to get the location for - * - * @return plot bottom location - * - * @deprecated As merged plots may not have a rectangular shape - * - * @see Plot - */ - @SuppressWarnings("deprecation") - @Deprecated - public Location getBottomLocation(Plot plot) { - return BukkitUtil.getLocation(plot.getCorners()[0]); - } - - /** - * Get Top Location (max, max, max). - * - * @param plot Plot that you want to get the location for - * - * @return plot top location - * - * @deprecated As merged plots may not have a rectangular shape - * - * @see Plot - */ - @SuppressWarnings("deprecation") - @Deprecated - public Location getTopLocation(Plot plot) { - return BukkitUtil.getLocation(plot.getCorners()[1]); - } - - /** - * Check whether or not a player is in a plot. - * - * @param player who we're checking for - * - * @return true if the player is in a plot, false if not- - * - */ - public boolean isInPlot(Player player) { - return getPlot(player) != null; - } - - /** - * Register a subcommand. - * @deprecated Command registration is done on object creation - * @param c SubCommand, that we want to register - * @see SubCommand - */ - @Deprecated - public void registerCommand(SubCommand c) { - PS.debug("SubCommands are now registered on creation"); - } - - /** - * Gets the PlotSquared class. - * - * @return PlotSquared Class - * - * @see PS - */ - public PS getPlotSquared() { - return PS.get(); - } - - /** - * Gets the player plot count. - * - * @param world Specify the world we want to select the plots from - * @param player Player, for whom we're getting the plot count - * - * @return the number of plots the player has - * - */ - public int getPlayerPlotCount(World world, Player player) { - if (world == null) { - return 0; - } - return BukkitUtil.getPlayer(player).getPlotCount(world.getName()); - } - - /** - * Gets a collection containing the players plots. - * - * @param world Specify the world we want to select the plots from - * @param player Player, for whom we're getting the plots - * - * @return a set containing the players plots - * - * @see PS#getPlots(String, PlotPlayer) - * - * @see Plot - */ - public Set getPlayerPlots(World world, Player player) { - if (world == null) { - return new HashSet<>(); - } - return PlotPlayer.wrap(player).getPlots(world.getName()); - } - - /** - * Gets the number of plots, which the player is able to build in. - * - * @param player player, for whom we're getting the plots - * - * @return the number of allowed plots - * - */ - public int getAllowedPlots(Player player) { - PlotPlayer plotPlayer = PlotPlayer.wrap(player); - return plotPlayer.getAllowedPlots(); - } - - /** - * Gets the PlotPlayer for a player. The PlotPlayer is usually cached and - * will provide useful functions relating to players. - * - * @see PlotPlayer#wrap(Object) - * - * @param player the player to wrap - * @return a {@code PlotPlayer} - */ - public PlotPlayer wrapPlayer(Player player) { - return PlotPlayer.wrap(player); - } - - /** - * Get the PlotPlayer for a UUID. - * - *

Please note that PlotSquared can be configured to provide - * different UUIDs than bukkit - * - * @see PlotPlayer#wrap(Object) - * - * @param uuid the uuid of the player to wrap - * @return a {@code PlotPlayer} - */ - public PlotPlayer wrapPlayer(UUID uuid) { - return PlotPlayer.wrap(uuid); - } - - /** - * Get the PlotPlayer for a username. - * - * @see PlotPlayer#wrap(Object) - * - * @param player the player to wrap - * @return a {@code PlotPlayer} - */ - public PlotPlayer wrapPlayer(String player) { - return PlotPlayer.wrap(player); - } - - /** - * Get the PlotPlayer for an offline player. - * - *

Note that this will work if the player is offline, however not all - * functionality will work. - * - * @see PlotPlayer#wrap(Object) - * - * @param player the player to wrap - * @return a {@code PlotPlayer} - */ - public PlotPlayer wrapPlayer(OfflinePlayer player) { - return PlotPlayer.wrap(player); - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/EntityPortal_1_7_9.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/EntityPortal_1_7_9.java deleted file mode 100644 index 20f029a3f..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/EntityPortal_1_7_9.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.plotsquared.bukkit.listeners; - -import com.intellectualcrafters.plot.PS; -import java.util.List; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Vehicle; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.event.entity.EntityTeleportEvent; -import org.bukkit.event.vehicle.*; -import org.bukkit.metadata.FixedMetadataValue; -import org.bukkit.metadata.MetadataValue; -import org.bukkit.plugin.Plugin; - -public class EntityPortal_1_7_9 implements Listener { - public EntityPortal_1_7_9() { - } - - @EventHandler - public void onVehicle(VehicleUpdateEvent event) { - test(event.getVehicle()); - } - - @EventHandler - public void onVehicle(VehicleDestroyEvent event) { - test(event.getVehicle()); - } - - @EventHandler - public void onVehicle(VehicleEntityCollisionEvent event) { - test(event.getVehicle()); - } - - @EventHandler - public void onVehicle(VehicleCreateEvent event) { - test(event.getVehicle()); - } - - @EventHandler - public void onVehicle(VehicleBlockCollisionEvent event) { - test(event.getVehicle()); - } - - @EventHandler - public void onTeleport(EntityTeleportEvent event) { - Entity ent = event.getEntity(); - if (ent instanceof Vehicle || ent instanceof ArmorStand) test(event.getEntity()); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void vehicleMove(VehicleMoveEvent event) throws IllegalAccessException { - test(event.getVehicle()); - } - - @EventHandler - public void spawn(CreatureSpawnEvent event) { - switch (event.getEntityType()) { - case ARMOR_STAND: - test(event.getEntity()); - } - } - - private static boolean ignoreTP = false; - - public static void test(Entity entity) { - List meta = entity.getMetadata("plotworld"); - World world = entity.getLocation().getWorld(); - if (meta == null || meta.isEmpty()) { - if (PS.get().isPlotWorld(world.getName())) { - entity.setMetadata("plotworld", new FixedMetadataValue((Plugin) PS.get().IMP, entity.getLocation())); - } - } else { - Location origin = (Location) meta.get(0).value(); - World originWorld = origin.getWorld(); - if (!originWorld.equals(world)) { - if (!ignoreTP) { - if (!world.getName().equalsIgnoreCase(originWorld + "_the_end")) { - try { - ignoreTP = true; - entity.teleport(origin); - } finally { - ignoreTP = false; - } - if (entity.getLocation().getWorld().equals(world)) { - entity.remove(); - } - } - } else { - entity.remove(); - } - } - } - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/EntitySpawnListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/EntitySpawnListener.java deleted file mode 100644 index 32bebe45b..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/EntitySpawnListener.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.plotsquared.bukkit.listeners; - -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.plotsquared.bukkit.util.BukkitUtil; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntitySpawnEvent; -import org.bukkit.metadata.FixedMetadataValue; -import org.bukkit.plugin.Plugin; - -public class EntitySpawnListener implements Listener { - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void creatureSpawnEvent(EntitySpawnEvent event) { - Entity entity = event.getEntity(); - Location location = BukkitUtil.getLocation(entity.getLocation()); - PlotArea area = location.getPlotArea(); - if (area == null) { - return; - } - Plot plot = area.getOwnedPlotAbs(location); - if (plot == null) { - if (!area.MOB_SPAWNING) { - EntityType type = entity.getType(); - switch (type) { - case DROPPED_ITEM: - if (Settings.Enabled_Components.KILL_ROAD_ITEMS) { - break; - } - case PLAYER: - return; - } - if (type.isAlive() || !area.MISC_SPAWN_UNOWNED) { - event.setCancelled(true); - } - } - return; - } - if (Settings.Done.RESTRICT_BUILDING && plot.hasFlag(Flags.DONE)) { - event.setCancelled(true); - } - switch (entity.getType()) { - case ENDER_CRYSTAL: - if (PlayerEvents.checkEntity(entity, plot)) { - event.setCancelled(true); - } - case SHULKER: - if(!entity.hasMetadata("plot")) { - entity.setMetadata("plot", new FixedMetadataValue((Plugin) PS.get().IMP, plot.getId())); - } - } - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents183.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents183.java deleted file mode 100644 index f58cee225..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents183.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.plotsquared.bukkit.listeners; - -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.plotsquared.bukkit.util.BukkitUtil; -import org.bukkit.block.Block; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockExplodeEvent; - -import java.util.Iterator; - -public class PlayerEvents183 implements Listener { - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBigBoom(BlockExplodeEvent event) { - Block block = event.getBlock(); - Location location = BukkitUtil.getLocation(block.getLocation()); - String world = location.getWorld(); - if (!PS.get().hasPlotArea(world)) { - return; - } - PlotArea area = location.getPlotArea(); - if (area == null) { - Iterator iterator = event.blockList().iterator(); - while (iterator.hasNext()) { - location = BukkitUtil.getLocation(iterator.next().getLocation()); - if (location.getPlotArea() != null) { - iterator.remove(); - } - } - return; - } - Plot plot = area.getOwnedPlot(location); - if (plot == null || !plot.getFlag(Flags.EXPLOSION).or(false)) { - event.setCancelled(true); - } - Iterator iterator = event.blockList().iterator(); - while (iterator.hasNext()) { - Block b = iterator.next(); - if (!plot.equals(area.getOwnedPlot(BukkitUtil.getLocation(b.getLocation())))) { - iterator.remove(); - } - } - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8.java deleted file mode 100644 index ffc23d1e1..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_8.java +++ /dev/null @@ -1,175 +0,0 @@ -package com.plotsquared.bukkit.listeners; - -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.plotsquared.bukkit.util.BukkitUtil; -import com.plotsquared.listener.PlotListener; -import java.util.HashSet; -import java.util.List; -import java.util.UUID; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Entity; -import org.bukkit.entity.HumanEntity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryAction; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.player.PlayerInteractAtEntityEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.PlayerInventory; -import org.bukkit.inventory.meta.ItemMeta; - -public class PlayerEvents_1_8 extends PlotListener implements Listener { - - @SuppressWarnings("deprecation") - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onInventoryClick(InventoryClickEvent event) { - if (!event.isLeftClick() || (event.getAction() != InventoryAction.PLACE_ALL) || event.isShiftClick()) { - return; - } - HumanEntity entity = event.getWhoClicked(); - if (!(entity instanceof Player) || !PS.get().hasPlotArea(entity.getWorld().getName())) { - return; - } - Player player = (Player) entity; - PlayerInventory inv = player.getInventory(); - int slot = inv.getHeldItemSlot(); - if ((slot > 8) || !event.getEventName().equals("InventoryCreativeEvent")) { - return; - } - ItemStack current = inv.getItemInHand(); - ItemStack newItem = event.getCursor(); - ItemMeta newMeta = newItem.getItemMeta(); - ItemMeta oldMeta = newItem.getItemMeta(); - String newLore = ""; - if (newMeta != null) { - List lore = newMeta.getLore(); - if (lore != null) { - newLore = lore.toString(); - } - } - String oldLore = ""; - if (oldMeta != null) { - List lore = oldMeta.getLore(); - if (lore != null) { - oldLore = lore.toString(); - } - } - if (!"[(+NBT)]".equals(newLore) || (current.equals(newItem) && newLore.equals(oldLore))) { - switch (newItem.getType()) { - case BANNER: - case SKULL_ITEM: - if (newMeta != null) break; - default: - return; - } - } - - HashSet blocks = null; - Block block = player.getTargetBlock(blocks, 7); - BlockState state = block.getState(); - if (state == null) { - return; - } - Material stateType = state.getType(); - Material itemType = newItem.getType(); - if (stateType != itemType) { - switch (stateType) { - case STANDING_BANNER: - case WALL_BANNER: - if (itemType == Material.BANNER) break; - case SKULL: - if (itemType == Material.SKULL_ITEM) break; - default: - return; - } - } - Location l = BukkitUtil.getLocation(state.getLocation()); - PlotArea area = l.getPlotArea(); - if (area == null) { - return; - } - Plot plot = area.getPlotAbs(l); - PlotPlayer pp = BukkitUtil.getPlayer(player); - boolean cancelled = false; - if (plot == null) { - 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")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.unowned"); - cancelled = true; - } - } else { - UUID uuid = pp.getUUID(); - 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.getType() == newItem.getType()) && (current.getDurability() == newItem.getDurability())) { - event.setCursor(new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability())); - event.setCancelled(true); - return; - } - event.setCursor(new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability())); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onInteract(PlayerInteractAtEntityEvent e) { - Entity entity = e.getRightClicked(); - if (!(entity instanceof ArmorStand)) { - return; - } - Location l = BukkitUtil.getLocation(e.getRightClicked().getLocation()); - PlotArea area = l.getPlotArea(); - if (area == null) { - return; - } - - EntityPortal_1_7_9.test(entity); - - Plot plot = area.getPlotAbs(l); - PlotPlayer pp = BukkitUtil.getPlayer(e.getPlayer()); - if (plot == null) { - 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")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.unowned"); - e.setCancelled(true); - } - } else { - UUID uuid = pp.getUUID(); - if (!plot.isAdded(uuid)) { - if (Flags.MISC_INTERACT.isTrue(plot)) { - return; - } - if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.other"); - e.setCancelled(true); - } - } - } - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_9.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_9.java deleted file mode 100644 index 6a9b3abb0..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents_1_9.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.plotsquared.bukkit.listeners; - -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.object.Location; -import com.plotsquared.bukkit.util.BukkitUtil; -import org.bukkit.entity.LingeringPotion; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.LingeringPotionSplashEvent; - -public class PlayerEvents_1_9 implements Listener { - - private final PlayerEvents parent; - - public PlayerEvents_1_9(PlayerEvents parent) { - this.parent = parent; - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPotionSplash(LingeringPotionSplashEvent event) { - LingeringPotion entity = event.getEntity(); - Location l = BukkitUtil.getLocation(entity); - if (!PS.get().hasPlotArea(l.getWorld())) { - return; - } - if (!parent.onProjectileHit(event)) { - event.setCancelled(true); - } - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener_1_12.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener_1_12.java deleted file mode 100644 index 12cc6ab7e..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener_1_12.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.plotsquared.bukkit.listeners; - -import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.plotsquared.bukkit.util.BukkitUtil; -import java.util.UUID; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityPickupItemEvent; - -public class PlotPlusListener_1_12 implements Listener { - @EventHandler - public void onItemPickup(EntityPickupItemEvent event) { - LivingEntity ent = event.getEntity(); - if (ent instanceof Player) { - Player player = (Player) ent; - PlotPlayer pp = BukkitUtil.getPlayer(player); - Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); - if (plot == null) { - return; - } - UUID uuid = pp.getUUID(); - if (!plot.isAdded(uuid) && Flags.DROP_PROTECTION.isTrue(plot)) { - event.setCancelled(true); - } - } - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener_Legacy.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener_Legacy.java deleted file mode 100644 index ce0c57f4e..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlotPlusListener_Legacy.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.plotsquared.bukkit.listeners; - -import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.plotsquared.bukkit.util.BukkitUtil; -import java.util.UUID; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerPickupItemEvent; - -public class PlotPlusListener_Legacy implements Listener { - @EventHandler - public void onItemPickup(PlayerPickupItemEvent event) { - Player player = event.getPlayer(); - PlotPlayer pp = BukkitUtil.getPlayer(player); - Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); - if (plot == null) { - return; - } - UUID uuid = pp.getUUID(); - if (!plot.isAdded(uuid) && Flags.DROP_PROTECTION.isTrue(plot)) { - event.setCancelled(true); - } - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitLazyBlock.java b/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitLazyBlock.java deleted file mode 100644 index 7a26d21a5..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/object/BukkitLazyBlock.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.plotsquared.bukkit.object; - -import com.intellectualcrafters.plot.object.LazyBlock; -import com.intellectualcrafters.plot.object.PlotBlock; -import org.bukkit.block.Block; - -public class BukkitLazyBlock extends LazyBlock { - - private int id; - private Block block; - private PlotBlock pb; - - public BukkitLazyBlock(int id, Block block) { - this.id = id; - this.block = block; - } - - public BukkitLazyBlock(PlotBlock pb) { - this.id = pb.id; - this.pb = pb; - } - - public BukkitLazyBlock(Block block) { - this.block = block; - } - - @Override - public PlotBlock getPlotBlock() { - if (this.pb != null) { - return this.pb; - } - if (this.id == 0) { - this.id = this.block.getTypeId(); - } - byte data; - switch (this.id) { - case 0: - case 2: - case 4: - case 13: - case 14: - case 15: - case 20: - case 21: - case 22: - case 24: - case 25: - case 30: - case 32: - case 37: - case 39: - case 40: - case 41: - case 42: - case 45: - case 46: - case 47: - case 48: - case 49: - case 51: - case 52: - case 54: - case 55: - case 56: - case 57: - case 58: - case 60: - case 61: - case 62: - case 7: - case 8: - case 9: - case 10: - case 11: - case 73: - case 74: - case 78: - case 79: - case 80: - case 81: - case 82: - case 83: - case 84: - case 85: - case 87: - case 88: - case 101: - case 102: - case 103: - case 110: - case 112: - case 113: - case 117: - case 121: - case 122: - case 123: - case 124: - case 129: - case 133: - case 138: - case 137: - case 140: - case 165: - case 166: - case 169: - case 170: - case 172: - case 173: - case 174: - case 176: - case 177: - case 181: - case 182: - case 188: - case 189: - case 190: - case 191: - case 192: - data = 0; - break; - default: - data = this.block.getData(); - break; - } - this.pb = PlotBlock.get((short) this.id, data); - return this.pb; - - } - - @Override - public int getId() { - if (this.id == 0) { - this.id = this.block.getTypeId(); - } - return this.id; - } - -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager_183.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager_183.java deleted file mode 100644 index 559e296fd..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitleManager_183.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.plotsquared.bukkit.titles; - -import com.plotsquared.bukkit.chat.Reflection; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -import java.lang.reflect.Method; - -public class DefaultTitleManager_183 extends DefaultTitleManager { - - /** - * Create a new 1.8 title. - * - * @param title Title text - * @param subtitle Subtitle text - * @param fadeInTime Fade in time - * @param stayTime Stay on screen time - * @param fadeOutTime Fade out time - */ - DefaultTitleManager_183(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) { - super(title, subtitle, fadeInTime, stayTime, fadeOutTime); - } - - /** - * Load spigot and NMS classes. - */ - @Override - void loadClasses() { - this.packetTitle = Reflection.getNMSClass("PacketPlayOutTitle"); - this.chatBaseComponent = Reflection.getNMSClass("IChatBaseComponent"); - this.packetActions = Reflection.getNMSClass("PacketPlayOutTitle$EnumTitleAction"); - this.nmsChatSerializer = Reflection.getNMSClass("IChatBaseComponent$ChatSerializer"); - } - - @Override - public void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException { - if (this.packetTitle != null) { - // First reset previous settings - resetTitle(player); - // Send timings first - Object handle = getHandle(player); - Object connection = getField(handle.getClass(), "playerConnection").get(handle); - Object[] actions = this.packetActions.getEnumConstants(); - Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = this.packetTitle - .getConstructor(this.packetActions, this.chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE) - .newInstance(actions[2], null, - this.fadeInTime * (this.ticks ? 1 : 20), - this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime * (this.ticks ? 1 : 20)); - // Send if set - if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) { - sendPacket.invoke(connection, packet); - } - // Send title - Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, - "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + "\",color:" + this.titleColor.name().toLowerCase() - + "}"); - packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[0], serialized); - sendPacket.invoke(connection, packet); - if (!this.getSubtitle().isEmpty()) { - // Send subtitle if present - serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, - "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + "\",color:" + this.subtitleColor.name() - .toLowerCase() + "}"); - packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[1], serialized); - sendPacket.invoke(connection, packet); - } - } - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_111.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_111.java deleted file mode 100644 index be6cfc568..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_111.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.plotsquared.bukkit.titles; - -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.AbstractTitle; -import com.plotsquared.bukkit.object.BukkitPlayer; -import com.plotsquared.bukkit.util.BukkitVersion; -import org.bukkit.entity.Player; - -@SuppressWarnings("deprecation") -public class DefaultTitle_111 extends AbstractTitle { - - private final boolean valid; - - public DefaultTitle_111() { - this.valid = PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_11_0); - } - - @Override - public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) { - if (valid) { - try { - final Player playerObj = ((BukkitPlayer) player).player; - TitleManager_1_11 title = new TitleManager_1_11(head, sub, in, delay, out); - title.send(playerObj); - return; - } catch (Throwable ignored) {} - } - AbstractTitle.TITLE_CLASS = new DefaultTitle_180(); - AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out); - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_180.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_180.java deleted file mode 100644 index 5f7836b13..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_180.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.plotsquared.bukkit.titles; - -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.AbstractTitle; -import com.plotsquared.bukkit.object.BukkitPlayer; - -public class DefaultTitle_180 extends AbstractTitle { - - @Override - public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) { - try { - DefaultTitleManager title = new DefaultTitleManager(head, sub, in, delay, out); - title.send(((BukkitPlayer) player).player); - } catch (Exception ignored) { - AbstractTitle.TITLE_CLASS = new DefaultTitle_19(); - AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out); - } - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_183.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_183.java deleted file mode 100644 index 46a81a306..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_183.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.plotsquared.bukkit.titles; - -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.AbstractTitle; -import com.plotsquared.bukkit.object.BukkitPlayer; - -public class DefaultTitle_183 extends AbstractTitle { - - @Override - public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) { - try { - DefaultTitleManager_183 title = new DefaultTitleManager_183(head, sub, in, delay, out); - title.send(((BukkitPlayer) player).player); - } catch (Exception ignored) { - AbstractTitle.TITLE_CLASS = new HackTitle(); - AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out); - } - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_19.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_19.java deleted file mode 100644 index f6f90c2f2..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/DefaultTitle_19.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.plotsquared.bukkit.titles; - -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.AbstractTitle; -import com.intellectualcrafters.plot.util.TaskManager; -import com.plotsquared.bukkit.object.BukkitPlayer; -import org.bukkit.entity.Player; - -@SuppressWarnings("deprecation") -public class DefaultTitle_19 extends AbstractTitle { - - @Override - public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) { - try { - final Player playerObj = ((BukkitPlayer) player).player; - playerObj.sendTitle(head, sub); - TaskManager.runTaskLater(new Runnable() { - @Override - public void run() { - playerObj.sendTitle("", ""); - } - }, delay * 20); - } catch (Throwable ignored) { - AbstractTitle.TITLE_CLASS = new DefaultTitle_183(); - AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out); - } - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/HackTitle.java b/Bukkit/src/main/java/com/plotsquared/bukkit/titles/HackTitle.java deleted file mode 100644 index 508dc03fd..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/titles/HackTitle.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.plotsquared.bukkit.titles; - -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.AbstractTitle; -import com.plotsquared.bukkit.object.BukkitPlayer; - -public class HackTitle extends AbstractTitle { - - @Override - public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) { - try { - HackTitleManager title = new HackTitleManager(head, sub, in, delay, out); - title.send(((BukkitPlayer) player).player); - } catch (Exception ignored) { - PS.debug("&cYour server version does not support titles!"); - Settings.TITLES = false; - AbstractTitle.TITLE_CLASS = null; - } - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java deleted file mode 100644 index 3e7c226f5..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitChatManager.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.plotsquared.bukkit.util; - -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.object.ConsolePlayer; -import com.intellectualcrafters.plot.object.PlotMessage; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.ChatManager; -import com.plotsquared.bukkit.chat.FancyMessage; -import com.plotsquared.bukkit.object.BukkitPlayer; -import org.bukkit.ChatColor; - -import java.util.ArrayList; -import java.util.List; - -public class BukkitChatManager extends ChatManager { - - @Override - public FancyMessage builder() { - return new FancyMessage(""); - } - - @Override - public void color(PlotMessage message, String color) { - message.$(this).color(ChatColor.getByChar(C.color(color).substring(1))); - } - - @Override - public void tooltip(PlotMessage message, PlotMessage... tooltips) { - List lines = new ArrayList<>(); - for (PlotMessage tooltip : tooltips) { - lines.add(tooltip.$(this)); - } - message.$(this).formattedTooltip(lines); - } - - @Override - public void command(PlotMessage message, String command) { - message.$(this).command(command); - } - - @Override - public void text(PlotMessage message, String text) { - message.$(this).then(ChatColor.stripColor(text)); - } - - @Override - public void send(PlotMessage plotMessage, PlotPlayer player) { - if (player instanceof ConsolePlayer || !Settings.Chat.INTERACTIVE) { - player.sendMessage(plotMessage.$(this).toOldMessageFormat()); - } else { - plotMessage.$(this).send(((BukkitPlayer) player).player); - } - } - - @Override - public void suggest(PlotMessage plotMessage, String command) { - plotMessage.$(this).suggest(command); - } - -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java deleted file mode 100644 index df957892e..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSchematicHandler.java +++ /dev/null @@ -1,310 +0,0 @@ -package com.plotsquared.bukkit.util; - -import com.intellectualcrafters.jnbt.ByteArrayTag; -import com.intellectualcrafters.jnbt.CompoundTag; -import com.intellectualcrafters.jnbt.IntTag; -import com.intellectualcrafters.jnbt.ListTag; -import com.intellectualcrafters.jnbt.ShortTag; -import com.intellectualcrafters.jnbt.StringTag; -import com.intellectualcrafters.jnbt.Tag; -import com.intellectualcrafters.plot.object.ChunkLoc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.RegionWrapper; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.block.LocalBlockQueue; -import com.plotsquared.bukkit.object.schematic.StateWrapper; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; - -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Schematic Handler. - */ -public class BukkitSchematicHandler extends SchematicHandler { - - @Override - public void getCompoundTag(final String world, final Set regions, final RunnableVal whenDone) { - // async - TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { - // Main positions - Location[] corners = MainUtil.getCorners(world, regions); - final Location bot = corners[0]; - Location top = corners[1]; - - final int width = top.getX() - bot.getX() + 1; - int height = top.getY() - bot.getY() + 1; - final int length = top.getZ() - bot.getZ() + 1; - // Main Schematic tag - final HashMap schematic = new HashMap<>(); - schematic.put("Width", new ShortTag("Width", (short) width)); - schematic.put("Length", new ShortTag("Length", (short) length)); - schematic.put("Height", new ShortTag("Height", (short) height)); - schematic.put("Materials", new StringTag("Materials", "Alpha")); - schematic.put("WEOriginX", new IntTag("WEOriginX", 0)); - schematic.put("WEOriginY", new IntTag("WEOriginY", 0)); - schematic.put("WEOriginZ", new IntTag("WEOriginZ", 0)); - schematic.put("WEOffsetX", new IntTag("WEOffsetX", 0)); - schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0)); - schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0)); - // Arrays of data types - final List tileEntities = new ArrayList<>(); - final byte[] blocks = new byte[width * height * length]; - final byte[] blockData = new byte[width * height * length]; - // Queue - final ArrayDeque queue = new ArrayDeque<>(regions); - TaskManager.runTask(new Runnable() { - @Override - public void run() { - if (queue.isEmpty()) { - TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { - schematic.put("Blocks", new ByteArrayTag("Blocks", blocks)); - schematic.put("Data", new ByteArrayTag("Data", blockData)); - schematic.put("Entities", new ListTag("Entities", CompoundTag.class, new ArrayList())); - schematic.put("TileEntities", new ListTag("TileEntities", CompoundTag.class, tileEntities)); - whenDone.value = new CompoundTag("Schematic", schematic); - TaskManager.runTask(whenDone); - System.gc(); - System.gc(); - } - }); - return; - } - final Runnable regionTask = this; - RegionWrapper region = queue.poll(); - Location pos1 = new Location(world, region.minX, region.minY, region.minZ); - Location pos2 = new Location(world, region.maxX, region.maxY, region.maxZ); - final int bx = bot.getX(); - final int bz = bot.getZ(); - final int p1x = pos1.getX(); - final int p1z = pos1.getZ(); - final int p2x = pos2.getX(); - final int p2z = pos2.getZ(); - final int bcx = p1x >> 4; - final int bcz = p1z >> 4; - final int tcx = p2x >> 4; - final int tcz = p2z >> 4; - final int sy = pos1.getY(); - final int ey = pos2.getY(); - // Generate list of chunks - final ArrayList chunks = new ArrayList<>(); - for (int x = bcx; x <= tcx; x++) { - for (int z = bcz; z <= tcz; z++) { - chunks.add(new ChunkLoc(x, z)); - } - } - final World worldObj = Bukkit.getWorld(world); - // Main thread - TaskManager.runTask(new Runnable() { - @Override - public void run() { - long start = System.currentTimeMillis(); - while (!chunks.isEmpty() && System.currentTimeMillis() - start < 20) { - // save schematics - ChunkLoc chunk = chunks.remove(0); - Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z); - if (!bc.load(false)) { - continue; - } - int X = chunk.x; - int Z = chunk.z; - int xxb = X << 4; - int zzb = Z << 4; - int xxt = xxb + 15; - int zzt = zzb + 15; - - if (X == bcx) { - xxb = p1x; - } - if (X == tcx) { - xxt = p2x; - } - if (Z == bcz) { - zzb = p1z; - } - if (Z == tcz) { - zzt = p2z; - } - for (int y = sy; y <= Math.min(255, ey); y++) { - int ry = y - sy; - int i1 = ry * width * length; - for (int z = zzb; z <= zzt; z++) { - int rz = z - bz; - int i2 = i1 + rz * width; - for (int x = xxb; x <= xxt; x++) { - int rx = x - bx; - int index = i2 + rx; - Block block = worldObj.getBlockAt(x, y, z); - int id = block.getTypeId(); - switch (id) { - case 0: - case 2: - case 4: - case 13: - case 14: - case 15: - case 20: - case 21: - case 22: - case 24: - case 30: - case 32: - case 37: - case 39: - case 40: - case 41: - case 42: - case 45: - case 46: - case 47: - case 48: - case 49: - case 51: - case 55: - case 56: - case 57: - case 58: - case 60: - case 7: - case 8: - case 9: - case 10: - case 11: - case 73: - case 74: - case 78: - case 79: - case 80: - case 81: - case 82: - case 83: - case 85: - case 87: - case 88: - case 101: - case 102: - case 103: - case 110: - case 112: - case 113: - case 121: - case 122: - case 129: - case 133: - case 165: - case 166: - case 169: - case 170: - case 172: - case 173: - case 174: - case 181: - case 182: - case 188: - case 189: - case 190: - case 191: - case 192: - break; - case 54: - case 130: - case 142: - case 27: - case 137: - case 52: - case 154: - case 84: - case 25: - case 144: - case 138: - case 176: - case 177: - case 63: - case 68: - case 323: - case 117: - case 116: - case 28: - case 66: - case 157: - case 61: - case 62: - case 140: - case 146: - case 149: - case 150: - case 158: - case 23: - case 123: - case 124: - case 29: - case 33: - case 151: - case 178: - // TODO implement fully - BlockState state = block.getState(); - if (state != null) { - StateWrapper wrapper = new StateWrapper(state); - CompoundTag rawTag = wrapper.getTag(); - if (rawTag != null) { - Map values = new HashMap<>(rawTag.getValue()); - values.put("id", new StringTag("id", wrapper.getId())); - values.put("x", new IntTag("x", x)); - values.put("y", new IntTag("y", y)); - values.put("z", new IntTag("z", z)); - CompoundTag tileEntityTag = new CompoundTag(values); - tileEntities.add(tileEntityTag); - } - } - default: - blockData[index] = block.getData(); - } - // For optimization reasons, we are not supporting custom data types - // Especially since the most likely reason beyond this range is modded servers in which the blocks - // have NBT - // if (type > 255) { - // if (addBlocks == null) { - // addBlocks = new byte[(blocks.length >> 1) + 1]; - // } - // addBlocks[index >> 1] = (byte) (((index & 1) == 0) ? - // (addBlocks[index >> 1] & 0xF0) | ((type >> 8) & 0xF) : (addBlocks[index >> 1] & 0xF) | (((type - // >> 8) & 0xF) << 4)); - // } - blocks[index] = (byte) id; - } - } - } - } - if (!chunks.isEmpty()) { - TaskManager.runTaskLater(this, 1); - } else { - regionTask.run(); - } - } - }); - } - }); - } - }); - } - - @Override - public boolean restoreTile(LocalBlockQueue queue, CompoundTag ct, int x, int y, int z) { - return new StateWrapper(ct).restoreTag(queue.getWorld(), x, y, z); - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java deleted file mode 100644 index 7a6c89ded..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitTaskManager.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.plotsquared.bukkit.util; - -import com.intellectualcrafters.plot.util.TaskManager; -import com.plotsquared.bukkit.BukkitMain; -import org.bukkit.Bukkit; - -public class BukkitTaskManager extends TaskManager { - - private final BukkitMain bukkitMain; - - public BukkitTaskManager(BukkitMain bukkitMain) { - this.bukkitMain = bukkitMain; - } - - @Override - public int taskRepeat(Runnable runnable, int interval) { - return this.bukkitMain.getServer().getScheduler().scheduleSyncRepeatingTask(this.bukkitMain, runnable, interval, interval); - } - - @SuppressWarnings("deprecation") - @Override - public int taskRepeatAsync(Runnable runnable, int interval) { - return this.bukkitMain.getServer().getScheduler().scheduleAsyncRepeatingTask(this.bukkitMain, runnable, interval, interval); - } - - @Override - public void taskAsync(Runnable runnable) { - this.bukkitMain.getServer().getScheduler().runTaskAsynchronously(this.bukkitMain, runnable).getTaskId(); - } - - @Override - public void task(Runnable runnable) { - this.bukkitMain.getServer().getScheduler().runTask(this.bukkitMain, runnable).getTaskId(); - } - - @Override - public void taskLater(Runnable runnable, int delay) { - this.bukkitMain.getServer().getScheduler().runTaskLater(this.bukkitMain, runnable, delay).getTaskId(); - } - - @Override - public void taskLaterAsync(Runnable runnable, int delay) { - this.bukkitMain.getServer().getScheduler().runTaskLaterAsynchronously(this.bukkitMain, runnable, delay); - } - - @Override - public void cancelTask(int task) { - if (task != -1) { - Bukkit.getScheduler().cancelTask(task); - } - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java deleted file mode 100644 index 83511ac0a..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java +++ /dev/null @@ -1,342 +0,0 @@ -package com.plotsquared.bukkit.util; - -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.PlotBlock; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RegionWrapper; -import com.intellectualcrafters.plot.object.schematic.PlotItem; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.StringComparison; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.WorldUtil; -import com.plotsquared.bukkit.object.BukkitPlayer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.OfflinePlayer; -import org.bukkit.World; -import org.bukkit.block.Biome; -import org.bukkit.block.Block; -import org.bukkit.block.BlockState; -import org.bukkit.block.Sign; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.ItemStack; -import org.bukkit.material.MaterialData; -import org.bukkit.material.Sandstone; -import org.bukkit.material.Step; -import org.bukkit.material.Tree; -import org.bukkit.material.WoodenStep; -import org.bukkit.material.Wool; - -public class BukkitUtil extends WorldUtil { - - private static String lastString = null; - private static World lastWorld = null; - - private static Player lastPlayer = null; - private static PlotPlayer lastPlotPlayer = null; - - public static void removePlayer(String player) { - lastPlayer = null; - lastPlotPlayer = null; - } - - public static PlotPlayer getPlayer(OfflinePlayer op) { - if (op.isOnline()) { - return getPlayer(op.getPlayer()); - } - Player player = OfflinePlayerUtil.loadPlayer(op); - player.loadData(); - return new BukkitPlayer(player, true); - } - - public static PlotPlayer getPlayer(Player player) { - if (player == lastPlayer) { - return lastPlotPlayer; - } - String name = player.getName(); - PlotPlayer plotPlayer = UUIDHandler.getPlayer(name); - if (plotPlayer != null) { - return plotPlayer; - } - lastPlotPlayer = new BukkitPlayer(player); - UUIDHandler.getPlayers().put(name, lastPlotPlayer); - lastPlayer = player; - return lastPlotPlayer; - } - - public static Location getLocation(org.bukkit.Location location) { - return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), - MathMan.roundInt(location.getZ())); - } - - public static org.bukkit.Location getLocation(Location location) { - return new org.bukkit.Location(getWorld(location.getWorld()), location.getX(), location.getY(), location.getZ()); - } - - public static World getWorld(String string) { - return Bukkit.getWorld(string); - } - - public static String getWorld(Entity entity) { - return entity.getWorld().getName(); - } - - public static List getEntities(String worldName) { - World world = getWorld(worldName); - return world != null ? world.getEntities() : new ArrayList(); - } - - public static Location getLocation(Entity entity) { - org.bukkit.Location location = entity.getLocation(); - String world = location.getWorld().getName(); - return new Location(world, location.getBlockX(), location.getBlockY(), location.getBlockZ()); - } - - public static Location getLocationFull(Entity entity) { - org.bukkit.Location location = entity.getLocation(); - return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()), - location.getYaw(), location.getPitch()); - } - - @Override - public boolean isWorld(String worldName) { - return getWorld(worldName) != null; - } - - @Override - public String getBiome(String world, int x, int z) { - return getWorld(world).getBiome(x, z).name(); - } - - @Override - public void setSign(String worldName, int x, int y, int z, String[] lines) { - World world = getWorld(worldName); - Block block = world.getBlockAt(x, y, z); - // block.setType(Material.AIR); - Material type = block.getType(); - if (type != Material.SIGN && type != Material.SIGN_POST) { - int data = 2; - if (world.getBlockAt(x, y, z + 1).getType().isSolid()) data = 2; - else if (world.getBlockAt(x + 1, y, z).getType().isSolid()) data = 4; - else if (world.getBlockAt(x, y, z - 1).getType().isSolid()) data = 3; - else if (world.getBlockAt(x - 1, y, z).getType().isSolid()) data = 5; - block.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) data, false); - } - BlockState blockstate = block.getState(); - if (blockstate instanceof Sign) { - final Sign sign = (Sign) blockstate; - for (int i = 0; i < lines.length; i++) { - sign.setLine(i, lines[i]); - } - sign.update(true); - } - } - - @Override - public String[] getSign(Location location) { - Block block = getWorld(location.getWorld()).getBlockAt(location.getX(), location.getY(), location.getZ()); - if (block != null) { - if (block.getState() instanceof Sign) { - Sign sign = (Sign) block.getState(); - return sign.getLines(); - } - } - return null; - } - - @Override - public Location getSpawn(PlotPlayer player) { - return getLocation(((BukkitPlayer) player).player.getBedSpawnLocation()); - } - - @Override - public Location getSpawn(String world) { - org.bukkit.Location temp = getWorld(world).getSpawnLocation(); - return new Location(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), temp.getPitch()); - } - - @Override - public void setSpawn(Location location) { - World world = getWorld(location.getWorld()); - if (world != null) { - world.setSpawnLocation(location.getX(), location.getY(), location.getZ()); - } - } - - @Override - public void saveWorld(String worldName) { - World world = getWorld(worldName); - if (world != null) { - world.save(); - } - } - - @Override - public int getHighestBlock(String world, int x, int z) { - World bukkitWorld = getWorld(world); - // Skip top and bottom block - int air = 1; - for (int y = bukkitWorld.getMaxHeight() - 1; y >= 0; y--) { - Block block = bukkitWorld.getBlockAt(x, y, z); - if (block != null) { - Material type = block.getType(); - if (type.isSolid()) { - if (air > 1) return y; - air = 0; - } else { - switch (type) { - case WATER: - case LAVA: - case STATIONARY_LAVA: - case STATIONARY_WATER: - return y; - } - air++; - } - } - } - return bukkitWorld.getMaxHeight() - 1; - } - - @Override - public int getBiomeFromString(String biomeString) { - try { - Biome biome = Biome.valueOf(biomeString.toUpperCase()); - return Arrays.asList(Biome.values()).indexOf(biome); - } catch (IllegalArgumentException ignored) { - return -1; - } - } - - @Override - public String[] getBiomeList() { - Biome[] biomes = Biome.values(); - String[] list = new String[biomes.length]; - for (int i = 0; i < biomes.length; i++) { - list[i] = biomes[i].name(); - } - return list; - } - - @Override - public boolean addItems(String worldName, PlotItem items) { - World world = getWorld(worldName); - Block block = world.getBlockAt(items.x, items.y, items.z); - if (block == null) { - return false; - } - BlockState state = block.getState(); - if (state instanceof InventoryHolder) { - InventoryHolder holder = (InventoryHolder) state; - Inventory inv = holder.getInventory(); - for (int i = 0; i < items.id.length; i++) { - ItemStack item = new ItemStack(items.id[i], items.amount[i], items.data[i]); - inv.addItem(item); - } - state.update(true); - return true; - } - return false; - } - - @Override - public boolean isBlockSolid(PlotBlock block) { - try { - Material material = Material.getMaterial(block.id); - if (material.isBlock() && material.isSolid() && !material.hasGravity()) { - Class 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) { - case NOTE_BLOCK: - case MOB_SPAWNER: - return false; - default: - return true; - } - } - } - return false; - } catch (Exception ignored) { - return false; - } - } - - @Override - public String getClosestMatchingName(PlotBlock block) { - try { - return Material.getMaterial(block.id).name(); - } catch (Exception ignored) { - return null; - } - } - - @Override - public StringComparison.ComparisonResult getClosestBlock(String name) { - try { - Material material = Material.valueOf(name.toUpperCase()); - return new StringComparison().new ComparisonResult(0, PlotBlock.get((short) material.getId(), (byte) 0)); - } catch (IllegalArgumentException ignored) {} - try { - byte data; - String[] split = name.split(":"); - if (split.length == 2) { - data = Byte.parseByte(split[1]); - name = split[0]; - } else { - data = 0; - } - double match; - short id; - if (MathMan.isInteger(split[0])) { - id = Short.parseShort(split[0]); - match = 0; - } else { - StringComparison.ComparisonResult comparison = new StringComparison<>(name, Material.values()).getBestMatchAdvanced(); - match = comparison.match; - id = (short) comparison.best.getId(); - } - PlotBlock block = PlotBlock.get(id, data); - StringComparison outer = new StringComparison<>(); - return outer.new ComparisonResult(match, block); - - } catch (NumberFormatException ignored) {} - return null; - } - - @Override - public void setBiomes(String worldName, RegionWrapper region, String biomeString) { - World world = getWorld(worldName); - Biome biome = Biome.valueOf(biomeString.toUpperCase()); - for (int x = region.minX; x <= region.maxX; x++) { - for (int z = region.minZ; z <= region.maxZ; z++) { - world.setBiome(x, z, biome); - } - } - } - - @Override - public PlotBlock getBlock(Location location) { - World world = getWorld(location.getWorld()); - Block block = world.getBlockAt(location.getX(), location.getY(), location.getZ()); - if (block == null) { - return PlotBlock.EVERYTHING; - } - return PlotBlock.get((short) block.getTypeId(), block.getData()); - } - - @Override - public String getMainWorld() { - return Bukkit.getWorlds().get(0).getName(); - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitVersion.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitVersion.java deleted file mode 100644 index cdf36fff9..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitVersion.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.plotsquared.bukkit.util; - -public class BukkitVersion { - public static int[] v1_13_0 = {1, 13, 0}; - public static int[] v1_12_1 = {1, 12, 1}; - public static int[] v1_12_0 = {1, 12, 0}; - public static int[] v1_11_0 = {1, 11, 0}; - public static int[] v1_10_2 = {1, 10, 2}; - public static int[] v1_10_0 = {1, 10, 0}; - public static int[] v1_9_4 = {1, 9, 4}; - public static int[] v1_9_0 = {1, 9, 0}; - public static int[] v1_8_3 = {1, 8, 3}; - public static int[] v1_8_0 = {1, 8, 0}; - public static int[] v1_7_6 = {1, 7, 6}; - public static int[] v1_7_0 = {1, 7, 0}; - public static int[] v1_6_0 = {1, 6, 0}; -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_7.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_7.java deleted file mode 100644 index c1cb7eae9..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_7.java +++ /dev/null @@ -1,135 +0,0 @@ -package com.plotsquared.bukkit.util.block; - -import com.intellectualcrafters.plot.object.ChunkWrapper; -import com.intellectualcrafters.plot.object.PlotBlock; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.ReflectionUtils; -import com.intellectualcrafters.plot.util.TaskManager; -import com.plotsquared.bukkit.util.SendChunk; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.World; - - -import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; - -public class BukkitLocalQueue_1_7 extends BukkitLocalQueue { - - private final ReflectionUtils.RefClass classBlock = getRefClass("{nms}.Block"); - private final ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk"); - private final ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World"); - private final ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld"); - private final ReflectionUtils.RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); - private final ReflectionUtils.RefMethod methodGetHandle; - private final ReflectionUtils.RefMethod methodGetHandleChunk; - private final ReflectionUtils.RefMethod methodGetChunkAt; - private final ReflectionUtils.RefMethod methodA; - private final ReflectionUtils.RefMethod methodGetById; - private final ReflectionUtils.RefMethod methodInitLighting; - private final SendChunk sendChunk; - - private final HashMap toUpdate = new HashMap<>(); - - public BukkitLocalQueue_1_7(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException { - super(world); - this.methodGetHandle = this.classCraftWorld.getMethod("getHandle"); - this.methodGetChunkAt = this.classWorld.getMethod("getChunkAt", int.class, int.class); - this.methodA = this.classChunk.getMethod("a", int.class, int.class, int.class, this.classBlock, int.class); - this.methodGetById = this.classBlock.getMethod("getById", int.class); - this.methodGetHandleChunk = this.classCraftChunk.getMethod("getHandle"); - this.methodInitLighting = this.classChunk.getMethod("initLighting"); - this.sendChunk = new SendChunk(); - TaskManager.runTaskRepeat(new Runnable() { - @Override - public void run() { - if (BukkitLocalQueue_1_7.this.toUpdate.isEmpty()) { - return; - } - int count = 0; - ArrayList chunks = new ArrayList<>(); - Iterator> i = BukkitLocalQueue_1_7.this.toUpdate.entrySet().iterator(); - while (i.hasNext() && (count < 128)) { - chunks.add(i.next().getValue()); - i.remove(); - count++; - } - if (count == 0) { - return; - } - update(chunks); - } - }, 1); - MainUtil.initCache(); - } - - public void update(Collection chunks) { - if (chunks.isEmpty()) { - return; - } - if (!MainUtil.canSendChunk) { - for (Chunk chunk : chunks) { - chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ()); - chunk.unload(true, false); - chunk.load(); - } - return; - } - try { - this.sendChunk.sendChunk(chunks); - } catch (Throwable e) { - e.printStackTrace(); - MainUtil.canSendChunk = false; - } - } - - @Override - public void fixChunkLighting(int x, int z) { - Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call(); - this.methodInitLighting.of(c).call(); - } - - @Override - public void setBlocks(LocalChunk lc) { - Chunk chunk = getChunk(lc.getX(), lc.getZ()); - chunk.load(true); - World world = chunk.getWorld(); - ChunkWrapper wrapper = new ChunkWrapper(getWorld(), lc.getX(), lc.getZ()); - if (!this.toUpdate.containsKey(wrapper)) { - this.toUpdate.put(wrapper, chunk); - } - Object w = this.methodGetHandle.of(world).call(); - Object c = this.methodGetChunkAt.of(w).call(lc.getX(), lc.getZ()); - for (int i = 0; i < lc.blocks.length; i++) { - PlotBlock[] result2 = lc.blocks[i]; - if (result2 == null) { - continue; - } - for (int j = 0; j < 4096; j++) { - int x = MainUtil.x_loc[i][j]; - int y = MainUtil.y_loc[i][j]; - int z = MainUtil.z_loc[i][j]; - PlotBlock newBlock = result2[j]; - if (newBlock != null) { - if (newBlock.id == -1) { - chunk.getBlock(x, y, z).setData(newBlock.data, false); - continue; - } - Object block = this.methodGetById.call(newBlock.id); - this.methodA.of(c).call(x, y, z, block, newBlock.data); - } - } - } - fixChunkLighting(lc.getX(), lc.getZ()); - } - - @Override - public void refreshChunk(int x, int z) { - update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z))); - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8.java deleted file mode 100644 index 3212742ad..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8.java +++ /dev/null @@ -1,343 +0,0 @@ -package com.plotsquared.bukkit.util.block; - -import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; - -import com.intellectualcrafters.plot.object.ChunkWrapper; -import com.intellectualcrafters.plot.object.PlotBlock; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.ReflectionUtils; -import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass; -import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod; -import com.intellectualcrafters.plot.util.TaskManager; -import com.plotsquared.bukkit.util.SendChunk; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.World; -import org.bukkit.block.Block; - -public class BukkitLocalQueue_1_8 extends BukkitLocalQueue { - - private final ReflectionUtils.RefMethod methodInitLighting; - private final ReflectionUtils.RefClass classBlock = getRefClass("{nms}.Block"); - private final ReflectionUtils.RefClass classBlockPosition = getRefClass("{nms}.BlockPosition"); - private final ReflectionUtils.RefClass classIBlockData = getRefClass("{nms}.IBlockData"); - private final ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk"); - private final ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World"); - private final ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld"); - private final HashMap toUpdate = new HashMap<>(); - private final ReflectionUtils.RefMethod methodGetHandle; - private final ReflectionUtils.RefMethod methodGetChunkAt; - private final ReflectionUtils.RefMethod methodA; - private final ReflectionUtils.RefMethod methodGetByCombinedId; - private final ReflectionUtils.RefConstructor constructorBlockPosition; - private final SendChunk sendChunk; - private final RefMethod methodGetHandleChunk; - - public BukkitLocalQueue_1_8(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException { - super(world); - this.methodInitLighting = this.classChunk.getMethod("initLighting"); - this.constructorBlockPosition = this.classBlockPosition.getConstructor(int.class, int.class, int.class); - this.methodGetByCombinedId = this.classBlock.getMethod("getByCombinedId", int.class); - this.methodGetHandle = this.classCraftWorld.getMethod("getHandle"); - RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); - this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); - this.methodGetChunkAt = this.classWorld.getMethod("getChunkAt", int.class, int.class); - this.methodA = this.classChunk.getMethod("a", this.classBlockPosition, this.classIBlockData); - this.sendChunk = new SendChunk(); - TaskManager.runTaskRepeat(new Runnable() { - @Override - public void run() { - if (BukkitLocalQueue_1_8.this.toUpdate.isEmpty()) { - return; - } - int count = 0; - ArrayList chunks = new ArrayList<>(); - Iterator> i = BukkitLocalQueue_1_8.this.toUpdate.entrySet().iterator(); - while (i.hasNext() && count < 128) { - chunks.add(i.next().getValue()); - i.remove(); - count++; - } - if (count == 0) { - return; - } - update(chunks); - } - }, 1); - MainUtil.initCache(); - } - - @Override - public void fixChunkLighting(int x, int z) { - Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call(); - this.methodInitLighting.of(c).call(); - } - - @Override - public void setBlocks(LocalChunk lc) { - Chunk chunk = getChunk(lc.getX(), lc.getZ()); - chunk.load(true); - World world = chunk.getWorld(); - ChunkWrapper wrapper = new ChunkWrapper(getWorld(), lc.getX(), lc.getZ()); - if (!this.toUpdate.containsKey(wrapper)) { - this.toUpdate.put(wrapper, chunk); - } - Object w = this.methodGetHandle.of(world).call(); - Object c = this.methodGetChunkAt.of(w).call(lc.getX(), lc.getZ()); - for (int i = 0; i < lc.blocks.length; i++) { - PlotBlock[] result2 = lc.blocks[i]; - if (result2 == null) { - continue; - } - for (int j = 0; j < 4096; j++) { - int x = MainUtil.x_loc[i][j]; - int y = MainUtil.y_loc[i][j]; - int z = MainUtil.z_loc[i][j]; - PlotBlock newBlock = result2[j]; - if (newBlock == null) continue; - - if (newBlock.id == -1) { - chunk.getBlock(x, y, z).setData(newBlock.data, false); - continue; - } - // Start blockstate workaround // - switch (newBlock.id) { - case 54: - case 130: - case 142: - case 132: - case 27: - case 137: - case 52: - case 154: - case 84: - case 25: - case 144: - case 138: - case 176: - case 177: - case 119: - case 63: - case 68: - case 323: - case 117: - case 116: - case 28: - case 66: - case 157: - case 61: - case 62: - case 140: - case 146: - case 149: - case 150: - case 158: - case 23: - case 123: - case 124: - case 29: - case 33: - case 151: - case 178: - Block block = world.getBlockAt(x, y, z); - if (block.getData() == newBlock.data) { - if (block.getTypeId() != newBlock.id) { - block.setTypeId(newBlock.id, false); - } - } else { - if (block.getTypeId() == newBlock.id) { - block.setData(newBlock.data, false); - } else { - block.setTypeIdAndData(newBlock.id, newBlock.data, false); - } - } - continue; - } - - // Start data value shortcut - Block block = world.getBlockAt(x, y, z); - int currentId = block.getTypeId(); - if (currentId == newBlock.id) { - switch (newBlock.id) { - case 0: - case 2: - case 4: - case 13: - case 14: - case 15: - case 20: - case 21: - case 22: - case 25: - case 30: - case 32: - case 37: - case 39: - case 40: - case 41: - case 42: - case 45: - case 46: - case 47: - case 48: - case 49: - case 51: - case 52: - case 54: - case 55: - case 56: - case 57: - case 58: - case 60: - case 61: - case 62: - case 7: - case 8: - case 9: - case 10: - case 11: - case 73: - case 74: - case 78: - case 79: - case 80: - case 81: - case 82: - case 83: - case 84: - case 85: - case 87: - case 88: - case 101: - case 102: - case 103: - case 110: - case 112: - case 113: - case 117: - case 121: - case 122: - case 123: - case 124: - case 129: - case 133: - case 138: - case 137: - case 140: - case 165: - case 166: - case 169: - case 170: - case 172: - case 173: - case 174: - case 176: - case 177: - case 181: - case 182: - case 188: - case 189: - case 190: - case 191: - case 192: - continue; - } - if (block.getData() == newBlock.data) { - return; - } - block.setData(newBlock.data, false); - return; - } - // blockstate - switch (currentId) { - case 54: - case 130: - case 132: - case 142: - case 27: - case 137: - case 52: - case 154: - case 84: - case 25: - case 144: - case 138: - case 176: - case 177: - case 63: - case 68: - case 323: - case 117: - case 119: - case 116: - case 28: - case 66: - case 157: - case 61: - case 62: - case 140: - case 146: - case 149: - case 150: - case 158: - case 23: - case 123: - case 124: - case 29: - case 33: - case 151: - case 178: - if (block.getData() == newBlock.data) { - block.setTypeId(newBlock.id, false); - } else { - block.setTypeIdAndData(newBlock.id, newBlock.data, false); - } - continue; - } - // End blockstate workaround // - - // check sign - Object pos = null; - try { - pos = this.constructorBlockPosition.create(x, y, z); - } catch (ReflectiveOperationException e) { - e.printStackTrace(); - } - Object combined = this.methodGetByCombinedId.call(newBlock.id + (newBlock.data << 12)); - this.methodA.of(c).call(pos, combined); - } - } - fixChunkLighting(lc.getX(), lc.getZ()); - } - - public void update(Collection chunks) { - if (chunks.isEmpty()) { - return; - } - if (!MainUtil.canSendChunk) { - for (Chunk chunk : chunks) { - chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ()); - chunk.unload(true, false); - chunk.load(); - } - return; - } - try { - this.sendChunk.sendChunk(chunks); - } catch (Throwable e) { - e.printStackTrace(); - MainUtil.canSendChunk = false; - } - } - - @Override - public void refreshChunk(int x, int z) { - update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z))); - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8_3.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8_3.java deleted file mode 100644 index 90982a1cc..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_8_3.java +++ /dev/null @@ -1,537 +0,0 @@ -package com.plotsquared.bukkit.util.block; - -import com.intellectualcrafters.plot.object.ChunkLoc; -import com.intellectualcrafters.plot.object.ChunkWrapper; -import com.intellectualcrafters.plot.object.PseudoRandom; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.ReflectionUtils; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue; -import com.plotsquared.bukkit.util.SendChunk; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.Material; -import org.bukkit.World; - - -import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; - -public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue { - - private final SendChunk sendChunk; - private final HashMap toUpdate = new HashMap<>(); - private final ReflectionUtils.RefMethod methodGetHandleChunk; - private final ReflectionUtils.RefMethod methodGetHandleWorld; - private final ReflectionUtils.RefMethod methodInitLighting; - private final ReflectionUtils.RefConstructor classBlockPositionConstructor; - private final ReflectionUtils.RefConstructor classChunkSectionConstructor; - private final ReflectionUtils.RefMethod methodX; - private final ReflectionUtils.RefMethod methodAreNeighborsLoaded; - private final ReflectionUtils.RefField fieldSections; - private final ReflectionUtils.RefField fieldWorld; - private final ReflectionUtils.RefMethod methodGetIdArray; - private final ReflectionUtils.RefMethod methodGetWorld; - private final ReflectionUtils.RefField tileEntityListTick; - - public BukkitLocalQueue_1_8_3(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException { - super(world); - ReflectionUtils.RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); - ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld"); - this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); - ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk"); - this.methodInitLighting = classChunk.getMethod("initLighting"); - ReflectionUtils.RefClass classBlockPosition = getRefClass("{nms}.BlockPosition"); - this.classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class); - ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World"); - this.methodX = classWorld.getMethod("x", classBlockPosition.getRealClass()); - this.fieldSections = classChunk.getField("sections"); - this.fieldWorld = classChunk.getField("world"); - ReflectionUtils.RefClass classChunkSection = getRefClass("{nms}.ChunkSection"); - this.methodGetIdArray = classChunkSection.getMethod("getIdArray"); - this.methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class); - this.classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class); - this.tileEntityListTick = classWorld.getField("tileEntityList"); - this.methodGetHandleWorld = classCraftWorld.getMethod("getHandle"); - this.methodGetWorld = classChunk.getMethod("getWorld"); - this.sendChunk = new SendChunk(); - TaskManager.runTaskRepeat(new Runnable() { - @Override - public void run() { - if (BukkitLocalQueue_1_8_3.this.toUpdate.isEmpty()) { - return; - } - int count = 0; - ArrayList chunks = new ArrayList<>(); - Iterator> i = BukkitLocalQueue_1_8_3.this.toUpdate.entrySet().iterator(); - while (i.hasNext() && count < 128) { - chunks.add(i.next().getValue()); - i.remove(); - count++; - } - if (count == 0) { - return; - } - update(chunks); - } - }, 1); - MainUtil.initCache(); - } - - @Override - public LocalChunk getLocalChunk(int x, int z) { - return new CharLocalChunk_1_8_3(this, x, z); - } - - public class CharLocalChunk_1_8_3 extends CharLocalChunk { - public short[] count; - public short[] air; - public short[] relight; - - public CharLocalChunk_1_8_3(BasicLocalBlockQueue parent, int x, int z) { - super(parent, x, z); - this.count = new short[16]; - this.air = new short[16]; - this.relight = new short[16]; - } - - @Override - public void setBlock(int x, int y, int z, int id, int data) { - int i = MainUtil.CACHE_I[y][x][z]; - int j = MainUtil.CACHE_J[y][x][z]; - char[] vs = this.blocks[i]; - if (vs == null) { - vs = this.blocks[i] = new char[4096]; - this.count[i]++; - } else if (vs[j] == 0) { - this.count[i]++; - } - switch (id) { - case 0: - this.air[i]++; - vs[j] = (char) 1; - return; - case 10: - case 11: - case 39: - case 40: - case 51: - case 74: - case 89: - case 122: - case 124: - case 138: - case 169: - this.relight[i]++; - case 2: - case 4: - case 13: - case 14: - case 15: - case 20: - case 21: - case 22: - case 30: - case 32: - case 37: - case 41: - case 42: - case 45: - case 46: - case 47: - case 48: - case 49: - case 55: - case 56: - case 57: - case 58: - case 60: - case 7: - case 8: - case 9: - case 73: - case 78: - case 79: - case 80: - case 81: - case 82: - case 83: - case 85: - case 87: - case 88: - case 101: - case 102: - case 103: - case 110: - case 112: - case 113: - case 121: - case 129: - case 133: - case 165: - case 166: - case 170: - case 172: - case 173: - case 174: - case 181: - case 182: - case 188: - case 189: - case 190: - case 191: - case 192: - vs[j] = (char) (id << 4); - return; - case 130: - case 76: - case 62: - this.relight[i]++; - case 54: - case 146: - case 61: - case 65: - case 68: - case 50: - if (data < 2) { - data = 2; - } - default: - vs[j] = (char) ((id << 4) + data); - return; - } - } - - public char[] getIdArray(int i) { - return this.blocks[i]; - } - - public int getCount(int i) { - return this.count[i]; - } - - public int getAir(int i) { - return this.air[i]; - } - - public void setCount(int i, short value) { - this.count[i] = value; - } - - public int getRelight(int i) { - return this.relight[i]; - } - - public int getTotalCount() { - int total = 0; - for (int i = 0; i < 16; i++) { - total += this.count[i]; - } - return total; - } - - public int getTotalRelight() { - if (getTotalCount() == 0) { - Arrays.fill(this.count, (short) 1); - Arrays.fill(this.relight, Short.MAX_VALUE); - return Short.MAX_VALUE; - } - int total = 0; - for (int i = 0; i < 16; i++) { - total += this.relight[i]; - } - return total; - } - } - - @Override - public void setBlocks(LocalChunk lc) { - CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc; - Chunk chunk = getChunk(lc.getX(), lc.getZ()); - chunk.load(true); - World world = chunk.getWorld(); - ChunkWrapper wrapper = new ChunkWrapper(getWorld(), lc.getX(), lc.getZ()); - if (!this.toUpdate.containsKey(wrapper)) { - this.toUpdate.put(wrapper, chunk); - } - try { - boolean flag = world.getEnvironment() == World.Environment.NORMAL; - - // Sections - Method getHandle = chunk.getClass().getDeclaredMethod("getHandle"); - Object c = getHandle.invoke(chunk); - Object w = this.methodGetWorld.of(c).call(); - Class clazz = c.getClass(); - Field sections1 = clazz.getDeclaredField("sections"); - sections1.setAccessible(true); - Field tileEntities = clazz.getDeclaredField("tileEntities"); - Field entitySlices = clazz.getDeclaredField("entitySlices"); - Object[] sections = (Object[]) sections1.get(c); - Map tiles = (Map) tileEntities.get(c); - Collection[] entities = (Collection[]) entitySlices.get(c); - - Method getX = null; - Method getY = null; - Method getZ = null; - - // Trim tiles - boolean removed = false; - Set> entrySet = (Set>) (Set) tiles.entrySet(); - Iterator> iterator = entrySet.iterator(); - while (iterator.hasNext()) { - Map.Entry tile = iterator.next(); - Object pos = tile.getKey(); - if (getX == null) { - Class clazz2 = pos.getClass().getSuperclass(); - getX = clazz2.getDeclaredMethod("getX"); - getY = clazz2.getDeclaredMethod("getY"); - getZ = clazz2.getDeclaredMethod("getZ"); - } - int lx = (int) getX.invoke(pos) & 15; - int ly = (int) getY.invoke(pos); - int lz = (int) getZ.invoke(pos) & 15; - int j = MainUtil.CACHE_I[ly][lx][lz]; - int k = MainUtil.CACHE_J[ly][lx][lz]; - char[] array = fs.getIdArray(j); - if (array == null) { - continue; - } - if (array[k] != 0) { - removed = true; - iterator.remove(); - } - } - if (removed) { - ((Collection) this.tileEntityListTick.of(w).get()).clear(); - } - - // Trim entities - for (int i = 0; i < 16; i++) { - if ((entities[i] != null) && (fs.getCount(i) >= 4096)) { - entities[i].clear(); - } - } - - // Efficiently merge sections - for (int j = 0; j < sections.length; j++) { - if (fs.getCount(j) == 0) { - continue; - } - char[] newArray = fs.getIdArray(j); - if (newArray == null) { - continue; - } - Object section = sections[j]; - if ((section == null) || (fs.getCount(j) >= 4096)) { - section = sections[j] = newChunkSection(j << 4, flag, newArray); - continue; - } - char[] currentArray = getIdArray(section); - boolean fill = true; - for (int k = 0; k < newArray.length; k++) { - char n = newArray[k]; - switch (n) { - case 0: - fill = false; - continue; - case 1: - fill = false; - currentArray[k] = 0; - continue; - default: - currentArray[k] = n; - continue; - } - } - if (fill) { - fs.setCount(j, Short.MAX_VALUE); - } - } - // Clear - } catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) { - e.printStackTrace(); - } - fixLighting(chunk, fs, true); - } - - public Object newChunkSection(int i, boolean flag, char[] ids) throws ReflectiveOperationException { - return this.classChunkSectionConstructor.create(i, flag, ids); - } - - public char[] getIdArray(Object obj) { - return (char[]) this.methodGetIdArray.of(obj).call(); - } - - @Override - public void fixChunkLighting(int x, int z) { - Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call(); - this.methodInitLighting.of(c).call(); - } - - public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) { - try { - if (!chunk.isLoaded()) { - chunk.load(false); - } else { - chunk.unload(true, false); - chunk.load(false); - } - - // Initialize lighting - Object c = this.methodGetHandleChunk.of(chunk).call(); - - if (fixAll && !(boolean) this.methodAreNeighborsLoaded.of(c).call(1)) { - World world = chunk.getWorld(); - ChunkWrapper wrapper = new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ()); - for (int x = wrapper.x - 1; x <= wrapper.x + 1; x++) { - for (int z = wrapper.z - 1; z <= wrapper.z + 1; z++) { - if (x != 0 && z != 0) { - Chunk other = world.getChunkAt(x, z); - while (!other.isLoaded()) { - other.load(true); - } - ChunkManager.manager.loadChunk(wrapper.world, new ChunkLoc(x, z), true); - } - } - } - /* - if (!(boolean) methodAreNeighborsLoaded.of(c).call(1)) { - return false; - } - */ - } - - this.methodInitLighting.of(c).call(); - - if (bc.getTotalRelight() == 0 && !fixAll) { - return true; - } - - Object[] sections = (Object[]) this.fieldSections.of(c).get(); - Object w = this.fieldWorld.of(c).get(); - - int X = chunk.getX() << 4; - int Z = chunk.getZ() << 4; - - ReflectionUtils.RefMethod.RefExecutor relight = this.methodX.of(w); - for (int j = 0; j < sections.length; j++) { - Object section = sections[j]; - if (section == null) { - continue; - } - if ((bc.getRelight(j) == 0 && !fixAll) || bc.getCount(j) == 0 || (bc.getCount(j) >= 4096 && bc.getAir(j) == 0)) { - continue; - } - char[] array = getIdArray(section); - int l = PseudoRandom.random.random(2); - for (int k = 0; k < array.length; k++) { - int i = array[k]; - if (i < 16) { - continue; - } - short id = (short) (i >> 4); - switch (id) { // Lighting - default: - if (!fixAll) { - continue; - } - if ((k & 1) == l) { - l = 1 - l; - continue; - } - case 10: - case 11: - case 39: - case 40: - case 50: - case 51: - case 62: - case 74: - case 76: - case 89: - case 122: - case 124: - case 130: - case 138: - case 169: - int x = MainUtil.x_loc[j][k]; - int y = MainUtil.y_loc[j][k]; - int z = MainUtil.z_loc[j][k]; - if (isSurrounded(sections, x, y, z)) { - continue; - } - Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z); - relight.call(pos); - } - } - } - return true; - } catch (Throwable e) { - e.printStackTrace(); - } - return false; - } - - public boolean isSurrounded(Object[] sections, int x, int y, int z) { - return isSolid(getId(sections, x, y + 1, z)) - && isSolid(getId(sections, x + 1, y - 1, z)) - && isSolid(getId(sections, x - 1, y, z)) - && isSolid(getId(sections, x, y, z + 1)) - && isSolid(getId(sections, x, y, z - 1)); - } - - public boolean isSolid(int i) { - return i != 0 && Material.getMaterial(i).isOccluding(); - } - - public int getId(Object[] sections, int x, int y, int z) { - if (x < 0 || x > 15 || z < 0 || z > 15) { - return 1; - } - if (y < 0 || y > 255) { - return 1; - } - int i = MainUtil.CACHE_I[y][x][z]; - Object section = sections[i]; - if (section == null) { - return 0; - } - char[] array = getIdArray(section); - int j = MainUtil.CACHE_J[y][x][z]; - return array[j] >> 4; - } - - public void update(Collection chunks) { - if (chunks.isEmpty()) { - return; - } - if (!MainUtil.canSendChunk) { - for (Chunk chunk : chunks) { - chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ()); - chunk.unload(true, false); - chunk.load(); - } - return; - } - try { - this.sendChunk.sendChunk(chunks); - } catch (Throwable e) { - e.printStackTrace(); - MainUtil.canSendChunk = false; - } - } - - @Override - public void refreshChunk(int x, int z) { - update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z))); - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_9.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_9.java deleted file mode 100644 index 351a69243..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/block/BukkitLocalQueue_1_9.java +++ /dev/null @@ -1,494 +0,0 @@ -package com.plotsquared.bukkit.util.block; - -import com.intellectualcrafters.plot.object.ChunkWrapper; -import com.intellectualcrafters.plot.object.PseudoRandom; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.ReflectionUtils; -import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import org.bukkit.Chunk; -import org.bukkit.Material; -import org.bukkit.World; - - -import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; - -public class BukkitLocalQueue_1_9 extends BukkitLocalQueue { - - private final Object air; - // private final HashMap toUpdate = new HashMap<>(); - private final ReflectionUtils.RefMethod methodGetHandleChunk; - private final ReflectionUtils.RefMethod methodInitLighting; - private final ReflectionUtils.RefConstructor classBlockPositionConstructor; - private final ReflectionUtils.RefConstructor classChunkSectionConstructor; - private final ReflectionUtils.RefMethod methodW; - private final ReflectionUtils.RefMethod methodAreNeighborsLoaded; - private final ReflectionUtils.RefField fieldSections; - private final ReflectionUtils.RefField fieldWorld; - private final ReflectionUtils.RefMethod methodGetBlocks; - private final ReflectionUtils.RefMethod methodGetType; - private final ReflectionUtils.RefMethod methodSetType; - private final ReflectionUtils.RefMethod methodGetCombinedId; - private final ReflectionUtils.RefMethod methodGetByCombinedId; - private final ReflectionUtils.RefMethod methodGetWorld; - - private final ReflectionUtils.RefField tileEntityListTick; - - public BukkitLocalQueue_1_9(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException { - super(world); - ReflectionUtils.RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); - this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); - ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk"); - this.methodInitLighting = classChunk.getMethod("initLighting"); - ReflectionUtils.RefClass classBlockPosition = getRefClass("{nms}.BlockPosition"); - this.classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class); - ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World"); - this.tileEntityListTick = classWorld.getField("tileEntityListTick"); - this.methodGetWorld = classChunk.getMethod("getWorld"); - this.methodW = classWorld.getMethod("w", classBlockPosition.getRealClass()); - this.fieldSections = classChunk.getField("sections"); - this.fieldWorld = classChunk.getField("world"); - ReflectionUtils.RefClass classBlock = getRefClass("{nms}.Block"); - ReflectionUtils.RefClass classIBlockData = getRefClass("{nms}.IBlockData"); - this.methodGetCombinedId = classBlock.getMethod("getCombinedId", classIBlockData.getRealClass()); - this.methodGetByCombinedId = classBlock.getMethod("getByCombinedId", int.class); - ReflectionUtils.RefClass classChunkSection = getRefClass("{nms}.ChunkSection"); - this.methodGetBlocks = classChunkSection.getMethod("getBlocks"); - this.methodGetType = classChunkSection.getMethod("getType", int.class, int.class, int.class); - this.methodSetType = classChunkSection.getMethod("setType", int.class, int.class, int.class, classIBlockData.getRealClass()); - this.methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class); - this.classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class); - this.air = this.methodGetByCombinedId.call(0); - MainUtil.initCache(); - } - - @Override - public LocalChunk getLocalChunk(int x, int z) { - return new CharLocalChunk_1_8_3(this, x, z); - } - - public class CharLocalChunk_1_8_3 extends CharLocalChunk { - public short[] count; - public short[] air; - public short[] relight; - - public CharLocalChunk_1_8_3(BasicLocalBlockQueue parent, int x, int z) { - super(parent, x, z); - this.count = new short[16]; - this.air = new short[16]; - this.relight = new short[16]; - } - - @Override - public void setBlock(int x, int y, int z, int id, int data) { - int i = MainUtil.CACHE_I[y][x][z]; - int j = MainUtil.CACHE_J[y][x][z]; - char[] vs = this.blocks[i]; - if (vs == null) { - vs = this.blocks[i] = new char[4096]; - this.count[i]++; - } else if (vs[j] == 0) { - this.count[i]++; - } - switch (id) { - case 0: - this.air[i]++; - vs[j] = (char) 1; - return; - case 10: - case 11: - case 39: - case 40: - case 51: - case 74: - case 89: - case 122: - case 124: - case 138: - case 169: - this.relight[i]++; - case 2: - case 4: - case 13: - case 14: - case 15: - case 20: - case 21: - case 22: - case 30: - case 32: - case 37: - case 41: - case 42: - case 45: - case 46: - case 47: - case 48: - case 49: - case 55: - case 56: - case 57: - case 58: - case 60: - case 7: - case 8: - case 9: - case 73: - case 78: - case 79: - case 80: - case 81: - case 82: - case 83: - case 85: - case 87: - case 88: - case 101: - case 102: - case 103: - case 110: - case 112: - case 113: - case 121: - case 129: - case 133: - case 165: - case 166: - case 170: - case 172: - case 173: - case 174: - case 181: - case 182: - case 188: - case 189: - case 190: - case 191: - case 192: - vs[j] = (char) (id << 4); - return; - case 130: - case 76: - case 62: - this.relight[i]++; - case 54: - case 146: - case 61: - case 65: - case 68: - case 50: - if (data < 2) { - data = 2; - } - default: - vs[j] = (char) ((id << 4) + data); - return; - } - } - - public char[] getIdArray(int i) { - return this.blocks[i]; - } - - public int getCount(int i) { - return this.count[i]; - } - - public int getAir(int i) { - return this.air[i]; - } - - public void setCount(int i, short value) { - this.count[i] = value; - } - - public int getRelight(int i) { - return this.relight[i]; - } - - public int getTotalCount() { - int total = 0; - for (int i = 0; i < 16; i++) { - total += this.count[i]; - } - return total; - } - - public int getTotalRelight() { - if (getTotalCount() == 0) { - Arrays.fill(this.count, (short) 1); - Arrays.fill(this.relight, Short.MAX_VALUE); - return Short.MAX_VALUE; - } - int total = 0; - for (int i = 0; i < 16; i++) { - total += this.relight[i]; - } - return total; - } - } - - @Override - public void setBlocks(LocalChunk lc) { - CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc; - Chunk chunk = getChunk(lc.getX(), lc.getZ()); - chunk.load(true); - World world = chunk.getWorld(); - try { - boolean flag = world.getEnvironment() == World.Environment.NORMAL; - - // Sections - Method getHandle = chunk.getClass().getDeclaredMethod("getHandle"); - Object c = getHandle.invoke(chunk); - Object w = this.methodGetWorld.of(c).call(); - Class clazz = c.getClass(); - Field sf = clazz.getDeclaredField("sections"); - sf.setAccessible(true); - Field tf = clazz.getDeclaredField("tileEntities"); - Field entitySlices = clazz.getDeclaredField("entitySlices"); - Object[] sections = (Object[]) sf.get(c); - Map tiles = (Map) tf.get(c); - Collection[] entities = (Collection[]) entitySlices.get(c); - - Method xm = null; - Method ym = null; - Method zm = null; - // Trim tiles - Collection tickList = ((Collection) this.tileEntityListTick.of(w).get()); - Set> entrySet = (Set>) (Set) tiles.entrySet(); - Iterator> iterator = entrySet.iterator(); - while (iterator.hasNext()) { - Map.Entry tile = iterator.next(); - Object pos = tile.getKey(); - if (xm == null) { - Class clazz2 = pos.getClass().getSuperclass(); - xm = clazz2.getDeclaredMethod("getX"); - ym = clazz2.getDeclaredMethod("getY"); - zm = clazz2.getDeclaredMethod("getZ"); - } - int lx = (int) xm.invoke(pos) & 15; - int ly = (int) ym.invoke(pos); - int lz = (int) zm.invoke(pos) & 15; - int j = MainUtil.CACHE_I[ly][lx][lz]; - int k = MainUtil.CACHE_J[ly][lx][lz]; - char[] array = fs.getIdArray(j); - if (array == null) { - continue; - } - if (array[k] != 0) { - tickList.remove(tile.getValue()); - iterator.remove(); - } - } - - // Trim entities - for (int i = 0; i < 16; i++) { - if (entities[i] != null && fs.getCount(i) >= 4096) { - entities[i].clear(); - } - } - - // Efficiently merge sections - for (int j = 0; j < sections.length; j++) { - if (fs.getCount(j) == 0) { - continue; - } - char[] newArray = fs.getIdArray(j); - if (newArray == null) { - continue; - } - Object section = sections[j]; - if (section == null || fs.getCount(j) >= 4096) { - section = sections[j] = newChunkSection(j << 4, flag, fs.getIdArray(j)); - continue; - } - Object currentArray = getBlocks(section); - ReflectionUtils.RefMethod.RefExecutor setType = this.methodSetType.of(section); - boolean fill = true; - for (int k = 0; k < newArray.length; k++) { - char n = newArray[k]; - switch (n) { - case 0: - fill = false; - continue; - case 1: { - fill = false; - int x = MainUtil.x_loc[j][k]; - int y = MainUtil.y_loc[j][k]; - int z = MainUtil.z_loc[j][k]; - setType.call(x, y & 15, z, this.air); - continue; - } - default: - int x = MainUtil.x_loc[j][k]; - int y = MainUtil.y_loc[j][k]; - int z = MainUtil.z_loc[j][k]; - int id = n >> 4; - int data = n & 15; - Object iBlock = this.methodGetByCombinedId.call((int) (id & 0xFFF) + (data << 12)); - setType.call(x, y & 15, z, iBlock); - } - } - if (fill) { - fs.setCount(j, Short.MAX_VALUE); - } - } - // Clear - } catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) { - e.printStackTrace(); - } - fixLighting(chunk, fs, true); - refreshChunk(fs.getX(), fs.getZ()); - } - - public Object newChunkSection(int i, boolean flag, char[] ids) throws ReflectiveOperationException { - return this.classChunkSectionConstructor.create(i, flag, ids); - } - - public Object getBlocks(Object obj) { - return this.methodGetBlocks.of(obj).call(); - } - - @Override - public void fixChunkLighting(int x, int z) { - Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call(); - this.methodInitLighting.of(c).call(); - } - - public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) { - try { - if (!chunk.isLoaded()) { - chunk.load(false); - } else { - chunk.unload(true, false); - chunk.load(false); - } - - // Initialize lighting - Object c = this.methodGetHandleChunk.of(chunk).call(); - - ChunkWrapper wrapper = new ChunkWrapper(getWorld(), bc.getX(), bc.getZ()); - Object[] result = disableLighting(chunk); - enableLighting(result); - - this.methodInitLighting.of(c).call(); - - if (bc.getTotalRelight() != 0 || fixAll) { - Object[] sections = (Object[]) this.fieldSections.of(c).get(); - Object w = this.fieldWorld.of(c).get(); - - int X = chunk.getX() << 4; - int Z = chunk.getZ() << 4; - ReflectionUtils.RefMethod.RefExecutor relight = this.methodW.of(w); - for (int j = 0; j < sections.length; j++) { - Object section = sections[j]; - if (section == null) { - continue; - } - if (bc.getRelight(j) == 0 && !fixAll || bc.getCount(j) == 0 || bc.getCount(j) >= 4096 && bc.getAir(j) == 0) { - continue; - } - char[] array = bc.getIdArray(j); - if (array != null) { - int l = PseudoRandom.random.random(2); - for (int k = 0; k < array.length; k++) { - int i = array[k]; - if (i < 16) { - continue; - } - short id = (short) (i >> 4); - switch (id) { // Lighting - default: - if (!fixAll) { - continue; - } - if ((k & 1) == l) { - l = 1 - l; - continue; - } - case 10: - case 11: - case 39: - case 40: - case 50: - case 51: - case 62: - case 74: - case 76: - case 89: - case 122: - case 124: - case 130: - case 138: - case 169: - int x = MainUtil.x_loc[j][k]; - int y = MainUtil.y_loc[j][k]; - int z = MainUtil.z_loc[j][k]; - if (isSurrounded(bc.blocks, x, y, z)) { - continue; - } - Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z); - relight.call(pos); - } - } - } - } - } - resetLighting(result); - return true; - } catch (Throwable e) { - e.printStackTrace(); - } - return false; - } - - @Override - public void refreshChunk(int x, int z) { - getBukkitWorld().refreshChunk(x, z); - } - - public boolean isSurrounded(char[][] sections, int x, int y, int z) { - return isSolid(getId(sections, x, y + 1, z)) - && isSolid(getId(sections, x + 1, y - 1, z)) - && isSolid(getId(sections, x - 1, y, z)) - && isSolid(getId(sections, x, y, z + 1)) - && isSolid(getId(sections, x, y, z - 1)); - } - - public boolean isSolid(int i) { - if (i != 0) { - Material material = Material.getMaterial(i); - return material != null && Material.getMaterial(i).isOccluding(); - } - return false; - } - - public int getId(char[] section, int x, int y, int z) { - if (section == null) { - return 0; - } - int j = MainUtil.CACHE_J[y][x][z]; - return section[j] >> 4; - } - - public int getId(char[][] sections, int x, int y, int z) { - if (x < 0 || x > 15 || z < 0 || z > 15) { - return 1; - } - if (y < 0 || y > 255) { - return 1; - } - int i = MainUtil.CACHE_I[y][x][z]; - char[] section = sections[i]; - if (section == null) { - return 0; - } - return getId(section, x, y, z); - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java deleted file mode 100644 index e066b29f8..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/DefaultUUIDWrapper.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.plotsquared.bukkit.uuid; - -import com.intellectualcrafters.plot.object.OfflinePlotPlayer; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.uuid.UUIDWrapper; -import com.plotsquared.bukkit.object.BukkitOfflinePlayer; -import com.plotsquared.bukkit.object.BukkitPlayer; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; - -import java.util.UUID; - -public class DefaultUUIDWrapper extends UUIDWrapper { - - @Override - public UUID getUUID(PlotPlayer player) { - return ((BukkitPlayer) player).player.getUniqueId(); - } - - @Override - public UUID getUUID(OfflinePlotPlayer player) { - return player.getUUID(); - } - - @Override - public OfflinePlotPlayer getOfflinePlayer(UUID uuid) { - return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(uuid)); - } - - @Override - public UUID getUUID(String name) { - return Bukkit.getOfflinePlayer(name).getUniqueId(); - } - - @Override - public OfflinePlotPlayer[] getOfflinePlayers() { - OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); - BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; - for (int i = 0; i < ops.length; i++) { - toReturn[i] = new BukkitOfflinePlayer(ops[i]); - } - return toReturn; - } - - @Override - public OfflinePlotPlayer getOfflinePlayer(String name) { - return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(name)); - } -} diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java deleted file mode 100644 index e2afa50e9..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/uuid/LowerOfflineUUIDWrapper.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.plotsquared.bukkit.uuid; - -import com.google.common.base.Charsets; -import com.intellectualcrafters.plot.object.OfflinePlotPlayer; -import com.intellectualcrafters.plot.object.PlotPlayer; -import org.bukkit.OfflinePlayer; - -import java.util.UUID; - -public class LowerOfflineUUIDWrapper extends OfflineUUIDWrapper { - - @Override - public UUID getUUID(PlotPlayer player) { - return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); - } - - @Override - public UUID getUUID(OfflinePlotPlayer player) { - return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); - } - - @Override - public UUID getUUID(OfflinePlayer player) { - return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); - } - - @Override - public UUID getUUID(String name) { - return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8)); - } - -} diff --git a/Bukkit/src/main/resources/plugin.yml b/Bukkit/src/main/resources/plugin.yml index 8c0c8bd9f..ae7d4ad57 100644 --- a/Bukkit/src/main/resources/plugin.yml +++ b/Bukkit/src/main/resources/plugin.yml @@ -1,5 +1,6 @@ name: ${name} -main: com.plotsquared.bukkit.BukkitMain +main: com.github.intellectualsites.plotsquared.bukkit.BukkitMain +api-version: 1.13 version: ${version} load: STARTUP description: > @@ -314,4 +315,4 @@ permissions: plots.admin.vehicle.*: true plots.admin.interact.*: true plots.admin.build.*: true - plots.admin.destroy.*: true \ No newline at end of file + plots.admin.destroy.*: true diff --git a/Core/build.gradle b/Core/build.gradle index 0b787c2f0..f7d9f78eb 100644 --- a/Core/build.gradle +++ b/Core/build.gradle @@ -2,10 +2,11 @@ dependencies { testCompile 'junit:junit:4.12' compile 'org.yaml:snakeyaml:1.16' compile 'com.google.code.gson:gson:2.2.4' + compileOnly 'org.projectlombok:lombok:1.16.18' } -sourceCompatibility = 1.7 -targetCompatibility = 1.7 +sourceCompatibility = 1.8 +targetCompatibility = 1.8 processResources { @@ -18,7 +19,7 @@ processResources { } } -jar.archiveName="plotsquared-api-${project.parent.version}.jar" +jar.archiveName = "plotsquared-api-${project.parent.version}.jar" jar.destinationDir = file '../mvn/com/plotsquared/plotsquared-api/' + project.parent.version task createPom << { pom { @@ -43,10 +44,10 @@ task copyFiles { from "../mvn/com/plotsquared/plotsquared-api/${project.parent.version}/" into '../mvn/com/plotsquared/plotsquared-api/latest/' include('*.jar') - rename ("plotsquared-api-${project.parent.version}.jar", 'plotsquared-api-latest.jar') + rename("plotsquared-api-${project.parent.version}.jar", 'plotsquared-api-latest.jar') } } } build.finalizedBy(copyFiles) -copyFiles.dependsOn(createPom) \ No newline at end of file +copyFiles.dependsOn(createPom) diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/api/PlotAPI.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/api/PlotAPI.java new file mode 100644 index 000000000..c966903be --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/api/PlotAPI.java @@ -0,0 +1,224 @@ +package com.github.intellectualsites.plotsquared.api; + +import com.github.intellectualsites.plotsquared.configuration.file.YamlConfiguration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.flag.Flag; +import com.github.intellectualsites.plotsquared.plot.flag.Flags; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.uuid.UUIDWrapper; +import lombok.NoArgsConstructor; + +import java.util.Collections; +import java.util.Set; +import java.util.UUID; + +/** + * PlotSquared API. + * + *

Useful classes: + *

    + *
  • {@link PlotPlayer}
  • + *
  • {@link Plot}
  • + *
  • {@link com.github.intellectualsites.plotsquared.plot.object.Location}
  • + *
  • {@link PlotArea}
  • + *
  • {@link PlotSquared}
  • + *
+ * + * @version 3.3.3 + */ +@SuppressWarnings({"unused", "WeakerAccess"}) @NoArgsConstructor public class PlotAPI { + + /** + * Get all plots. + * + * @return all plots + * @see PlotSquared#getPlots() + */ + public Set getAllPlots() { + return PlotSquared.get().getPlots(); + } + + /** + * Return all plots for a player. + * + * @param player Player, whose plots to search for + * @return all plots that a player owns + */ + public Set getPlayerPlots(PlotPlayer player) { + return PlotSquared.get().getPlots(player); + } + + /** + * Add a plot world. + * + * @param plotArea Plot World Object + * @see PlotSquared#addPlotArea(PlotArea) + */ + public void addPlotArea(PlotArea plotArea) { + PlotSquared.get().addPlotArea(plotArea); + } + + /** + * Returns the PlotSquared configurations file. + * + * @return main configuration + * @see PlotSquared#config + */ + public YamlConfiguration getConfig() { + return PlotSquared.get().config; + } + + /** + * Get the PlotSquared storage file. + * + * @return storage configuration + * @see PlotSquared#storage + */ + public YamlConfiguration getStorage() { + return PlotSquared.get().storage; + } + + /** + * Get the main class for this plugin. Only use this if you really need it. + * + * @return PlotSquared PlotSquared Main Class + * @see PlotSquared + */ + public PlotSquared getMain() { + return PlotSquared.get(); + } + + /** + * ChunkManager class contains several useful methods. + *
    + *
  • Chunk deletion
  • + *
  • Moving or copying regions
  • + *
  • Plot swapping
  • + *
  • Entity Tracking
  • + *
  • Region Regeneration
  • + *
+ * + * @return ChunkManager + * @see ChunkManager + */ + public ChunkManager getChunkManager() { + return ChunkManager.manager; + } + + /** + * Get the block/biome set queue + * + * @return GlobalBlockQueue.IMP + */ + public GlobalBlockQueue getBlockQueue() { + return GlobalBlockQueue.IMP; + } + + /** + * UUIDWrapper class has basic methods for getting UUIDS. It's recommended + * to use the UUIDHandler class instead. + * + * @return UUIDWrapper + * @see UUIDWrapper + */ + public UUIDWrapper getUUIDWrapper() { + return UUIDHandler.getUUIDWrapper(); + } + + /** + * SchematicHandler class contains methods related to pasting, reading + * and writing schematics. + * + * @return SchematicHandler + * @see SchematicHandler + */ + public SchematicHandler getSchematicHandler() { + return SchematicHandler.manager; + } + + /** + * Get a list of PlotAreas in the world. + * + * @param world The world to check for plot areas + * @return A set of PlotAreas + */ + public Set getPlotAreas(String world) { + if (world == null) { + return Collections.emptySet(); + } + return PlotSquared.get().getPlotAreas(world); + } + + /** + * Send a message to the console. The message supports color codes. + * + * @param message the message + * @see MainUtil#sendConsoleMessage(C, String...) + */ + public void sendConsoleMessage(String message) { + PlotSquared.log(message); + } + + /** + * Send a message to the console. + * + * @param caption the message + * @see #sendConsoleMessage(String) + * @see C + */ + public void sendConsoleMessage(C caption) { + sendConsoleMessage(caption.s()); + } + + /** + * Registers a flag for use in plots. + * + * @param flag the flag to register + */ + public void addFlag(Flag flag) { + Flags.registerFlag(flag); + } + + /** + * Gets the PlotSquared class. + * + * @return PlotSquared Class + * @see PlotSquared + */ + public PlotSquared getPlotSquared() { + return PlotSquared.get(); + } + + /** + * Get the PlotPlayer for a UUID. + * + *

Please note that PlotSquared can be configured to provide + * different UUIDs than bukkit + * + * @param uuid the uuid of the player to wrap + * @return a {@code PlotPlayer} + * @see PlotPlayer#wrap(Object) + */ + public PlotPlayer wrapPlayer(UUID uuid) { + return PlotPlayer.wrap(uuid); + } + + /** + * Get the PlotPlayer for a username. + * + * @param player the player to wrap + * @return a {@code PlotPlayer} + * @see PlotPlayer#wrap(Object) + */ + public PlotPlayer wrapPlayer(String player) { + return PlotPlayer.wrap(player); + } +} diff --git a/Core/src/main/java/com/plotsquared/general/commands/Argument.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Argument.java similarity index 54% rename from Core/src/main/java/com/plotsquared/general/commands/Argument.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Argument.java index f9696a7b6..dd5221a3a 100644 --- a/Core/src/main/java/com/plotsquared/general/commands/Argument.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Argument.java @@ -1,49 +1,49 @@ -package com.plotsquared.general.commands; +package com.github.intellectualsites.plotsquared.commands; -import com.intellectualcrafters.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; public abstract class Argument { public static final Argument Integer = new Argument("int", 16) { - @Override - public Integer parse(String in) { + @Override public Integer parse(String in) { Integer value = null; try { value = java.lang.Integer.parseInt(in); - } catch (Exception ignored) {} + } catch (Exception ignored) { + } return value; } }; public static final Argument Boolean = new Argument("boolean", true) { - @Override - public Boolean parse(String in) { + @Override public Boolean parse(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 = new Argument("String", "Example") { - @Override - public String parse(String in) { + @Override public String parse(String in) { return in; } }; - public static final Argument PlayerName = new Argument("PlayerName", "Dinnerbone") { - @Override - public String parse(String in) { - return in.length() <= 16 ? in : null; - } - }; - public static final Argument PlotID = new Argument("PlotID", new PlotId(-6, 3)) { - @Override - public PlotId parse(String in) { - return PlotId.fromString(in); - } - }; + public static final Argument PlayerName = + new Argument("PlayerName", "Dinnerbone") { + @Override public String parse(String in) { + return in.length() <= 16 ? in : null; + } + }; + public static final Argument PlotID = + new Argument("PlotID", new PlotId(-6, 3)) { + @Override public PlotId parse(String in) { + return PlotId.fromString(in); + } + }; private final String name; private final T example; @@ -54,8 +54,7 @@ public abstract class Argument { public abstract T parse(String in); - @Override - public final String toString() { + @Override public final String toString() { return this.getName(); } diff --git a/Core/src/main/java/com/plotsquared/general/commands/Command.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Command.java similarity index 83% rename from Core/src/main/java/com/plotsquared/general/commands/Command.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Command.java index 5152b0e10..6bac09a26 100644 --- a/Core/src/main/java/com/plotsquared/general/commands/Command.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Command.java @@ -1,35 +1,22 @@ -package com.plotsquared.general.commands; +package com.github.intellectualsites.plotsquared.commands; -import com.intellectualcrafters.configuration.file.YamlConfiguration; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.commands.CommandCategory; -import com.intellectualcrafters.plot.commands.MainCommand; -import com.intellectualcrafters.plot.commands.RequiredType; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.PlotMessage; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal2; -import com.intellectualcrafters.plot.object.RunnableVal3; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.StringComparison; -import com.intellectualcrafters.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.configuration.file.YamlConfiguration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.commands.CommandCategory; +import com.github.intellectualsites.plotsquared.plot.commands.MainCommand; +import com.github.intellectualsites.plotsquared.plot.commands.RequiredType; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.PlotMessage; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; +import com.github.intellectualsites.plotsquared.plot.util.*; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; public abstract class Command { @@ -52,7 +39,8 @@ public abstract class Command { private CommandCategory category; private Argument[] arguments; - public Command(Command parent, boolean isStatic, String id, String perm, RequiredType required, CommandCategory cat) { + public Command(Command parent, boolean isStatic, String id, String perm, RequiredType required, + CommandCategory cat) { this.parent = parent; this.isStatic = isStatic; this.id = id; @@ -78,12 +66,13 @@ public abstract class Command { Class[] types = method.getParameterTypes(); // final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 // whenDone - if (types.length == 5 && types[0] == Command.class && types[1] == PlotPlayer.class && types[2] == String[].class - && types[3] == RunnableVal3.class && types[4] == RunnableVal2.class) { + if (types.length == 5 && types[0] == Command.class && types[1] == PlotPlayer.class + && types[2] == String[].class && types[3] == RunnableVal3.class + && types[4] == RunnableVal2.class) { Command tmp = new Command(this, true) { - @Override - public void execute(PlotPlayer player, String[] args, RunnableVal3 confirm, - RunnableVal2 whenDone) { + @Override public void execute(PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) { try { method.invoke(Command.this, this, player, args, confirm, whenDone); } catch (IllegalAccessException | InvocationTargetException e) { @@ -177,7 +166,8 @@ public abstract class Command { options.put("usage", declaration.usage()); options.put("confirmation", declaration.confirmation()); boolean set = false; - YamlConfiguration commands = PS.get() == null ? new YamlConfiguration() : PS.get().commands; + YamlConfiguration commands = + PlotSquared.get() == null ? new YamlConfiguration() : PlotSquared.get().commands; for (Map.Entry entry : options.entrySet()) { String key = this.getFullId() + "." + entry.getKey(); if (!commands.contains(key)) { @@ -185,9 +175,9 @@ public abstract class Command { set = true; } } - if (set && PS.get() != null) { + if (set && PlotSquared.get() != null) { try { - commands.save(PS.get().commandsFile); + commands.save(PlotSquared.get().commandsFile); } catch (IOException e) { e.printStackTrace(); @@ -223,8 +213,8 @@ public abstract class Command { return "plots." + getFullId(); } - public void paginate(PlotPlayer player, List c, int size, int page, RunnableVal3 add, String baseCommand, - String header) { + public void paginate(PlotPlayer player, List c, int size, int page, + RunnableVal3 add, String baseCommand, String header) { // Calculate pages & index if (page < 0) { page = 0; @@ -238,8 +228,8 @@ public abstract class Command { max = c.size(); } // Send the header - header = header.replaceAll("%cur", page + 1 + "").replaceAll("%max", totalPages + 1 + "").replaceAll("%amount%", c.size() + "") - .replaceAll("%word%", "all"); + header = header.replaceAll("%cur", page + 1 + "").replaceAll("%max", totalPages + 1 + "") + .replaceAll("%amount%", c.size() + "").replaceAll("%word%", "all"); MainUtil.sendMessage(player, header); // Send the page content List subList = c.subList(page * size, max); @@ -252,31 +242,32 @@ public abstract class Command { } // Send the footer if (page < totalPages && page > 0) { // Back | Next - new PlotMessage().text("<-").color("$1").command(baseCommand + " " + page).text(" | ").color("$3").text("->").color("$1") - .command(baseCommand + " " + (page + 2)) - .text(C.CLICKABLE.s()).color("$2").send(player); + new PlotMessage().text("<-").color("$1").command(baseCommand + " " + page).text(" | ") + .color("$3").text("->").color("$1").command(baseCommand + " " + (page + 2)) + .text(C.CLICKABLE.s()).color("$2").send(player); return; } if (page == 0 && totalPages != 0) { // Next - new PlotMessage().text("<-").color("$3").text(" | ").color("$3").text("->").color("$1").command(baseCommand + " " + (0 + 2)) - .text(C.CLICKABLE.s()).color("$2").send(player); + new PlotMessage().text("<-").color("$3").text(" | ").color("$3").text("->").color("$1") + .command(baseCommand + " " + (0 + 2)).text(C.CLICKABLE.s()).color("$2") + .send(player); return; } if (page == totalPages && totalPages != 0) { // Back - new PlotMessage().text("<-").color("$1").command(baseCommand + " " + page).text(" | ").color("$3").text("->").color("$3") - .text(C.CLICKABLE.s()).color("$2").send(player); + new PlotMessage().text("<-").color("$1").command(baseCommand + " " + page).text(" | ") + .color("$3").text("->").color("$3").text(C.CLICKABLE.s()).color("$2").send(player); } } /** - * - * @param player Caller - * @param args Arguments + * @param player Caller + * @param args Arguments * @param confirm Instance, Success, Failure * @return */ - public void execute(PlotPlayer player, String[] args, RunnableVal3 confirm, - RunnableVal2 whenDone) throws CommandException { + public void execute(PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) throws CommandException { if (args.length == 0 || args[0] == null) { if (this.parent == null) { MainCommand.getInstance().help.displayHelp(player, null, 0); @@ -286,7 +277,8 @@ public abstract class Command { return; } if (this.allCommands == null || this.allCommands.isEmpty()) { - player.sendMessage("Not Implemented: https://github.com/IntellectualSites/PlotSquared/issues/new"); + player.sendMessage( + "Not Implemented: https://github.com/IntellectualSites/PlotSquared/issues/new"); return; } Command cmd = getCommand(args[0]); @@ -297,18 +289,21 @@ public abstract class Command { } // Help command try { - if (args.length == 0 || MathMan.isInteger(args[0]) || CommandCategory.valueOf(args[0].toUpperCase()) != null) { + if (args.length == 0 || MathMan.isInteger(args[0]) + || CommandCategory.valueOf(args[0].toUpperCase()) != null) { // This will default certain syntax to the help command // e.g. /plot, /plot 1, /plot claiming MainCommand.getInstance().help.execute(player, args, null, null); return; } - } catch (IllegalArgumentException ignored) {} + } catch (IllegalArgumentException ignored) { + } // Command recommendation MainUtil.sendMessage(player, C.NOT_VALID_SUBCOMMAND); List commands = getCommands(player); if (commands.isEmpty()) { - MainUtil.sendMessage(player, C.DID_YOU_MEAN, MainCommand.getInstance().help.getUsage()); + MainUtil + .sendMessage(player, C.DID_YOU_MEAN, MainCommand.getInstance().help.getUsage()); return; } HashSet setargs = new HashSet<>(args.length); @@ -443,7 +438,8 @@ public abstract class Command { } if (!this.required.allows(player)) { if (message) { - MainUtil.sendMessage(player, this.required == RequiredType.PLAYER ? C.IS_CONSOLE : C.NOT_CONSOLE); + MainUtil.sendMessage(player, + this.required == RequiredType.PLAYER ? C.IS_CONSOLE : C.NOT_CONSOLE); } } else if (!Permissions.hasPermission(player, getPermission())) { if (message) { @@ -488,7 +484,8 @@ public abstract class Command { return getCommandString() + " " + args + "]"; } - public Collection tabOf(PlotPlayer player, String[] input, boolean space, String... args) { + public Collection tabOf(PlotPlayer player, String[] input, boolean space, + String... args) { if (!space) { return null; } @@ -501,7 +498,8 @@ public abstract class Command { continue; } arg = StringMan.join(Arrays.copyOfRange(split, index, split.length), " "); - Command cmd = new Command(null, false, arg, getPermission(), getRequiredType(), null) {}; + Command cmd = new Command(null, false, arg, getPermission(), getRequiredType(), null) { + }; result.add(cmd); } return result; @@ -523,7 +521,8 @@ public abstract class Command { } else { Set commands = new HashSet(); for (Map.Entry entry : this.staticCommands.entrySet()) { - if (entry.getKey().startsWith(arg) && entry.getValue().canExecute(player, false)) { + if (entry.getKey().startsWith(arg) && entry.getValue() + .canExecute(player, false)) { commands.add(entry.getValue()); } } @@ -539,13 +538,11 @@ public abstract class Command { } } - @Override - public String toString() { + @Override public String toString() { return !this.aliases.isEmpty() ? this.aliases.get(0) : this.id; } - @Override - public boolean equals(Object obj) { + @Override public boolean equals(Object obj) { if (this == obj) { return true; } @@ -559,16 +556,10 @@ public abstract class Command { return this.getFullId().equals(other.getFullId()); } - @Override - public int hashCode() { + @Override public int hashCode() { return this.getFullId().hashCode(); } - public enum CommandResult { - FAILURE, - SUCCESS - } - public void checkTrue(boolean mustBeTrue, C message, Object... args) { if (!mustBeTrue) { throw new CommandException(message, args); @@ -582,6 +573,11 @@ public abstract class Command { return object; } + public enum CommandResult { + FAILURE, SUCCESS + } + + public static class CommandException extends RuntimeException { private final Object[] args; private final C message; diff --git a/Core/src/main/java/com/plotsquared/general/commands/CommandCaller.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/CommandCaller.java similarity index 75% rename from Core/src/main/java/com/plotsquared/general/commands/CommandCaller.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/commands/CommandCaller.java index d9aabe71b..3b5ee295e 100644 --- a/Core/src/main/java/com/plotsquared/general/commands/CommandCaller.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/CommandCaller.java @@ -1,22 +1,24 @@ -package com.plotsquared.general.commands; +package com.github.intellectualsites.plotsquared.commands; -import com.intellectualcrafters.plot.commands.RequiredType; +import com.github.intellectualsites.plotsquared.plot.commands.RequiredType; public interface CommandCaller { /** * Send the player a message. + * * @param message the message to send */ void sendMessage(String message); /** * Check the player's permissions. Will be cached if permission caching is enabled. + * * @param permission the name of the permission */ boolean hasPermission(String permission); boolean isPermissionSet(String permission); - + RequiredType getSuperCaller(); } diff --git a/Core/src/main/java/com/plotsquared/general/commands/CommandDeclaration.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/CommandDeclaration.java similarity index 63% rename from Core/src/main/java/com/plotsquared/general/commands/CommandDeclaration.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/commands/CommandDeclaration.java index d8d427e67..851a03174 100644 --- a/Core/src/main/java/com/plotsquared/general/commands/CommandDeclaration.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/CommandDeclaration.java @@ -1,29 +1,28 @@ -package com.plotsquared.general.commands; +package com.github.intellectualsites.plotsquared.commands; + +import com.github.intellectualsites.plotsquared.plot.commands.CommandCategory; +import com.github.intellectualsites.plotsquared.plot.commands.RequiredType; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import com.intellectualcrafters.plot.commands.CommandCategory; -import com.intellectualcrafters.plot.commands.RequiredType; - -@Target({ElementType.TYPE,ElementType.METHOD}) -@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface CommandDeclaration { - + String command(); - + String[] aliases() default {}; - + String permission() default ""; - + String usage() default ""; - + String description() default ""; - + RequiredType requiredType() default RequiredType.NONE; - + CommandCategory category() default CommandCategory.INFO; boolean confirmation() default false; diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/Configuration.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/Configuration.java similarity index 93% rename from Core/src/main/java/com/intellectualcrafters/configuration/Configuration.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/Configuration.java index 71ad38983..c2b4b4d95 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/Configuration.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/Configuration.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.configuration; +package com.github.intellectualsites.plotsquared.configuration; import java.util.Map; @@ -8,23 +8,23 @@ import java.util.Map; public interface Configuration extends ConfigurationSection { /** * Sets the default value of the given path as provided. - * + *

*

If no source {@link Configuration} was provided as a default * collection, then a new {@link MemoryConfiguration} will be created to * hold the new default value.

- * + *

*

If value is null, the value will be removed from the default * Configuration source.

* - * @param path Path of the value to set. + * @param path Path of the value to set. * @param value Value to set the default to. * @throws IllegalArgumentException Thrown if path is null. */ @Override void addDefault(String path, Object value); - + /** * Sets the default values of the given paths as provided. - * + *

*

If no source {@link Configuration} was provided as a default * collection, then a new {@link MemoryConfiguration} will be created to * hold the new default values.

@@ -33,14 +33,14 @@ public interface Configuration extends ConfigurationSection { * @throws IllegalArgumentException Thrown if defaults is null. */ void addDefaults(Map defaults); - + /** * Sets the default values of the given paths as provided. - * + *

*

If no source {@link Configuration} was provided as a default * collection, then a new {@link MemoryConfiguration} will be created to * hold the new default value.

- * + *

*

This method will not hold a reference to the specified Configuration, * nor will it automatically update if that Configuration ever changes. If * you check this, you should set the default source with {@link @@ -50,10 +50,10 @@ public interface Configuration extends ConfigurationSection { * @throws IllegalArgumentException Thrown if defaults is null or this. */ void addDefaults(Configuration defaults); - + /** * Gets the source {@link Configuration} for this configuration. - * + *

*

* If no configuration source was set, but default values were added, then * a {@link MemoryConfiguration} will be returned. If no source was set @@ -62,10 +62,10 @@ public interface Configuration extends ConfigurationSection { * @return Configuration source for default values, or null if none exist. */ Configuration getDefaults(); - + /** * Sets the source of all default values for this {@link Configuration}. - * + *

*

* If a previous source was set, or previous default values were defined, * then they will not be copied to the new source.

@@ -77,7 +77,7 @@ public interface Configuration extends ConfigurationSection { /** * Gets the {@link ConfigurationOptions} for this {@link Configuration}. - * + *

*

All setters through this method are chainable.

* * @return Options for this configuration diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationOptions.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/ConfigurationOptions.java similarity index 97% rename from Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationOptions.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/ConfigurationOptions.java index 445d1e938..5d13920e4 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationOptions.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/ConfigurationOptions.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.configuration; +package com.github.intellectualsites.plotsquared.configuration; /** * Various settings for controlling the input and output of a {@link @@ -8,11 +8,11 @@ class ConfigurationOptions { private final Configuration configuration; private char pathSeparator = '.'; private boolean copyDefaults = false; - + protected ConfigurationOptions(Configuration configuration) { this.configuration = configuration; } - + /** * Returns the {@link Configuration} that this object is responsible for. * @@ -21,7 +21,7 @@ class ConfigurationOptions { public Configuration configuration() { return configuration; } - + /** * Gets the char that will be used to separate {@link * ConfigurationSection}s. @@ -34,7 +34,7 @@ class ConfigurationOptions { public char pathSeparator() { return pathSeparator; } - + /** * Sets the char that will be used to separate {@link * ConfigurationSection}s. @@ -49,7 +49,7 @@ class ConfigurationOptions { pathSeparator = value; return this; } - + /** * Checks if the {@link Configuration} should copy values from its default * {@link Configuration} directly. @@ -67,7 +67,7 @@ class ConfigurationOptions { public boolean copyDefaults() { return copyDefaults; } - + /** * Sets if the {@link Configuration} should copy values from its default * {@link Configuration} directly. diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/ConfigurationSection.java similarity index 95% rename from Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/ConfigurationSection.java index 496a2775a..0752dfb57 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/ConfigurationSection.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/ConfigurationSection.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.configuration; +package com.github.intellectualsites.plotsquared.configuration; import java.util.List; import java.util.Map; @@ -20,7 +20,7 @@ public interface ConfigurationSection { * direct children, and not their own children. * * @param deep Whether or not to get a deep list, as opposed to a shallow - * list. + * list. * @return Set of keys contained within this ConfigurationSection. */ Set getKeys(boolean deep); @@ -36,7 +36,7 @@ public interface ConfigurationSection { * values of any direct children, and not their own children. * * @param deep Whether or not to get a deep list, as opposed to a shallow - * list. + * list. * @return Map of keys and values of this section. */ Map getValues(boolean deep); @@ -49,7 +49,7 @@ public interface ConfigurationSection { * * @param path Path to check for existence. * @return True if this section contains the requested path, either via - * default or being set. + * default or being set. * @throws IllegalArgumentException Thrown when path is {@code null}. */ boolean contains(String path); @@ -63,7 +63,7 @@ public interface ConfigurationSection { * * @param path Path to check for existence. * @return True if this section contains the requested path, regardless of - * having a default. + * having a default. * @throws IllegalArgumentException Thrown when path is {@code null}. */ boolean isSet(String path); @@ -147,7 +147,7 @@ public interface ConfigurationSection { * returned regardless of if a default has been identified in the root * {@link Configuration}. * - * @param path Path of the Object to get. + * @param path Path of the Object to get. * @param defaultValue The default value to return if the path is not found. * @return Requested Object. */ @@ -164,7 +164,7 @@ public interface ConfigurationSection { * you to store {@link Configuration}s or {@link ConfigurationSection}s, * please use {@link #createSection(String)} for that. * - * @param path Path of the object to set. + * @param path Path of the object to set. * @param value New value to set the path to. */ void set(String path, Object value); @@ -190,7 +190,7 @@ public interface ConfigurationSection { * be orphaned. * * @param path Path to create the section at. - * @param map The values to used. + * @param map The values to used. * @return Newly created section */ ConfigurationSection createSection(String path, Map map); @@ -218,8 +218,8 @@ public interface ConfigurationSection { * {@link Configuration}. * * @param path Path of the String to get. - * @param def The default value to return if the path is not found or is - * not a String. + * @param def The default value to return if the path is not found or is + * not a String. * @return Requested String. */ String getString(String path, String def); @@ -257,8 +257,8 @@ public interface ConfigurationSection { * {@link Configuration}. * * @param path Path of the int to get. - * @param def The default value to return if the path is not found or is - * not an int. + * @param def The default value to return if the path is not found or is + * not an int. * @return Requested int. */ int getInt(String path, int def); @@ -296,9 +296,9 @@ public interface ConfigurationSection { * returned regardless of if a default has been identified in the root * {@link Configuration}. * - * @param path Path of the boolean to get. + * @param path Path of the boolean to get. * @param defaultValue The default value to return if the path is not found or is - * not a boolean. + * not a boolean. * @return Requested boolean. */ boolean getBoolean(String path, boolean defaultValue); @@ -336,9 +336,9 @@ public interface ConfigurationSection { * returned regardless of if a default has been identified in the root * {@link Configuration}. * - * @param path Path of the double to get. + * @param path Path of the double to get. * @param defaultValue The default value to return if the path is not found or is - * not a double. + * not a double. * @return Requested double. */ double getDouble(String path, double defaultValue); @@ -377,8 +377,8 @@ public interface ConfigurationSection { * {@link Configuration}. * * @param path Path of the long to get. - * @param def The default value to return if the path is not found or is - * not a long. + * @param def The default value to return if the path is not found or is + * not a long. * @return Requested long. */ long getLong(String path, long def); @@ -419,8 +419,8 @@ public interface ConfigurationSection { * {@link Configuration}. * * @param path Path of the List to get. - * @param def The default value to return if the path is not found or is - * not a List. + * @param def The default value to return if the path is not found or is + * not a List. * @return Requested List. */ List getList(String path, List def); @@ -640,7 +640,7 @@ public interface ConfigurationSection { * {@code null}, then this will create a new section at the path, * replacing anything that may have existed there previously. * - * @param path Path of the value to set + * @param path Path of the value to set * @param value Value to set the default to * @throws IllegalArgumentException Thrown if path is {@code null} */ diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/InvalidConfigurationException.java similarity index 79% rename from Core/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/InvalidConfigurationException.java index f98b241af..e9c099ed1 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/InvalidConfigurationException.java @@ -1,17 +1,17 @@ -package com.intellectualcrafters.configuration; +package com.github.intellectualsites.plotsquared.configuration; /** * Exception thrown when attempting to load an invalid {@link Configuration}. */ -@SuppressWarnings("serial") -public class InvalidConfigurationException extends Exception { - +@SuppressWarnings("serial") public class InvalidConfigurationException extends Exception { + /** * Creates a new instance of InvalidConfigurationException without a * message or cause. */ - public InvalidConfigurationException() {} - + public InvalidConfigurationException() { + } + /** * Constructs an instance of InvalidConfigurationException with the * specified message. @@ -21,7 +21,7 @@ public class InvalidConfigurationException extends Exception { public InvalidConfigurationException(String msg) { super(msg); } - + /** * Constructs an instance of InvalidConfigurationException with the * specified cause. @@ -31,13 +31,13 @@ public class InvalidConfigurationException extends Exception { public InvalidConfigurationException(Throwable cause) { super(cause); } - + /** * Constructs an instance of InvalidConfigurationException with the * specified message and cause. * * @param cause The cause of the exception. - * @param msg The details of the exception. + * @param msg The details of the exception. */ public InvalidConfigurationException(String msg, Throwable cause) { super(msg, cause); diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemoryConfiguration.java similarity index 73% rename from Core/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemoryConfiguration.java index 7d1a5721a..20131cbe1 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemoryConfiguration.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.configuration; +package com.github.intellectualsites.plotsquared.configuration; import java.util.Map; @@ -10,12 +10,13 @@ import java.util.Map; public class MemoryConfiguration extends MemorySection implements Configuration { protected Configuration defaults; protected MemoryConfigurationOptions options; - + /** * Creates an empty {@link MemoryConfiguration} with no default values. */ - public MemoryConfiguration() {} - + public MemoryConfiguration() { + } + /** * Creates an empty {@link MemoryConfiguration} using the specified {@link * Configuration} as a source for all default values. @@ -26,49 +27,42 @@ public class MemoryConfiguration extends MemorySection implements Configuration public MemoryConfiguration(Configuration defaults) { this.defaults = defaults; } - - @Override - public void addDefault(String path, Object value) { + + @Override public void addDefault(String path, Object value) { if (this.defaults == null) { this.defaults = new MemoryConfiguration(); } this.defaults.set(path, value); } - - @Override - public void addDefaults(Map defaults) { + + @Override public void addDefaults(Map defaults) { for (Map.Entry entry : defaults.entrySet()) { addDefault(entry.getKey(), entry.getValue()); } } - - @Override - public void addDefaults(Configuration defaults) { + + @Override public void addDefaults(Configuration defaults) { addDefaults(defaults.getValues(true)); } - - @Override - public Configuration getDefaults() { + + @Override public Configuration getDefaults() { return this.defaults; } - @Override - public void setDefaults(Configuration defaults) { + @Override public void setDefaults(Configuration defaults) { if (defaults == null) { throw new NullPointerException("Defaults may not be null"); } this.defaults = defaults; } - - @Override - public ConfigurationSection getParent() { + + @Override public ConfigurationSection getParent() { return null; } - - @Override - public MemoryConfigurationOptions options() { + + @Override public MemoryConfigurationOptions options() { if (this.options == null) { this.options = new MemoryConfigurationOptions(this); } diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemoryConfigurationOptions.java similarity index 62% rename from Core/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemoryConfigurationOptions.java index b2df5e134..971ea1e70 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemoryConfigurationOptions.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.configuration; +package com.github.intellectualsites.plotsquared.configuration; /** * Various settings for controlling the input and output of a {@link @@ -8,20 +8,17 @@ public class MemoryConfigurationOptions extends ConfigurationOptions { protected MemoryConfigurationOptions(MemoryConfiguration configuration) { super(configuration); } - - @Override - public MemoryConfiguration configuration() { + + @Override public MemoryConfiguration configuration() { return (MemoryConfiguration) super.configuration(); } - - @Override - public MemoryConfigurationOptions copyDefaults(boolean value) { + + @Override public MemoryConfigurationOptions copyDefaults(boolean value) { super.copyDefaults(value); return this; } - - @Override - public MemoryConfigurationOptions pathSeparator(char value) { + + @Override public MemoryConfigurationOptions pathSeparator(char value) { super.pathSeparator(value); return this; } diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/MemorySection.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemorySection.java similarity index 82% rename from Core/src/main/java/com/intellectualcrafters/configuration/MemorySection.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemorySection.java index 86fd77acd..0f87931f4 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/MemorySection.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/MemorySection.java @@ -1,11 +1,6 @@ -package com.intellectualcrafters.configuration; +package com.github.intellectualsites.plotsquared.configuration; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; /** * A type of {@link ConfigurationSection} that is stored in memory. @@ -26,11 +21,12 @@ public class MemorySection implements ConfigurationSection { * will throw an exception! * * @throws IllegalStateException Thrown if this is not a {@link - * Configuration} root. + * Configuration} root. */ protected MemorySection() { if (!(this instanceof Configuration)) { - throw new IllegalStateException("Cannot construct a root MemorySection when not a Configuration"); + throw new IllegalStateException( + "Cannot construct a root MemorySection when not a Configuration"); } this.path = ""; @@ -43,10 +39,10 @@ public class MemorySection implements ConfigurationSection { * Creates an empty MemorySection with the specified parent and path. * * @param parent Parent section that contains this own section. - * @param path Path that you may access this section from via the root - * {@link Configuration}. + * @param path Path that you may access this section from via the root + * {@link Configuration}. * @throws IllegalArgumentException Thrown is parent or path is null, or - * if parent contains no root Configuration. + * if parent contains no root Configuration. */ protected MemorySection(ConfigurationSection parent, String path) { this.path = path; @@ -122,7 +118,7 @@ public class MemorySection implements ConfigurationSection { * only {@link MemorySection}. * * @param section Section to create a path for. - * @param key Name of the specified section. + * @param key Name of the specified section. * @return Full path of the section from its root. */ public static String createPath(ConfigurationSection section, String key) { @@ -136,12 +132,13 @@ public class MemorySection implements ConfigurationSection { *

You may use this method for any given {@link ConfigurationSection}, not * only {@link MemorySection}. * - * @param section Section to create a path for. - * @param key Name of the specified section. + * @param section Section to create a path for. + * @param key Name of the specified section. * @param relativeTo Section to create the path relative to. * @return Full path of the section from its root. */ - public static String createPath(ConfigurationSection section, String key, ConfigurationSection relativeTo) { + public static String createPath(ConfigurationSection section, String key, + ConfigurationSection relativeTo) { Configuration root = section.getRoot(); if (root == null) { throw new IllegalStateException("Cannot create path without a root"); @@ -149,7 +146,8 @@ public class MemorySection implements ConfigurationSection { char separator = root.options().pathSeparator(); StringBuilder builder = new StringBuilder(); - for (ConfigurationSection parent = section; (parent != null) && (parent != relativeTo); parent = parent.getParent()) { + for (ConfigurationSection parent = section; + (parent != null) && (parent != relativeTo); parent = parent.getParent()) { if (builder.length() > 0) { builder.insert(0, separator); } @@ -168,8 +166,7 @@ public class MemorySection implements ConfigurationSection { return builder.toString(); } - @Override - public Set getKeys(boolean deep) { + @Override public Set getKeys(boolean deep) { Set result = new LinkedHashSet<>(); Configuration root = getRoot(); @@ -186,8 +183,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public Map getValues(boolean deep) { + @Override public Map getValues(boolean deep) { Map result = new LinkedHashMap<>(); Configuration root = getRoot(); @@ -204,13 +200,11 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public boolean contains(String path) { + @Override public boolean contains(String path) { return get(path) != null; } - @Override - public boolean isSet(String path) { + @Override public boolean isSet(String path) { Configuration root = getRoot(); if (root == null) { return false; @@ -221,40 +215,35 @@ public class MemorySection implements ConfigurationSection { return get(path, null) != null; } - @Override - public String getCurrentPath() { + @Override public String getCurrentPath() { return this.fullPath; } - @Override - public String getName() { + @Override public String getName() { return this.path; } - @Override - public Configuration getRoot() { + @Override public Configuration getRoot() { return this.root; } - @Override - public ConfigurationSection getParent() { + @Override public ConfigurationSection getParent() { return this.parent; } - @Override - public void addDefault(String path, Object value) { + @Override public void addDefault(String path, Object value) { Configuration root = getRoot(); if (root == null) { throw new IllegalStateException("Cannot add default without root"); } if (root == this) { - throw new UnsupportedOperationException("Unsupported addDefault(String, Object) implementation"); + throw new UnsupportedOperationException( + "Unsupported addDefault(String, Object) implementation"); } root.addDefault(createPath(this, path), value); } - @Override - public ConfigurationSection getDefaultSection() { + @Override public ConfigurationSection getDefaultSection() { Configuration root = getRoot(); Configuration defaults = root == null ? null : root.getDefaults(); @@ -267,8 +256,7 @@ public class MemorySection implements ConfigurationSection { return null; } - @Override - public void set(String path, Object value) { + @Override public void set(String path, Object value) { Configuration root = getRoot(); if (root == null) { throw new IllegalStateException("Cannot use section without a root"); @@ -302,13 +290,11 @@ public class MemorySection implements ConfigurationSection { } } - @Override - public Object get(String path) { + @Override public Object get(String path) { return get(path, getDefault(path)); } - @Override - public Object get(String path, Object defaultValue) { + @Override public Object get(String path, Object defaultValue) { if (path == null) { throw new NullPointerException("Path cannot be null"); } @@ -347,8 +333,7 @@ public class MemorySection implements ConfigurationSection { return section.get(key, defaultValue); } - @Override - public ConfigurationSection createSection(String path) { + @Override public ConfigurationSection createSection(String path) { Configuration root = getRoot(); if (root == null) { throw new IllegalStateException("Cannot create section without a root"); @@ -379,8 +364,7 @@ public class MemorySection implements ConfigurationSection { return section.createSection(key); } - @Override - public ConfigurationSection createSection(String path, Map map) { + @Override public ConfigurationSection createSection(String path, Map map) { ConfigurationSection section = createSection(path); for (Map.Entry entry : map.entrySet()) { @@ -395,14 +379,12 @@ public class MemorySection implements ConfigurationSection { } // Primitives - @Override - public String getString(String path) { + @Override public String getString(String path) { Object def = getDefault(path); return getString(path, def != null ? def.toString() : null); } - @Override - public String getString(String path, String def) { + @Override public String getString(String path, String def) { Object val = get(path, def); if (val != null) { return val.toString(); @@ -411,32 +393,27 @@ public class MemorySection implements ConfigurationSection { } } - @Override - public boolean isString(String path) { + @Override public boolean isString(String path) { Object val = get(path); return val instanceof String; } - @Override - public int getInt(String path) { + @Override public int getInt(String path) { Object def = getDefault(path); return getInt(path, toInt(def, 0)); } - @Override - public int getInt(String path, int def) { + @Override public int getInt(String path, int def) { Object val = get(path, def); return toInt(val, def); } - @Override - public boolean isInt(String path) { + @Override public boolean isInt(String path) { Object val = get(path); return val instanceof Integer; } - @Override - public boolean getBoolean(String path) { + @Override public boolean getBoolean(String path) { Object def = getDefault(path); if (def instanceof Boolean) { return getBoolean(path, (Boolean) def); @@ -445,8 +422,7 @@ public class MemorySection implements ConfigurationSection { } } - @Override - public boolean getBoolean(String path, boolean defaultValue) { + @Override public boolean getBoolean(String path, boolean defaultValue) { Object val = get(path, defaultValue); if (val instanceof Boolean) { return (Boolean) val; @@ -455,69 +431,58 @@ public class MemorySection implements ConfigurationSection { } } - @Override - public boolean isBoolean(String path) { + @Override public boolean isBoolean(String path) { Object val = get(path); return val instanceof Boolean; } - @Override - public double getDouble(String path) { + @Override public double getDouble(String path) { Object def = getDefault(path); return getDouble(path, toDouble(def, 0)); } - @Override - public double getDouble(String path, double defaultValue) { + @Override public double getDouble(String path, double defaultValue) { Object val = get(path, defaultValue); return toDouble(val, defaultValue); } - @Override - public boolean isDouble(String path) { + @Override public boolean isDouble(String path) { Object val = get(path); return val instanceof Double; } - @Override - public long getLong(String path) { + @Override public long getLong(String path) { Object def = getDefault(path); return getLong(path, toLong(def, 0)); } - @Override - public long getLong(String path, long def) { + @Override public long getLong(String path, long def) { Object val = get(path, def); return toLong(val, def); } - @Override - public boolean isLong(String path) { + @Override public boolean isLong(String path) { Object val = get(path); return val instanceof Long; } // Java - @Override - public List getList(String path) { + @Override public List getList(String path) { Object def = getDefault(path); return getList(path, def instanceof List ? (List) def : null); } - @Override - public List getList(String path, List def) { + @Override public List getList(String path, List def) { Object val = get(path, def); return (List) ((val instanceof List) ? val : def); } - @Override - public boolean isList(String path) { + @Override public boolean isList(String path) { Object val = get(path); return val instanceof List; } - @Override - public List getStringList(String path) { + @Override public List getStringList(String path) { List list = getList(path); if (list == null) { @@ -535,8 +500,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public List getIntegerList(String path) { + @Override public List getIntegerList(String path) { List list = getList(path); List result = new ArrayList<>(); @@ -559,8 +523,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public List getBooleanList(String path) { + @Override public List getBooleanList(String path) { List list = getList(path); List result = new ArrayList<>(); @@ -580,8 +543,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public List getDoubleList(String path) { + @Override public List getDoubleList(String path) { List list = getList(path); List result = new ArrayList<>(); @@ -604,8 +566,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public List getFloatList(String path) { + @Override public List getFloatList(String path) { List list = getList(path); List result = new ArrayList<>(); @@ -628,8 +589,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public List getLongList(String path) { + @Override public List getLongList(String path) { List list = getList(path); List result = new ArrayList<>(); @@ -652,8 +612,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public List getByteList(String path) { + @Override public List getByteList(String path) { List list = getList(path); List result = new ArrayList<>(); @@ -676,8 +635,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public List getCharacterList(String path) { + @Override public List getCharacterList(String path) { List list = getList(path); List result = new ArrayList<>(); @@ -699,8 +657,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public List getShortList(String path) { + @Override public List getShortList(String path) { List list = getList(path); List result = new ArrayList<>(); @@ -723,8 +680,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public List> getMapList(String path) { + @Override public List> getMapList(String path) { List list = getList(path); List> result = new ArrayList<>(); @@ -737,8 +693,7 @@ public class MemorySection implements ConfigurationSection { return result; } - @Override - public ConfigurationSection getConfigurationSection(String path) { + @Override public ConfigurationSection getConfigurationSection(String path) { Object val = get(path, null); if (val != null) { return (val instanceof ConfigurationSection) ? (ConfigurationSection) val : null; @@ -748,21 +703,15 @@ public class MemorySection implements ConfigurationSection { return (val instanceof ConfigurationSection) ? createSection(path) : null; } - @Override - public boolean isConfigurationSection(String path) { + @Override public boolean isConfigurationSection(String path) { Object val = get(path); return val instanceof ConfigurationSection; } protected boolean isPrimitiveWrapper(Object input) { - return (input instanceof Integer) - || (input instanceof Boolean) - || (input instanceof Character) - || (input instanceof Byte) - || (input instanceof Short) - || (input instanceof Double) - || (input instanceof Long) - || (input instanceof Float); + return (input instanceof Integer) || (input instanceof Boolean) + || (input instanceof Character) || (input instanceof Byte) || (input instanceof Short) + || (input instanceof Double) || (input instanceof Long) || (input instanceof Float); } protected Object getDefault(String path) { @@ -792,7 +741,8 @@ public class MemorySection implements ConfigurationSection { } } - protected void mapChildrenValues(Map output, ConfigurationSection section, boolean deep) { + protected void mapChildrenValues(Map output, ConfigurationSection section, + boolean deep) { if (section instanceof MemorySection) { MemorySection sec = (MemorySection) section; @@ -814,13 +764,14 @@ public class MemorySection implements ConfigurationSection { } } - @Override - public String toString() { + @Override public String toString() { Configuration root = getRoot(); if (root == null) { - return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + null + "']"; + return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + null + + "']"; } else { - return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + root.getClass().getSimpleName() + "']"; + return getClass().getSimpleName() + "[path='" + getCurrentPath() + "', root='" + root + .getClass().getSimpleName() + "']"; } } } diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfiguration.java similarity index 78% rename from Core/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfiguration.java index 2c4f61991..668509bf3 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfiguration.java @@ -1,19 +1,10 @@ -package com.intellectualcrafters.configuration.file; +package com.github.intellectualsites.plotsquared.configuration.file; -import com.intellectualcrafters.configuration.Configuration; -import com.intellectualcrafters.configuration.InvalidConfigurationException; -import com.intellectualcrafters.configuration.MemoryConfiguration; +import com.github.intellectualsites.plotsquared.configuration.Configuration; +import com.github.intellectualsites.plotsquared.configuration.InvalidConfigurationException; +import com.github.intellectualsites.plotsquared.configuration.MemoryConfiguration; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.Writer; +import java.io.*; import java.nio.charset.StandardCharsets; /** @@ -25,8 +16,9 @@ public abstract class FileConfiguration extends MemoryConfiguration { /** * Creates an empty {@link FileConfiguration} with no default values. */ - FileConfiguration() {} - + FileConfiguration() { + } + /** * Creates an empty {@link FileConfiguration} using the specified {@link * Configuration} as a source for all default values. @@ -36,7 +28,7 @@ public abstract class FileConfiguration extends MemoryConfiguration { public FileConfiguration(Configuration defaults) { super(defaults); } - + /** * Saves this {@link FileConfiguration} to the specified location. * @@ -49,7 +41,7 @@ public abstract class FileConfiguration extends MemoryConfiguration { * * @param file File to save to. * @throws IOException Thrown when the given file cannot be written to for - * any reason. + * any reason. */ public void save(File file) throws IOException { File parent = file.getParentFile(); @@ -59,7 +51,8 @@ public abstract class FileConfiguration extends MemoryConfiguration { String data = saveToString(); - try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) { + try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), + StandardCharsets.UTF_8)) { writer.write(data); } } @@ -70,7 +63,7 @@ public abstract class FileConfiguration extends MemoryConfiguration { * @return String containing this configuration. */ public abstract String saveToString(); - + /** * Loads this {@link FileConfiguration} from the specified location. * @@ -82,17 +75,17 @@ public abstract class FileConfiguration extends MemoryConfiguration { * thrown. * * @param file File to load from. - * @throws FileNotFoundException Thrown when the given file cannot be - * opened. - * @throws IOException Thrown when the given file cannot be read. + * @throws FileNotFoundException Thrown when the given file cannot be + * opened. + * @throws IOException Thrown when the given file cannot be read. * @throws InvalidConfigurationException Thrown when the given file is not - * a valid Configuration. - * @throws IllegalArgumentException Thrown when file is null. + * a valid Configuration. + * @throws IllegalArgumentException Thrown when file is null. */ public void load(File file) throws IOException, InvalidConfigurationException { FileInputStream stream = new FileInputStream(file); - + load(new InputStreamReader(stream, StandardCharsets.UTF_8)); } @@ -104,15 +97,17 @@ public abstract class FileConfiguration extends MemoryConfiguration { * from the given stream. * * @param reader the reader to load from - * @throws IOException thrown when underlying reader throws an IOException + * @throws IOException thrown when underlying reader throws an IOException * @throws InvalidConfigurationException thrown when the reader does not - * represent a valid Configuration + * represent a valid Configuration */ public void load(Reader reader) throws IOException, InvalidConfigurationException { StringBuilder builder = new StringBuilder(); - try (BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader)) { + try (BufferedReader input = reader instanceof BufferedReader ? + (BufferedReader) reader : + new BufferedReader(reader)) { String line; while ((line = input.readLine()) != null) { @@ -120,7 +115,7 @@ public abstract class FileConfiguration extends MemoryConfiguration { builder.append('\n'); } } - + loadFromString(builder.toString()); } @@ -136,10 +131,10 @@ public abstract class FileConfiguration extends MemoryConfiguration { * * @param contents Contents of a Configuration to load. * @throws InvalidConfigurationException Thrown if the specified string is - * invalid. + * invalid. */ public abstract void loadFromString(String contents) throws InvalidConfigurationException; - + /** * Compiles the header for this {@link FileConfiguration} and returns the * result. @@ -151,9 +146,8 @@ public abstract class FileConfiguration extends MemoryConfiguration { * @return Compiled header */ protected abstract String buildHeader(); - - @Override - public FileConfigurationOptions options() { + + @Override public FileConfigurationOptions options() { if (this.options == null) { this.options = new FileConfigurationOptions(this); } diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfigurationOptions.java similarity index 86% rename from Core/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfigurationOptions.java index a2c1c19e6..a216d0566 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfigurationOptions.java @@ -1,8 +1,8 @@ -package com.intellectualcrafters.configuration.file; +package com.github.intellectualsites.plotsquared.configuration.file; -import com.intellectualcrafters.configuration.Configuration; -import com.intellectualcrafters.configuration.MemoryConfiguration; -import com.intellectualcrafters.configuration.MemoryConfigurationOptions; +import com.github.intellectualsites.plotsquared.configuration.Configuration; +import com.github.intellectualsites.plotsquared.configuration.MemoryConfiguration; +import com.github.intellectualsites.plotsquared.configuration.MemoryConfigurationOptions; /** * Various settings for controlling the input and output of a {@link @@ -11,28 +11,25 @@ import com.intellectualcrafters.configuration.MemoryConfigurationOptions; public class FileConfigurationOptions extends MemoryConfigurationOptions { private String header = null; private boolean copyHeader = true; - + protected FileConfigurationOptions(MemoryConfiguration configuration) { super(configuration); } - - @Override - public FileConfiguration configuration() { + + @Override public FileConfiguration configuration() { return (FileConfiguration) super.configuration(); } - - @Override - public FileConfigurationOptions copyDefaults(boolean value) { + + @Override public FileConfigurationOptions copyDefaults(boolean value) { super.copyDefaults(value); return this; } - - @Override - public FileConfigurationOptions pathSeparator(char value) { + + @Override public FileConfigurationOptions pathSeparator(char value) { super.pathSeparator(value); return this; } - + /** * Gets the header that will be applied to the top of the saved output. * @@ -50,7 +47,7 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions { public String header() { return header; } - + /** * Sets the header that will be applied to the top of the saved output. * @@ -70,7 +67,7 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions { header = value; return this; } - + /** * Gets whether or not the header should be copied from a default source. * @@ -91,7 +88,7 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions { public boolean copyHeader() { return copyHeader; } - + /** * Sets whether or not the header should be copied from a default source. * @@ -112,7 +109,7 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions { */ public FileConfigurationOptions copyHeader(boolean value) { copyHeader = value; - + return this; } } diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConfiguration.java similarity index 85% rename from Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConfiguration.java index ae158f938..d8c41c3da 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConfiguration.java @@ -1,9 +1,9 @@ -package com.intellectualcrafters.configuration.file; +package com.github.intellectualsites.plotsquared.configuration.file; -import com.intellectualcrafters.configuration.Configuration; -import com.intellectualcrafters.configuration.ConfigurationSection; -import com.intellectualcrafters.configuration.InvalidConfigurationException; -import com.intellectualcrafters.plot.PS; +import com.github.intellectualsites.plotsquared.configuration.Configuration; +import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection; +import com.github.intellectualsites.plotsquared.configuration.InvalidConfigurationException; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.error.YAMLException; @@ -51,11 +51,11 @@ public class YamlConfiguration extends FileConfiguration { dest = new File(file.getAbsolutePath() + "_broken_" + i++); } Files.copy(file.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING); - PS.debug("&dCould not read: &7" + file); - PS.debug("&dRenamed to: &7" + dest.getName()); - PS.debug("&c============ Full stacktrace ============"); + PlotSquared.debug("&dCould not read: &7" + file); + PlotSquared.debug("&dRenamed to: &7" + dest.getName()); + PlotSquared.debug("&c============ Full stacktrace ============"); ex.printStackTrace(); - PS.debug("&c========================================="); + PlotSquared.debug("&c========================================="); } catch (IOException e) { e.printStackTrace(); } @@ -64,8 +64,7 @@ public class YamlConfiguration extends FileConfiguration { return config; } - @Override - public String saveToString() { + @Override public String saveToString() { yamlOptions.setIndent(options().indent()); yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); @@ -79,9 +78,8 @@ public class YamlConfiguration extends FileConfiguration { return header + dump; } - - @Override - public void loadFromString(String contents) throws InvalidConfigurationException { + + @Override public void loadFromString(String contents) throws InvalidConfigurationException { Map input; try { @@ -101,7 +99,7 @@ public class YamlConfiguration extends FileConfiguration { convertMapsToSections(input, this); } } - + protected void convertMapsToSections(Map input, ConfigurationSection section) { for (Map.Entry entry : input.entrySet()) { String key = entry.getKey().toString(); @@ -114,7 +112,7 @@ public class YamlConfiguration extends FileConfiguration { } } } - + protected String parseHeader(String input) { String[] lines = input.split("\r?\n", -1); StringBuilder result = new StringBuilder(); @@ -143,9 +141,8 @@ public class YamlConfiguration extends FileConfiguration { return result.toString(); } - - @Override - protected String buildHeader() { + + @Override protected String buildHeader() { String header = options().header(); if (options().copyHeader()) { @@ -182,8 +179,7 @@ public class YamlConfiguration extends FileConfiguration { return builder.toString(); } - @Override - public YamlConfigurationOptions options() { + @Override public YamlConfigurationOptions options() { if (options == null) { options = new YamlConfigurationOptions(this); } diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConfigurationOptions.java similarity index 75% rename from Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConfigurationOptions.java index 242b40640..a17bc3538 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConfigurationOptions.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.configuration.file; +package com.github.intellectualsites.plotsquared.configuration.file; /** * Various settings for controlling the input and output of a {@link @@ -6,40 +6,35 @@ package com.intellectualcrafters.configuration.file; */ public class YamlConfigurationOptions extends FileConfigurationOptions { private int indent = 2; - + YamlConfigurationOptions(YamlConfiguration configuration) { super(configuration); } - - @Override - public YamlConfiguration configuration() { + + @Override public YamlConfiguration configuration() { return (YamlConfiguration) super.configuration(); } - - @Override - public YamlConfigurationOptions copyDefaults(boolean value) { + + @Override public YamlConfigurationOptions copyDefaults(boolean value) { super.copyDefaults(value); return this; } - - @Override - public YamlConfigurationOptions pathSeparator(char value) { + + @Override public YamlConfigurationOptions pathSeparator(char value) { super.pathSeparator(value); return this; } - - @Override - public YamlConfigurationOptions header(String value) { + + @Override public YamlConfigurationOptions header(String value) { super.header(value); return this; } - - @Override - public YamlConfigurationOptions copyHeader(boolean value) { + + @Override public YamlConfigurationOptions copyHeader(boolean value) { super.copyHeader(value); return this; } - + /** * Gets how much spaces should be used to indent each line. * @@ -50,7 +45,7 @@ public class YamlConfigurationOptions extends FileConfigurationOptions { public int indent() { return indent; } - + /** * Sets how much spaces should be used to indent each line. * @@ -66,7 +61,7 @@ public class YamlConfigurationOptions extends FileConfigurationOptions { if (value > 9) { throw new IllegalArgumentException("Indent cannot be greater than 9 characters"); } - + indent = value; return this; } diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConstructor.java similarity index 79% rename from Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConstructor.java index c70ea67b7..1f52f7abb 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlConstructor.java @@ -1,6 +1,6 @@ -package com.intellectualcrafters.configuration.file; +package com.github.intellectualsites.plotsquared.configuration.file; -import com.intellectualcrafters.configuration.serialization.ConfigurationSerialization; +import com.github.intellectualsites.plotsquared.configuration.serialization.ConfigurationSerialization; import org.yaml.snakeyaml.constructor.SafeConstructor; import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.nodes.Node; @@ -10,38 +10,36 @@ import java.util.LinkedHashMap; import java.util.Map; public class YamlConstructor extends SafeConstructor { - + YamlConstructor() { yamlConstructors.put(Tag.MAP, new ConstructCustomObject()); } - + private class ConstructCustomObject extends ConstructYamlMap { - @Override - public Object construct(final Node node) { + @Override public Object construct(final Node node) { if (node.isTwoStepsConstruction()) { throw new YAMLException("Unexpected referential mapping structure. Node: " + node); } - + final Map raw = (Map) super.construct(node); - + if (raw.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) { final Map typed = new LinkedHashMap<>(raw.size()); for (final Map.Entry entry : raw.entrySet()) { typed.put(entry.getKey().toString(), entry.getValue()); } - + try { return ConfigurationSerialization.deserializeObject(typed); } catch (final IllegalArgumentException ex) { throw new YAMLException("Could not deserialize object", ex); } } - + return raw; } - - @Override - public void construct2ndStep(final Node node, final Object object) { + + @Override public void construct2ndStep(final Node node, final Object object) { throw new YAMLException("Unexpected referential mapping structure. Node: " + node); } } diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlRepresenter.java similarity index 56% rename from Core/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlRepresenter.java index e130e5d94..ebe1aebee 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/YamlRepresenter.java @@ -1,8 +1,8 @@ -package com.intellectualcrafters.configuration.file; +package com.github.intellectualsites.plotsquared.configuration.file; -import com.intellectualcrafters.configuration.ConfigurationSection; -import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable; -import com.intellectualcrafters.configuration.serialization.ConfigurationSerialization; +import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection; +import com.github.intellectualsites.plotsquared.configuration.serialization.ConfigurationSerializable; +import com.github.intellectualsites.plotsquared.configuration.serialization.ConfigurationSerialization; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.representer.Representer; @@ -13,24 +13,25 @@ class YamlRepresenter extends Representer { YamlRepresenter() { this.multiRepresenters.put(ConfigurationSection.class, new RepresentConfigurationSection()); - this.multiRepresenters.put(ConfigurationSerializable.class, new RepresentConfigurationSerializable()); + this.multiRepresenters + .put(ConfigurationSerializable.class, new RepresentConfigurationSerializable()); } private class RepresentConfigurationSection extends RepresentMap { - @Override - public Node representData(Object data) { + @Override public Node representData(Object data) { return super.representData(((ConfigurationSection) data).getValues(false)); } } + private class RepresentConfigurationSerializable extends RepresentMap { - @Override - public Node representData(Object data) { + @Override public Node representData(Object data) { ConfigurationSerializable serializable = (ConfigurationSerializable) data; Map values = new LinkedHashMap<>(); - values.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(serializable.getClass())); + values.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, + ConfigurationSerialization.getAlias(serializable.getClass())); values.putAll(serializable.serialize()); return super.representData(values); diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/ConfigurationSerializable.java similarity index 93% rename from Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/ConfigurationSerializable.java index fed1b35b9..f83e7a468 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/ConfigurationSerializable.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.configuration.serialization; +package com.github.intellectualsites.plotsquared.configuration.serialization; import java.util.Map; @@ -21,7 +21,7 @@ import java.util.Map; * @see SerializableAs */ public interface ConfigurationSerializable { - + /** * Creates a Map representation of this class. * diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/ConfigurationSerialization.java similarity index 82% rename from Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/ConfigurationSerialization.java index 92b7edfba..0783b4af5 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/ConfigurationSerialization.java @@ -1,6 +1,6 @@ -package com.intellectualcrafters.configuration.serialization; +package com.github.intellectualsites.plotsquared.configuration.serialization; -import com.intellectualcrafters.configuration.Configuration; +import com.github.intellectualsites.plotsquared.configuration.Configuration; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -17,7 +17,8 @@ import java.util.logging.Logger; public class ConfigurationSerialization { public static final String SERIALIZED_TYPE_KEY = "=="; - private static final Map> aliases = new HashMap<>(); + private static final Map> aliases = + new HashMap<>(); private final Class clazz; protected ConfigurationSerialization(Class clazz) { @@ -27,31 +28,32 @@ public class ConfigurationSerialization { /** * Attempts to deserialize the given arguments into a new instance of the * given class. - * + *

*

The class must implement {@link ConfigurationSerializable}, including * the extra methods as specified in the javadoc of * ConfigurationSerializable.

- * + *

*

If a new instance could not be made, an example being the class not * fully implementing the interface, null will be returned.

* - * @param args Arguments for deserialization + * @param args Arguments for deserialization * @param clazz Class to deserialize into * @return New instance of the specified class */ - public static ConfigurationSerializable deserializeObject(Map args, Class clazz) { + public static ConfigurationSerializable deserializeObject(Map args, + Class clazz) { return new ConfigurationSerialization(clazz).deserialize(args); } /** * Attempts to deserialize the given arguments into a new instance of the - * + *

* given class. *

* The class must implement {@link ConfigurationSerializable}, including * the extra methods as specified in the javadoc of * ConfigurationSerializable.

- * + *

*

* If a new instance could not be made, an example being the class not * fully implementing the interface, null will be returned.

@@ -71,14 +73,16 @@ public class ConfigurationSerialization { } clazz = getClassByAlias(alias); if (clazz == null) { - throw new IllegalArgumentException("Specified class does not exist ('" + alias + "')"); + throw new IllegalArgumentException( + "Specified class does not exist ('" + alias + "')"); } } catch (ClassCastException ex) { ex.fillInStackTrace(); throw ex; } } else { - throw new IllegalArgumentException("Args doesn't contain type key ('" + SERIALIZED_TYPE_KEY + "')"); + throw new IllegalArgumentException( + "Args doesn't contain type key ('" + SERIALIZED_TYPE_KEY + "')"); } return new ConfigurationSerialization(clazz).deserialize(args); @@ -107,7 +111,8 @@ public class ConfigurationSerialization { * @param alias Alias to register as * @see SerializableAs */ - public static void registerClass(Class clazz, String alias) { + public static void registerClass(Class clazz, + String alias) { aliases.put(alias, clazz); } @@ -127,7 +132,8 @@ public class ConfigurationSerialization { * @param clazz Class to unregister */ public static void unregisterClass(Class clazz) { - while (aliases.values().remove(clazz)) {} + while (aliases.values().remove(clazz)) { + } } /** @@ -195,32 +201,35 @@ public class ConfigurationSerialization { protected ConfigurationSerializable deserializeViaMethod(Method method, Map args) { try { - ConfigurationSerializable result = (ConfigurationSerializable) method.invoke(null, args); + ConfigurationSerializable result = + (ConfigurationSerializable) method.invoke(null, args); if (result == null) { Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, - "Could not call method '" + method.toString() + "' of " + this.clazz + " for deserialization: method returned null"); + "Could not call method '" + method.toString() + "' of " + this.clazz + + " for deserialization: method returned null"); } else { return result; } } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ex) { - Logger.getLogger(ConfigurationSerialization.class.getName()) - .log(Level.SEVERE, "Could not call method '" + method.toString() + "' of " + this.clazz - + " for deserialization", - ex instanceof InvocationTargetException ? ex.getCause() : ex); + Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, + "Could not call method '" + method.toString() + "' of " + this.clazz + + " for deserialization", + ex instanceof InvocationTargetException ? ex.getCause() : ex); } return null; } - protected ConfigurationSerializable deserializeViaCtor(Constructor ctor, Map args) { + protected ConfigurationSerializable deserializeViaCtor( + Constructor ctor, Map args) { try { return ctor.newInstance(args); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException ex) { - Logger.getLogger(ConfigurationSerialization.class.getName()) - .log(Level.SEVERE, "Could not call constructor '" + ctor.toString() + "' of " + this.clazz - + " for deserialization", - ex instanceof InvocationTargetException ? ex.getCause() : ex); + Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, + "Could not call constructor '" + ctor.toString() + "' of " + this.clazz + + " for deserialization", + ex instanceof InvocationTargetException ? ex.getCause() : ex); } return null; diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/DelegateDeserialization.java similarity index 79% rename from Core/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/DelegateDeserialization.java index b6676c747..8a071cb2e 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/DelegateDeserialization.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.configuration.serialization; +package com.github.intellectualsites.plotsquared.configuration.serialization; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -9,8 +9,7 @@ import java.lang.annotation.Target; * Applies to a {@link ConfigurationSerializable} that will delegate all * deserialization to another {@link ConfigurationSerializable}. */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface DelegateDeserialization { /** * Which class should be used as a delegate for this classes diff --git a/Core/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/SerializableAs.java similarity index 84% rename from Core/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/SerializableAs.java index 54287571e..79b50998c 100644 --- a/Core/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/SerializableAs.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.configuration.serialization; +package com.github.intellectualsites.plotsquared.configuration.serialization; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -19,9 +19,7 @@ import java.lang.annotation.Target; * * @see ConfigurationSerialization#registerClass(Class, String) */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -public @interface SerializableAs { +@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface SerializableAs { /** * This is the name your class will be stored and retrieved as. *

diff --git a/Core/src/main/java/com/intellectualcrafters/json/CDL.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/CDL.java similarity index 96% rename from Core/src/main/java/com/intellectualcrafters/json/CDL.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/json/CDL.java index e09a05478..003e4cb2c 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/CDL.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/CDL.java @@ -1,16 +1,16 @@ -package com.intellectualcrafters.json; +package com.github.intellectualsites.plotsquared.json; /** * This provides static methods to convert comma delimited text into a JSONArray, and to covert a JSONArray into comma * delimited text. Comma delimited text is a very popular format for data interchange. It is understood by most * database, spreadsheet, and organizer programs. - * + *

* Each row of text represents a row in a table or a data record. Each row ends with a NEWLINE character. Each row * contains one or more values. Values are separated by commas. A value can contain any character except for comma, * unless is is wrapped in single quotes or double quotes. - * + *

* The first row usually contains the names of the columns. - * + *

* A comma delimited list can be converted into a JSONArray of JSONObjects. The names for the elements in the * JSONObjects can be taken from the names in the first row. * @@ -23,9 +23,7 @@ public class CDL { * Get the next value. The value can be wrapped in quotes. The value can be empty. * * @param x A JSONTokener of the source text. - * * @return The value string, or null if empty. - * * @throws JSONException if the quoted string is badly formed. */ private static String getValue(JSONTokener x) throws JSONException { @@ -66,9 +64,7 @@ public class CDL { * Produce a JSONArray of strings from a row of comma delimited values. * * @param x A JSONTokener of the source text. - * * @return A JSONArray of strings. - * * @throws JSONException */ public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException { @@ -102,9 +98,7 @@ public class CDL { * @param names A JSONArray of names. This is commonly obtained from the first row of a comma delimited text file * using the rowToJSONArray method. * @param x A JSONTokener of the source text. - * * @return A JSONObject combining the names and values. - * * @throws JSONException */ public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) throws JSONException { @@ -117,7 +111,6 @@ public class CDL { * Troublesome characters may be removed. * * @param ja A JSONArray of strings. - * * @return A string ending in NEWLINE. */ public static String rowToString(JSONArray ja) { @@ -129,8 +122,9 @@ public class CDL { Object object = ja.opt(i); if (object != null) { String string = object.toString(); - if (!string.isEmpty() && ((string.indexOf(',') >= 0) || (string.indexOf('\n') >= 0) || (string.indexOf('\r') >= 0) || ( - string.indexOf(0) >= 0) || (string.charAt(0) == '"'))) { + if (!string.isEmpty() && ((string.indexOf(',') >= 0) || (string.indexOf('\n') >= 0) + || (string.indexOf('\r') >= 0) || (string.indexOf(0) >= 0) || (string.charAt(0) + == '"'))) { sb.append('"'); int length = string.length(); for (int j = 0; j < length; j += 1) { @@ -153,9 +147,7 @@ public class CDL { * Produce a JSONArray of JSONObjects from a comma delimited text string, using the first row as a source of names. * * @param string The comma delimited text. - * * @return A JSONArray of JSONObjects. - * * @throws JSONException */ public static JSONArray toJSONArray(String string) throws JSONException { @@ -166,9 +158,7 @@ public class CDL { * Produce a JSONArray of JSONObjects from a comma delimited text string, using the first row as a source of names. * * @param x The JSONTokener containing the comma delimited text. - * * @return A JSONArray of JSONObjects. - * * @throws JSONException */ public static JSONArray toJSONArray(JSONTokener x) throws JSONException { @@ -181,9 +171,7 @@ public class CDL { * * @param names A JSONArray of strings. * @param string The comma delimited text. - * * @return A JSONArray of JSONObjects. - * * @throws JSONException */ public static JSONArray toJSONArray(JSONArray names, String string) throws JSONException { @@ -196,9 +184,7 @@ public class CDL { * * @param names A JSONArray of strings. * @param x A JSONTokener of the source text. - * * @return A JSONArray of JSONObjects. - * * @throws JSONException */ public static JSONArray toJSONArray(JSONArray names, JSONTokener x) throws JSONException { @@ -224,9 +210,7 @@ public class CDL { * inspecting the first JSONObject. * * @param ja A JSONArray of JSONObjects. - * * @return A comma delimited text. - * * @throws JSONException */ public static String toString(JSONArray ja) throws JSONException { @@ -246,9 +230,7 @@ public class CDL { * * @param names A JSONArray of strings. * @param ja A JSONArray of JSONObjects. - * * @return A comma delimited text. - * * @throws JSONException */ public static String toString(JSONArray names, JSONArray ja) throws JSONException { diff --git a/Core/src/main/java/com/intellectualcrafters/json/Cookie.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/Cookie.java similarity index 98% rename from Core/src/main/java/com/intellectualcrafters/json/Cookie.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/json/Cookie.java index ef58c8e8a..8e3c7444d 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/Cookie.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/Cookie.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.json; +package com.github.intellectualsites.plotsquared.json; /** * Convert a web browser cookie specification to a JSONObject and back. JSON and Cookies are both notations for @@ -16,7 +16,6 @@ public class Cookie { * encode '=' and ';' because we must. We encode '%' and '+' because they are meta characters in URL encoding. * * @param string The source string. - * * @return The escaped result. */ public static String escape(final String string) { @@ -36,7 +35,7 @@ public class Cookie { } return sb.toString(); } - + /** * Convert a cookie specification string into a JSONObject. The string will contain a name value pair separated by * '='. The name and the value will be unescaped, possibly converting '+' and '%' sequences. The cookie properties @@ -46,9 +45,7 @@ public class Cookie { * JSONObject. * * @param string The cookie specification string. - * * @return A JSONObject containing "name", "value", and possibly other members. - * * @throws JSONException */ public static JSONObject toJSONObject(final String string) throws JSONException { @@ -76,16 +73,14 @@ public class Cookie { } return jo; } - + /** * Convert a JSONObject into a cookie specification string. The JSONObject must contain "name" and "value" members. * If the JSONObject contains "expires", "domain", "path", or "secure" members, they will be appended to the cookie * specification string. All other members are ignored. * * @param jo A JSONObject - * * @return A cookie specification string - * * @throws JSONException */ public static String toString(final JSONObject jo) throws JSONException { @@ -105,13 +100,12 @@ public class Cookie { } return sb.toString(); } - + /** * Convert {@code %}hh sequences to single characters, and convert plus to space. * * @param string A string that may contain {@code +}  (plus) and %hh * sequences. - * * @return The unescaped string. */ public static String unescape(final String string) { diff --git a/Core/src/main/java/com/intellectualcrafters/json/CookieList.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/CookieList.java similarity index 96% rename from Core/src/main/java/com/intellectualcrafters/json/CookieList.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/json/CookieList.java index c0bf0f994..90b51cdd7 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/CookieList.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/CookieList.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.json; +package com.github.intellectualsites.plotsquared.json; import java.util.Iterator; @@ -13,14 +13,12 @@ public class CookieList { * Convert a cookie list into a JSONObject. A cookie list is a sequence of name/value pairs. The names are separated * from the values by '='. The pairs are separated by ';'. The names and the values will be unescaped, possibly * converting '+' and '%' sequences. - * + *

* To add a cookie to a cooklist, cookielistJSONObject.put(cookieJSONObject.getString("name"), * cookieJSONObject.getString("value")); * * @param string A cookie list string - * * @return A JSONObject - * * @throws JSONException */ public static JSONObject toJSONObject(final String string) throws JSONException { @@ -34,16 +32,14 @@ public class CookieList { } return jo; } - + /** * Convert a JSONObject into a cookie list. A cookie list is a sequence of name/value pairs. The names are separated * from the values by '='. The pairs are separated by ';'. The characters '%', '+', '=', and ';' in the names and * values are replaced by "%hh". * * @param jo A JSONObject - * * @return A cookie list string - * * @throws JSONException */ public static String toString(final JSONObject jo) throws JSONException { diff --git a/Core/src/main/java/com/intellectualcrafters/json/HTTP.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/HTTP.java similarity index 92% rename from Core/src/main/java/com/intellectualcrafters/json/HTTP.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/json/HTTP.java index d95995b29..338111da3 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/HTTP.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/HTTP.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.json; +package com.github.intellectualsites.plotsquared.json; import java.util.Iterator; @@ -13,7 +13,7 @@ public class HTTP { * Carriage return/line feed. */ public static final String CRLF = "\r\n"; - + public static JSONObject toJSONObject(final String string) throws JSONException { final JSONObject jo = new JSONObject(); final HTTPTokener x = new HTTPTokener(string); @@ -40,7 +40,7 @@ public class HTTP { } return jo; } - + /** * Convert a JSONObject into an HTTP header. A request header must contain * @@ -52,7 +52,7 @@ public class HTTP { * "HTTP-Version": "HTTP/1.1" (for example) * } * - * + *

* A response header must contain * * @@ -63,13 +63,11 @@ public class HTTP { * "Reason-Phrase": "OK" (for example) * } * - * + *

* Any other members of the JSONObject will be output as HTTP fields. The result will end with two CRLF pairs. * * @param jo A JSONObject - * * @return An HTTP header string. - * * @throws JSONException if the object does not contain enough information. */ public static String toString(final JSONObject jo) throws JSONException { @@ -96,7 +94,9 @@ public class HTTP { sb.append(CRLF); while (keys.hasNext()) { string = keys.next(); - if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase".equals(string) && !"Method".equals(string) && !"Request-URI".equals(string) && !jo.isNull(string)) { + if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase" + .equals(string) && !"Method".equals(string) && !"Request-URI".equals(string) && !jo + .isNull(string)) { sb.append(string); sb.append(": "); sb.append(jo.getString(string)); diff --git a/Core/src/main/java/com/intellectualcrafters/json/HTTPTokener.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/HTTPTokener.java similarity index 92% rename from Core/src/main/java/com/intellectualcrafters/json/HTTPTokener.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/json/HTTPTokener.java index 5a3fb1e56..9ee6548cf 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/HTTPTokener.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/HTTPTokener.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.json; +package com.github.intellectualsites.plotsquared.json; /** * The HTTPTokener extends the JSONTokener to provide additional methods for the parsing of HTTP headers. @@ -15,12 +15,11 @@ public class HTTPTokener extends JSONTokener { public HTTPTokener(final String string) { super(string); } - + /** * Get the next token or string. This is used in parsing HTTP headers. * * @return A String. - * * @throws JSONException */ public String nextToken() throws JSONException { @@ -32,7 +31,7 @@ public class HTTPTokener extends JSONTokener { } while (Character.isWhitespace(c)); if ((c == '"') || (c == '\'')) { q = c; - for (;;) { + for (; ; ) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); @@ -43,7 +42,7 @@ public class HTTPTokener extends JSONTokener { sb.append(c); } } - for (;;) { + for (; ; ) { if ((c == 0) || Character.isWhitespace(c)) { return sb.toString(); } diff --git a/Core/src/main/java/com/intellectualcrafters/json/JSONArray.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONArray.java similarity index 94% rename from Core/src/main/java/com/intellectualcrafters/json/JSONArray.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONArray.java index 32b75bd01..62ee01329 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/JSONArray.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONArray.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.json; +package com.github.intellectualsites.plotsquared.json; import java.io.IOException; import java.io.StringWriter; @@ -41,19 +41,18 @@ public class JSONArray { * The arrayList where the JSONArray's properties are kept. */ private final ArrayList myArrayList; - + /** * Construct an empty JSONArray. */ public JSONArray() { this.myArrayList = new ArrayList(); } - + /** * Construct a JSONArray from a JSONTokener. * * @param x A JSONTokener - * * @throws JSONException If there is a syntax error. */ public JSONArray(JSONTokener x) throws JSONException { @@ -63,7 +62,7 @@ public class JSONArray { } if (x.nextClean() != ']') { x.back(); - for (;;) { + for (; ; ) { if (x.nextClean() == ',') { x.back(); this.myArrayList.add(JSONObject.NULL); @@ -86,19 +85,18 @@ public class JSONArray { } } } - + /** * Construct a JSONArray from a source JSON text. * * @param source A string that begins with {@code [} (left bracket) and ends with * {@code ]}  (right bracket). - * * @throws JSONException If there is a syntax error. */ public JSONArray(String source) throws JSONException { this(new JSONTokener(source)); } - + /** * Construct a JSONArray from a Collection. * @@ -112,7 +110,7 @@ public class JSONArray { } } } - + /** * Construct a JSONArray from an array * @@ -126,17 +124,16 @@ public class JSONArray { this.put(JSONObject.wrap(Array.get(array, i))); } } else { - throw new JSONException("JSONArray initial value should be a string or collection or array."); + throw new JSONException( + "JSONArray initial value should be a string or collection or array."); } } - + /** * Get the object value associated with an index. * * @param index The index must be between 0 and length() - 1. - * * @return An object value. - * * @throws JSONException If there is no value for the index. */ public Object get(int index) throws JSONException { @@ -146,69 +143,67 @@ public class JSONArray { } return object; } - + /** * Get the boolean value associated with an index. The string values "true" and "false" are converted to boolean. * * @param index The index must be between 0 and length() - 1. - * * @return The truth. - * * @throws JSONException If there is no value for the index or if the value is not convertible to boolean. */ public boolean getBoolean(int index) throws JSONException { Object object = get(index); - if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("false"))) { + if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object) + .equalsIgnoreCase("false"))) { return false; - } else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("true"))) { + } else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object) + .equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a boolean."); } - + /** * Get the double value associated with an index. * * @param index The index must be between 0 and length() - 1. - * * @return The value. - * * @throws JSONException If the key is not found or if the value cannot be converted to a number. */ public double getDouble(int index) throws JSONException { Object object = get(index); try { - return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); + return object instanceof Number ? + ((Number) object).doubleValue() : + Double.parseDouble((String) object); } catch (NumberFormatException ignored) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } - + /** * Get the int value associated with an index. * * @param index The index must be between 0 and length() - 1. - * * @return The value. - * * @throws JSONException If the key is not found or if the value is not a number. */ public int getInt(int index) throws JSONException { Object object = get(index); try { - return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); + return object instanceof Number ? + ((Number) object).intValue() : + Integer.parseInt((String) object); } catch (NumberFormatException ignored) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } - + /** * Get the JSONArray associated with an index. * * @param index The index must be between 0 and length() - 1. - * * @return A JSONArray value. - * * @throws JSONException If there is no value for the index. or if the value is not a JSONArray */ public JSONArray getJSONArray(int index) throws JSONException { @@ -218,14 +213,12 @@ public class JSONArray { } throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); } - + /** * Get the JSONObject associated with an index. * * @param index subscript - * * @return A JSONObject value. - * * @throws JSONException If there is no value for the index or if the value is not a JSONObject */ public JSONObject getJSONObject(int index) throws JSONException { @@ -235,32 +228,30 @@ public class JSONArray { } throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); } - + /** * Get the long value associated with an index. * * @param index The index must be between 0 and length() - 1. - * * @return The value. - * * @throws JSONException If the key is not found or if the value cannot be converted to a number. */ public long getLong(int index) throws JSONException { Object object = get(index); try { - return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); + return object instanceof Number ? + ((Number) object).longValue() : + Long.parseLong((String) object); } catch (NumberFormatException ignored) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } - + /** * Get the string associated with an index. * * @param index The index must be between 0 and length() - 1. - * * @return A string value. - * * @throws JSONException If there is no string value for the index. */ public String getString(int index) throws JSONException { @@ -270,26 +261,23 @@ public class JSONArray { } throw new JSONException("JSONArray[" + index + "] not a string."); } - + /** * Determine if the value is null. * * @param index The index must be between 0 and length() - 1. - * * @return true if the value at the index is null, or if there is no value. */ public boolean isNull(int index) { return JSONObject.NULL.equals(opt(index)); } - + /** * Make a string from the contents of this JSONArray. The {@code separator} string is inserted between each * element. Warning: This method assumes that the data structure is acyclical. * * @param separator A string that will be inserted between the elements. - * * @return a string. - * * @throws JSONException If the array contains an invalid number. */ public String join(String separator) throws JSONException { @@ -303,7 +291,7 @@ public class JSONArray { } return sb.toString(); } - + /** * Get the number of elements in the JSONArray, included nulls. * @@ -312,37 +300,34 @@ public class JSONArray { public int length() { return this.myArrayList.size(); } - + /** * Get the optional object value associated with an index. * * @param index The index must be between 0 and length() - 1. - * * @return An object value, or null if there is no object at that index. */ public Object opt(int index) { return ((index < 0) || (index >= length())) ? null : this.myArrayList.get(index); } - + /** * Get the optional boolean value associated with an index. It returns false if there is no value at that index, or * if the value is not Boolean.TRUE or the String "true". * * @param index The index must be between 0 and length() - 1. - * * @return The truth. */ public boolean optBoolean(int index) { return this.optBoolean(index, false); } - + /** * Get the optional boolean value associated with an index. It returns the defaultValue if there is no value at that * index or if it is not a Boolean or the String "true" or "false" (case insensitive). * * @param index The index must be between 0 and length() - 1. * @param defaultValue A boolean default. - * * @return The truth. */ public boolean optBoolean(int index, boolean defaultValue) { @@ -352,26 +337,24 @@ public class JSONArray { return defaultValue; } } - + /** * Get the optional double value associated with an index. NaN is returned if there is no value for the index, or if * the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. - * * @return The value. */ public double optDouble(int index) { return this.optDouble(index, Double.NaN); } - + /** * Get the optional double value associated with an index. The defaultValue is returned if there is no value for the * index, or if the value is not a number and cannot be converted to a number. * * @param index subscript * @param defaultValue The default value. - * * @return The value. */ public double optDouble(int index, double defaultValue) { @@ -381,26 +364,24 @@ public class JSONArray { return defaultValue; } } - + /** * Get the optional int value associated with an index. Zero is returned if there is no value for the index, or if * the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. - * * @return The value. */ public int optInt(int index) { return this.optInt(index, 0); } - + /** * Get the optional int value associated with an index. The defaultValue is returned if there is no value for the * index, or if the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. * @param defaultValue The default value. - * * @return The value. */ public int optInt(int index, int defaultValue) { @@ -410,52 +391,48 @@ public class JSONArray { return defaultValue; } } - + /** * Get the optional JSONArray associated with an index. * * @param index subscript - * * @return A JSONArray value, or null if the index has no value, or if the value is not a JSONArray. */ public JSONArray optJSONArray(int index) { Object o = opt(index); return o instanceof JSONArray ? (JSONArray) o : null; } - + /** * Get the optional JSONObject associated with an index. Null is returned if the key is not found, or null if the * index has no value, or if the value is not a JSONObject. * * @param index The index must be between 0 and length() - 1. - * * @return A JSONObject value. */ public JSONObject optJSONObject(int index) { Object o = opt(index); return o instanceof JSONObject ? (JSONObject) o : null; } - + /** * Get the optional long value associated with an index. Zero is returned if there is no value for the index, or if * the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. - * * @return The value. */ public long optLong(int index) { return this.optLong(index, 0); } - + /** * Get the optional long value associated with an index. The defaultValue * is returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * - * @param index The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @param defaultValue The default value. - * * @return The value. */ public long optLong(int index, long defaultValue) { @@ -465,66 +442,60 @@ public class JSONArray { return defaultValue; } } - + /** * Get the optional string value associated with an index. It returns an * empty string if there is no value at that index. If the value is not a * string and is not null, then it is converted to a string. * * @param index The index must be between 0 and length() - 1. - * * @return A String value. */ public String optString(int index) { return this.optString(index, ""); } - + /** * Get the optional string associated with an index. The defaultValue is * returned if the key is not found. * * @param index The index must be between 0 and length() - 1. * @param defaultValue The default value. - * * @return A String value. */ public String optString(int index, String defaultValue) { Object object = opt(index); return JSONObject.NULL.equals(object) ? defaultValue : object.toString(); } - + /** * Append a boolean value. This increases the array's length by one. * * @param value A boolean value. - * * @return this. */ public JSONArray put(boolean value) { this.put(value ? Boolean.TRUE : Boolean.FALSE); return this; } - + /** * Put a value in the JSONArray, where the value will be a JSONArray which * is produced from a Collection. * * @param value A Collection value. - * * @return this. */ public JSONArray put(Collection value) { this.put(new JSONArray(value)); return this; } - + /** * Append a double value. This increases the array's length by one. * * @param value A double value. - * * @return this. - * * @throws JSONException if the value is not finite. */ public JSONArray put(double value) throws JSONException { @@ -533,90 +504,82 @@ public class JSONArray { this.put(d); return this; } - + /** * Append an int value. This increases the array's length by one. * * @param value An int value. - * * @return this. */ public JSONArray put(int value) { this.put(Integer.valueOf(value)); return this; } - + /** * Append an long value. This increases the array's length by one. * * @param value A long value. - * * @return this. */ public JSONArray put(long value) { this.put(Long.valueOf(value)); return this; } - + /** * Put a value in the JSONArray, where the value will be a JSONObject which * is produced from a Map. * * @param value A Map value. - * * @return this. */ public JSONArray put(Map value) { this.put(new JSONObject(value)); return this; } - + /** * Append an object value. This increases the array's length by one. * * @param value An object value. The value should be a Boolean, Double, - * Integer, JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. - * + * Integer, JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. * @return this. */ public JSONArray put(Object value) { this.myArrayList.add(value); return this; } - + /** * Put or replace a boolean value in the JSONArray. If the index is greater than the length of the JSONArray, then * null elements will be added as necessary to pad it out. * * @param index The subscript. * @param value A boolean value. - * * @return this. - * * @throws JSONException If the index is negative. */ public JSONArray put(int index, boolean value) throws JSONException { this.put(index, value ? Boolean.TRUE : Boolean.FALSE); return this; } - + /** * Put a value in the JSONArray, where the value will be a JSONArray which * is produced from a Collection. * * @param index The subscript. * @param value A Collection value. - * * @return this. - * * @throws JSONException If the index is negative or if the value is not - * finite. + * finite. */ public JSONArray put(int index, Collection value) throws JSONException { this.put(index, new JSONArray(value)); return this; } - + /** * Put or replace a double value. If the index is greater than the length * of the JSONArray, then null elements will be added as necessary to pad @@ -624,66 +587,58 @@ public class JSONArray { * * @param index The subscript. * @param value A double value. - * * @return this. - * * @throws JSONException If the index is negative or if the value is not - * finite. + * finite. */ public JSONArray put(int index, double value) throws JSONException { this.put(index, new Double(value)); return this; } - + /** * Put or replace an int value. If the index is greater than the length of the JSONArray, then null elements will be * added as necessary to pad it out. * * @param index The subscript. * @param value An int value. - * * @return this. - * * @throws JSONException If the index is negative. */ public JSONArray put(int index, int value) throws JSONException { this.put(index, Integer.valueOf(value)); return this; } - + /** * Put or replace a long value. If the index is greater than the length of the JSONArray, then null elements will be * added as necessary to pad it out. * * @param index The subscript. * @param value A long value. - * * @return this. - * * @throws JSONException If the index is negative. */ public JSONArray put(int index, long value) throws JSONException { this.put(index, Long.valueOf(value)); return this; } - + /** * Put a value in the JSONArray, where the value will be a JSONObject that * is produced from a Map. * * @param index The subscript. * @param value The Map value. - * * @return this. - * * @throws JSONException If the index is negative or if the the value is an - * invalid number. + * invalid number. */ public JSONArray put(int index, Map value) throws JSONException { this.put(index, new JSONObject(value)); return this; } - + /** * Put or replace an object value in the JSONArray. If the index is greater than the length of the JSONArray, then * null elements will be added as necessary to pad it out. @@ -691,9 +646,7 @@ public class JSONArray { * @param index The subscript. * @param value The value to put into the array. The value should be a Boolean, Double, Integer, JSONArray, * JSONObject, Long, or String, or the JSONObject.NULL object. - * * @return this. - * * @throws JSONException If the index is negative or if the the value is an invalid number. */ public JSONArray put(int index, Object value) throws JSONException { @@ -711,23 +664,21 @@ public class JSONArray { } return this; } - + /** * Remove an index and close the hole. * * @param index The index of the element to be removed. - * * @return The value that was associated with the index, or null if there was no value. */ public Object remove(int index) { return (index >= 0) && (index < length()) ? this.myArrayList.remove(index) : null; } - + /** * Determine if two JSONArrays are similar. They must contain similar sequences. * * @param other The other JSONArray - * * @return true if they are equal */ public boolean similar(Object other) { @@ -755,14 +706,12 @@ public class JSONArray { } return true; } - + /** * Produce a JSONObject by combining a JSONArray of names with the values of this JSONArray. * * @param names A JSONArray containing a list of key strings. These will be paired with the values. - * * @return A JSONObject, or null if there are no names or if this JSONArray has no values. - * * @throws JSONException If any of the names are null. */ public JSONObject toJSONObject(JSONArray names) throws JSONException { @@ -775,35 +724,32 @@ public class JSONArray { } return jo; } - + /** * Make a JSON text of this JSONArray. For compactness, no unnecessary whitespace is added. If it is not possible to * produce a syntactically correct JSON text then null will be returned instead. This could occur if the array * contains an invalid number. - * + *

* Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, transmittable representation of the array. */ - @Override - public String toString() { + @Override public String toString() { try { return this.toString(0); } catch (JSONException ignored) { return null; } } - + /** * Make a prettyprinted JSON text of this JSONArray. Warning: This method assumes that the data structure is * acyclical. * * @param indentFactor The number of spaces to add to each level of indentation. - * * @return a printable, displayable, transmittable representation of the object, beginning with * {@code [} (left bracket) and ending with {@code ]}  (right * bracket). - * * @throws JSONException */ public String toString(int indentFactor) throws JSONException { @@ -812,30 +758,27 @@ public class JSONArray { return this.write(sw, indentFactor, 0).toString(); } } - + /** * Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is added. - * + *

* Warning: This method assumes that the data structure is acyclical. * * @return The writer. - * * @throws JSONException */ public Writer write(Writer writer) throws JSONException { return this.write(writer, 0, 0); } - + /** * Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is added. - * + *

* Warning: This method assumes that the data structure is acyclical. * * @param indentFactor The number of spaces to add to each level of indentation. * @param indent The indention of the top level. - * * @return The writer. - * * @throws JSONException */ Writer write(Writer writer, int indentFactor, int indent) throws JSONException { diff --git a/Core/src/main/java/com/intellectualcrafters/json/JSONException.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONException.java similarity index 90% rename from Core/src/main/java/com/intellectualcrafters/json/JSONException.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONException.java index 0d2acb352..67de10815 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/JSONException.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONException.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.json; +package com.github.intellectualsites.plotsquared.json; /** * The JSONException is thrown by the JSON.org classes when things are amiss. @@ -9,7 +9,7 @@ package com.intellectualcrafters.json; public class JSONException extends RuntimeException { private static final long serialVersionUID = 0; private Throwable cause; - + /** * Constructs a JSONException with an explanatory message. * @@ -18,7 +18,7 @@ public class JSONException extends RuntimeException { public JSONException(final String message) { super(message); } - + /** * Constructs a new JSONException with the specified cause. * @@ -28,14 +28,13 @@ public class JSONException extends RuntimeException { super(cause.getMessage()); this.cause = cause; } - + /** * Returns the cause of this exception or null if the cause is nonexistent or unknown. * * @return the cause of this exception or null if the cause is nonexistent or unknown. */ - @Override - public Throwable getCause() { + @Override public Throwable getCause() { return cause; } } diff --git a/Core/src/main/java/com/intellectualcrafters/json/JSONML.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONML.java similarity index 96% rename from Core/src/main/java/com/intellectualcrafters/json/JSONML.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONML.java index 0b1f9ece4..144ebc1d8 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/JSONML.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONML.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.json; +package com.github.intellectualsites.plotsquared.json; import java.util.Iterator; @@ -16,12 +16,11 @@ public class JSONML { * @param x The XMLTokener containing the source string. * @param arrayForm true if array form, false if object form. * @param ja The JSONArray that is containing the current tag or null if we are at the outermost level. - * * @return A JSONArray if the value is the outermost tag, otherwise null. - * * @throws JSONException */ - private static Object parse(XMLTokener x, boolean arrayForm, JSONArray ja) throws JSONException { + private static Object parse(XMLTokener x, boolean arrayForm, JSONArray ja) + throws JSONException { String attribute; char c; String closeTag = null; @@ -47,7 +46,8 @@ public class JSONML { // Close tag 0)) { @@ -180,22 +182,20 @@ public class JSONML { } } } - + /** * Convert a well-formed (but not necessarily valid) XML string into a JSONArray using the JsonML transform. Each * XML tag is represented as a JSONArray in which the first element is the tag name. If the tag has attributes, then * the second element will be JSONObject containing the name/value pairs. If the tag contains children, then strings * * @param string The source string. - * * @return A JSONArray containing the structured data from the XML string. - * * @throws JSONException */ public static JSONArray toJSONArray(String string) throws JSONException { return toJSONArray(new XMLTokener(string)); } - + /** * Convert a well-formed (but not necessarily valid) XML string into a JSONArray using the JsonML transform. Each * XML tag is represented as a JSONArray in which the first element is the tag name. If the tag has attributes, then @@ -204,58 +204,50 @@ public class JSONML { * are ignored. * * @param x An XMLTokener. - * * @return A JSONArray containing the structured data from the XML string. - * * @throws JSONException */ public static JSONArray toJSONArray(XMLTokener x) throws JSONException { return (JSONArray) parse(x, true, null); } - + /** * Convert a well-formed (but not necessarily valid) XML string into a JSONObject using the JsonML transform. Each * XML tag is represented as a JSONObject with a "tagName" property. If the tag has attributes, then the attributes * will be in the JSONObject as properties. If the tag contains children, the object will have a "childNodes" * property which will be an array of strings and JsonML JSONObjects. - * + *

* Comments, prologs, DTDs, and <[ [ ]]> are ignored. * * @param x An XMLTokener of the XML source text. - * * @return A JSONObject containing the structured data from the XML string. - * * @throws JSONException */ public static JSONObject toJSONObject(XMLTokener x) throws JSONException { return (JSONObject) parse(x, false, null); } - + /** * Convert a well-formed (but not necessarily valid) XML string into a JSONObject using the JsonML transform. Each * XML tag is represented as a JSONObject with a "tagName" property. If the tag has attributes, then the attributes * will be in the JSONObject as properties. If the tag contains children, the object will have a "childNodes" * property which will be an array of strings and JsonML JSONObjects. - * + *

* Comments, prologs, DTDs, and <[ [ ]]> are ignored. * * @param string The XML source text. - * * @return A JSONObject containing the structured data from the XML string. - * * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { return toJSONObject(new XMLTokener(string)); } - + /** * Reverse the JSONML transformation, making an XML text from a JSONArray. * * @param ja A JSONArray. - * * @return An XML string. - * * @throws JSONException */ public static String toString(JSONArray ja) throws JSONException { @@ -323,16 +315,14 @@ public class JSONML { } return sb.toString(); } - + /** * Reverse the JSONML transformation, making an XML text from a JSONObject. The JSONObject must contain a "tagName" * property. If it has children, then it must have a "childNodes" property containing an array of objects. The other * properties are attributes with string values. * * @param jo A JSONObject. - * * @return An XML string. - * * @throws JSONException */ public static String toString(JSONObject jo) throws JSONException { diff --git a/Core/src/main/java/com/intellectualcrafters/json/JSONObject.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONObject.java similarity index 94% rename from Core/src/main/java/com/intellectualcrafters/json/JSONObject.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONObject.java index 685e15fd8..9a84920dc 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/JSONObject.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONObject.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.json; +package com.github.intellectualsites.plotsquared.json; import java.io.IOException; import java.io.StringWriter; @@ -7,15 +7,8 @@ import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.Collection; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.ResourceBundle; -import java.util.Set; /** * A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces @@ -28,21 +21,21 @@ import java.util.Set; * values into a JSON text using the put and toString methods. A get method * returns a value if one can be found, and throws an exception if one cannot be found. An opt method * returns a default value instead of throwing an exception, and so is useful for obtaining optional values. - * + *

* The generic get() and opt() methods return an object, which you can cast or query for type. * There are also typed get and opt methods that do type checking and type coercion for you. * The opt methods differ from the get methods in that they do not throw. Instead, they return a specified value, such * as null. - * + *

* The put methods add or replace values in an object. For example, * * *

  * myString = new JSONObject().put("JSON", "Hello, World!").toString();
  * 
- * + *

* produces the string {"JSON": "Hello, World"}. - * + *

* The texts produced by the toString methods strictly conform to the JSON syntax rules. The constructors * are more forgiving in the texts they will accept:

  • An extra , (comma) may * appear just before the closing brace.
  • Strings may be quoted with ' (single @@ -65,21 +58,20 @@ public class JSONObject { * The map where the JSONObject's properties are kept. */ private final Map map; - + /** * Construct an empty JSONObject. */ public JSONObject() { this.map = new HashMap(); } - + /** * Construct a JSONObject from a subset of another JSONObject. An array of strings is used to identify the keys that * should be copied. Missing keys are ignored. * * @param jo A JSONObject. * @param names An array of strings. - * * @throws JSONException * @throws JSONException If a value is a non-finite number or if a name is duplicated. */ @@ -88,15 +80,15 @@ public class JSONObject { for (String name : names) { try { putOnce(name, jo.opt(name)); - } catch (JSONException ignore) {} + } catch (JSONException ignore) { + } } } - + /** * Construct a JSONObject from a JSONTokener. * * @param x A JSONTokener object containing the source string. - * * @throws JSONException If there is a syntax error in the source string or a duplicated key. */ public JSONObject(JSONTokener x) throws JSONException { @@ -106,7 +98,7 @@ public class JSONObject { if (x.nextClean() != '{') { throw x.syntaxError("A JSONObject text must begin with '{'"); } - for (;;) { + for (; ; ) { c = x.nextClean(); switch (c) { case 0: @@ -139,12 +131,11 @@ public class JSONObject { } } } - + /** * Construct a JSONObject from a Map. * * @param map A map object that can be used to initialize the contents of the JSONObject. - * * @throws JSONException */ public JSONObject(Map map) { @@ -158,16 +149,16 @@ public class JSONObject { } } } - + /** * Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object. * For each of the methods with no parameters and a name starting with "get" or "is" * followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method * are put into the new JSONObject. - * + *

    * The key is formed by removing the "get" or "is" prefix. If the second remaining * character is not upper case, then the first character is converted to lower case. - * + *

    * For example, if an object has a method named "getPluginName", and if the result of calling * object.getPluginName() is "Larry Fine", then the JSONObject will contain "name": "Larry * Fine". @@ -178,7 +169,7 @@ public class JSONObject { this(); populateMap(bean); } - + /** * Construct a JSONObject from an Object, using reflection to find the public members. The resulting JSONObject's * keys will be the strings from the names array, and the values will be the field values associated with those keys @@ -193,33 +184,33 @@ public class JSONObject { for (String name : names) { try { putOpt(name, c.getField(name).get(object)); - } catch (JSONException | SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException ignore) {} + } catch (JSONException | SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException ignore) { + } } } - + /** * Construct a JSONObject from a source JSON text string. This is the most commonly used JSONObject constructor. * * @param source A string beginning with { (left brace) and ending with * }  (right brace). - * * @throws JSONException If there is a syntax error in the source string or a duplicated key. */ public JSONObject(String source) throws JSONException { this(new JSONTokener(source)); } - + /** * Construct a JSONObject from a ResourceBundle. * * @param baseName The ResourceBundle base name. * @param locale The Locale to load the ResourceBundle for. - * * @throws JSONException If any JSONExceptions are detected. */ public JSONObject(String baseName, Locale locale) throws JSONException { this(); - ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, Thread.currentThread().getContextClassLoader()); + ResourceBundle bundle = ResourceBundle + .getBundle(baseName, locale, Thread.currentThread().getContextClassLoader()); // Iterate through the keys in the bundle. Enumeration keys = bundle.getKeys(); while (keys.hasMoreElements()) { @@ -246,12 +237,11 @@ public class JSONObject { } } } - + /** * Produce a string from a double. The string "null" will be returned if the number is not finite. * * @param d A double. - * * @return A String. */ public static String doubleToString(double d) { @@ -270,7 +260,7 @@ public class JSONObject { } return string; } - + /** * Get an array of field names from a JSONObject. * @@ -290,7 +280,7 @@ public class JSONObject { } return names; } - + /** * Get an array of field names from an Object. * @@ -312,14 +302,12 @@ public class JSONObject { } return names; } - + /** * Produce a string from a Number. * * @param number A Number - * * @return A String. - * * @throws JSONException If n is a non-finite number. */ public static String numberToString(Number number) throws JSONException { @@ -339,13 +327,12 @@ public class JSONObject { } return string; } - + /** * Produce a string in double quotes with backslash sequences in all the right places. A backslash will be inserted * control character or an unescaped quote or backslash. * * @param string A String - * * @return A String correctly formatted for insertion in a JSON text. */ public static String quote(String string) { @@ -402,7 +389,8 @@ public class JSONObject { w.write("\\r"); break; default: - if ((c < ' ') || ((c >= '\u0080') && (c < '\u00a0')) || ((c >= '\u2000') && (c < '\u2100'))) { + if ((c < ' ') || ((c >= '\u0080') && (c < '\u00a0')) || ((c >= '\u2000') && (c + < '\u2100'))) { w.write("\\u"); hhhh = Integer.toHexString(c); w.write("0000", 0, 4 - hhhh.length()); @@ -415,12 +403,11 @@ public class JSONObject { w.write('"'); return w; } - + /** * Try to convert a string into a number, boolean, or null. If the string can't be converted, return the string. * * @param string A String. - * * @return A simple JSON value. */ public static Object stringToValue(String string) { @@ -444,7 +431,8 @@ public class JSONObject { char b = string.charAt(0); if (((b >= '0') && (b <= '9')) || (b == '-')) { try { - if ((string.indexOf('.') > -1) || (string.indexOf('e') > -1) || (string.indexOf('E') > -1)) { + if ((string.indexOf('.') > -1) || (string.indexOf('e') > -1) || (string.indexOf('E') + > -1)) { d = Double.valueOf(string); if (!d.isInfinite() && !d.isNaN()) { return d; @@ -459,16 +447,16 @@ public class JSONObject { } } } - } catch (NumberFormatException ignore) {} + } catch (NumberFormatException ignore) { + } } return string; } - + /** * Throw an exception if the object is a NaN or infinite number. * * @param o The object to test. - * * @throws JSONException If o is a non-finite number. */ public static void testValidity(Object o) throws JSONException { @@ -484,7 +472,7 @@ public class JSONObject { } } } - + /** * Make a JSON text of an Object value. If the object has an value.toJSONString() method, then that method will be * used to produce the JSON text. The method is required to produce a strictly conforming text. If the object does @@ -492,16 +480,14 @@ public class JSONObject { * If the value is an array or Collection, then a JSONArray will be made from it and its toJSONString method will be * called. If the value is a MAP, then a JSONObject will be made from it and its toJSONString method will be called. * Otherwise, the value's toString method will be called, and the result will be quoted. - * - * + *

    + *

    * Warning: This method assumes that the data structure is acyclical. * * @param value The value to be serialized. - * * @return a printable, displayable, transmittable representation of the object, beginning with * { (left brace) and ending with } (right * brace). - * * @throws JSONException If the value is or contains an invalid number. */ public static String valueToString(Object value) throws JSONException { @@ -523,7 +509,8 @@ public class JSONObject { if (value instanceof Number) { return numberToString((Number) value); } - if ((value instanceof Boolean) || (value instanceof JSONObject) || (value instanceof JSONArray)) { + if ((value instanceof Boolean) || (value instanceof JSONObject) + || (value instanceof JSONArray)) { return value.toString(); } if (value instanceof Map) { @@ -537,7 +524,7 @@ public class JSONObject { } return quote(value.toString()); } - + /** * Wrap an object, if necessary. If the object is null, return the NULL object. If it is an array or collection, * wrap it in a JSONArray. If it is a map, wrap it in a JSONObject. If it is a standard property (Double, String, et @@ -545,7 +532,6 @@ public class JSONObject { * if it doesn't, try to wrap it in a JSONObject. If the wrapping fails, then null is returned. * * @param object The object to wrap - * * @return The wrapped value */ public static Object wrap(Object object) { @@ -553,19 +539,12 @@ public class JSONObject { if (object == null) { return NULL; } - if ((object instanceof JSONObject) - || (object instanceof JSONArray) - || NULL.equals(object) - || (object instanceof JSONString) - || (object instanceof Byte) - || (object instanceof Character) - || (object instanceof Short) - || (object instanceof Integer) - || (object instanceof Long) - || (object instanceof Boolean) - || (object instanceof Float) - || (object instanceof Double) - || (object instanceof String)) { + if ((object instanceof JSONObject) || (object instanceof JSONArray) || NULL + .equals(object) || (object instanceof JSONString) || (object instanceof Byte) + || (object instanceof Character) || (object instanceof Short) + || (object instanceof Integer) || (object instanceof Long) + || (object instanceof Boolean) || (object instanceof Float) + || (object instanceof Double) || (object instanceof String)) { return object; } if (object instanceof Collection) { @@ -579,7 +558,8 @@ public class JSONObject { } Package objectPackage = object.getClass().getPackage(); String objectPackageName = objectPackage != null ? objectPackage.getName() : ""; - if (objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || (object.getClass().getClassLoader() == null)) { + if (objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || ( + object.getClass().getClassLoader() == null)) { return object.toString(); } return new JSONObject(object); @@ -588,7 +568,8 @@ public class JSONObject { } } - static final Writer writeValue(Writer writer, Object value, int indentFactor, int indent) throws JSONException, IOException { + static final Writer writeValue(Writer writer, Object value, int indentFactor, int indent) + throws JSONException, IOException { if ((value == null) || value.equals(null)) { writer.write("null"); } else if (value instanceof JSONObject) { @@ -624,20 +605,18 @@ public class JSONObject { writer.write(' '); } } - + /** * Accumulate values under a key. It is similar to the put method except that if there is already an object stored * under the key then a JSONArray is stored under the key to hold all of the accumulated values. If there is already * a JSONArray, then the new value is appended to it. In contrast, the put method replaces the previous value. - * + *

    * If only one value is accumulated that is not a JSONArray, then the result will be the same as using put. But if * multiple values are accumulated, then the result will be like append. * * @param key A key string. * @param value An object to be accumulated under the key. - * * @return this. - * * @throws JSONException If the value is an invalid number or if the key is null. */ public JSONObject accumulate(String key, Object value) throws JSONException { @@ -652,7 +631,7 @@ public class JSONObject { } return this; } - + /** * Append values to the array under a key. If the key does not exist in the JSONObject, then the key is put in the * JSONObject with its value being a JSONArray containing the value parameter. If the key was already associated @@ -660,9 +639,7 @@ public class JSONObject { * * @param key A key string. * @param value An object to be accumulated under the key. - * * @return this. - * * @throws JSONException If the key is null or if the current value associated with the key is not a JSONArray. */ public JSONObject append(String key, Object value) throws JSONException { @@ -677,14 +654,12 @@ public class JSONObject { } return this; } - + /** * Get the value object associated with a key. * * @param key A key string. - * * @return The object associated with the key. - * * @throws JSONException if the key is not found. */ public Object get(String key) throws JSONException { @@ -697,70 +672,68 @@ public class JSONObject { } return object; } - + /** * Get the boolean value associated with a key. * * @param key A key string. - * * @return The truth. - * * @throws JSONException if the value is not a Boolean or the String "true" or "false". */ public boolean getBoolean(String key) throws JSONException { Object object = get(key); - if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("false"))) { + if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object) + .equalsIgnoreCase("false"))) { return false; - } else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("true"))) { + } else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object) + .equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); } - + /** * Get the double value associated with a key. * * @param key A key string. - * * @return The numeric value. - * * @throws JSONException if the key is not found or if the value is not a Number object and cannot be converted to a * number. */ public double getDouble(String key) throws JSONException { Object object = get(key); try { - return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); + return object instanceof Number ? + ((Number) object).doubleValue() : + Double.parseDouble((String) object); } catch (NumberFormatException ignored) { throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); } } - + /** * Get the int value associated with a key. * * @param key A key string. - * * @return The integer value. - * * @throws JSONException if the key is not found or if the value cannot be converted to an integer. */ public int getInt(String key) throws JSONException { Object object = get(key); try { - return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); + return object instanceof Number ? + ((Number) object).intValue() : + Integer.parseInt((String) object); } catch (NumberFormatException ignored) { throw new JSONException("JSONObject[" + quote(key) + "] is not an int."); } } - + /** * Get the JSONArray value associated with a key. * * @param key A key string. - * * @return A JSONArray which is the value. - * * @throws JSONException if the key is not found or if the value is not a JSONArray. */ public JSONArray getJSONArray(String key) throws JSONException { @@ -770,14 +743,12 @@ public class JSONObject { } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); } - + /** * Get the JSONObject value associated with a key. * * @param key A key string. - * * @return A JSONObject which is the value. - * * @throws JSONException if the key is not found or if the value is not a JSONObject. */ public JSONObject getJSONObject(String key) throws JSONException { @@ -787,32 +758,30 @@ public class JSONObject { } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); } - + /** * Get the long value associated with a key. * * @param key A key string. - * * @return The long value. - * * @throws JSONException if the key is not found or if the value cannot be converted to a long. */ public long getLong(String key) throws JSONException { Object object = get(key); try { - return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); + return object instanceof Number ? + ((Number) object).longValue() : + Long.parseLong((String) object); } catch (NumberFormatException ignored) { throw new JSONException("JSONObject[" + quote(key) + "] is not a long."); } } - + /** * Get the string associated with a key. * * @param key A key string. - * * @return A string which is the value. - * * @throws JSONException if there is no string value for the key. */ public String getString(String key) throws JSONException { @@ -822,26 +791,23 @@ public class JSONObject { } throw new JSONException("JSONObject[" + quote(key) + "] not a string."); } - + /** * Determine if the JSONObject contains a specific key. * * @param key A key string. - * * @return true if the key exists in the JSONObject. */ public boolean has(String key) { return this.map.containsKey(key); } - + /** * Increment a property of a JSONObject. If there is no such property, create one with a value of 1. If there is * such a property, and if it is an Integer, Long, Double, or Float, then add one to it. * * @param key A key string. - * * @return this. - * * @throws JSONException If there is already a property with this name that is not an Integer, Long, Double, or * Float. */ @@ -862,18 +828,17 @@ public class JSONObject { } return this; } - + /** * Determine if the value associated with the key is null or if there is no value. * * @param key A key string. - * * @return true if there is no value associated with the key or if the value is the JSONObject.NULL object. */ public boolean isNull(String key) { return JSONObject.NULL.equals(opt(key)); } - + /** * Get an enumeration of the keys of the JSONObject. * @@ -882,7 +847,7 @@ public class JSONObject { public Iterator keys() { return keySet().iterator(); } - + /** * Get a set of keys of the JSONObject. * @@ -891,7 +856,7 @@ public class JSONObject { public Set keySet() { return this.map.keySet(); } - + /** * Get the number of keys stored in the JSONObject. * @@ -900,7 +865,7 @@ public class JSONObject { public int length() { return this.map.size(); } - + /** * Produce a JSONArray containing the names of the elements of this JSONObject. * @@ -914,37 +879,34 @@ public class JSONObject { } return ja.length() == 0 ? null : ja; } - + /** * Get an optional value associated with a key. * * @param key A key string. - * * @return An object which is the value, or null if there is no value. */ public Object opt(String key) { return key == null ? null : this.map.get(key); } - + /** * Get an optional boolean associated with a key. It returns false if there is no such key, or if the value is not * Boolean.TRUE or the String "true". * * @param key A key string. - * * @return The truth. */ public boolean optBoolean(String key) { return this.optBoolean(key, false); } - + /** * Get an optional boolean associated with a key. It returns the defaultValue if there is no such key, or if it is * not a Boolean or the String "true" or "false" (case insensitive). * * @param key A key string. * @param defaultValue The default. - * * @return The truth. */ public boolean optBoolean(String key, boolean defaultValue) { @@ -954,26 +916,24 @@ public class JSONObject { return defaultValue; } } - + /** * Get an optional double associated with a key, or NaN if there is no such key or if its value is not a number. If * the value is a string, an attempt will be made to evaluate it as a number. * * @param key A string which is the key. - * * @return An object which is the value. */ public double optDouble(String key) { return this.optDouble(key, Double.NaN); } - + /** * Get an optional double associated with a key, or the defaultValue if there is no such key or if its value is not * a number. If the value is a string, an attempt will be made to evaluate it as a number. * * @param key A key string. * @param defaultValue The default. - * * @return An object which is the value. */ public double optDouble(String key, double defaultValue) { @@ -983,26 +943,24 @@ public class JSONObject { return defaultValue; } } - + /** * Get an optional int value associated with a key, or zero if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as a number. * * @param key A key string. - * * @return An object which is the value. */ public int optInt(String key) { return this.optInt(key, 0); } - + /** * Get an optional int value associated with a key, or the default if there is no such key or if the value is not a * number. If the value is a string, an attempt will be made to evaluate it as a number. * * @param key A key string. * @param defaultValue The default. - * * @return An object which is the value. */ public int optInt(String key, int defaultValue) { @@ -1012,52 +970,48 @@ public class JSONObject { return defaultValue; } } - + /** * Get an optional JSONArray associated with a key. It returns null if there is no such key, or if its value is not * a JSONArray. * * @param key A key string. - * * @return A JSONArray which is the value. */ public JSONArray optJSONArray(String key) { Object o = opt(key); return o instanceof JSONArray ? (JSONArray) o : null; } - + /** * Get an optional JSONObject associated with a key. It returns null if there is no such key, or if its value is not * a JSONObject. * * @param key A key string. - * * @return A JSONObject which is the value. */ public JSONObject optJSONObject(String key) { Object object = opt(key); return object instanceof JSONObject ? (JSONObject) object : null; } - + /** * Get an optional long value associated with a key, or zero if there is no such key or if the value is not a * number. If the value is a string, an attempt will be made to evaluate it as a number. * * @param key A key string. - * * @return An object which is the value. */ public long optLong(String key) { return this.optLong(key, 0); } - + /** * Get an optional long value associated with a key, or the default if there is no such key or if the value is not a * number. If the value is a string, an attempt will be made to evaluate it as a number. * * @param key A key string. * @param defaultValue The default. - * * @return An object which is the value. */ public long optLong(String key, long defaultValue) { @@ -1067,25 +1021,23 @@ public class JSONObject { return defaultValue; } } - + /** * Get an optional string associated with a key. It returns an empty string if there is no such key. If the value is * not a string and is not null, then it is converted to a string. * * @param key A key string. - * * @return A string which is the value. */ public String optString(String key) { return this.optString(key, ""); } - + /** * Get an optional string associated with a key. It returns the defaultValue if there is no such key. * * @param key A key string. * @param defaultValue The default. - * * @return A string which is the value. */ public String optString(String key, String defaultValue) { @@ -1112,7 +1064,8 @@ public class JSONObject { } else if (name.startsWith("is")) { key = name.substring(2); } - if (!key.isEmpty() && Character.isUpperCase(key.charAt(0)) && (method.getParameterTypes().length == 0)) { + if (!key.isEmpty() && Character.isUpperCase(key.charAt(0)) && ( + method.getParameterTypes().length == 0)) { if (key.length() == 1) { key = key.toLowerCase(); } else if (!Character.isUpperCase(key.charAt(1))) { @@ -1124,100 +1077,89 @@ public class JSONObject { } } } - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ignore) {} + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ignore) { + } } } - + /** * Put a key/boolean pair in the JSONObject. * * @param key A key string. * @param value A boolean which is the value. - * * @return this. - * * @throws JSONException If the key is null. */ public JSONObject put(String key, boolean value) throws JSONException { this.put(key, value ? Boolean.TRUE : Boolean.FALSE); return this; } - + /** * Put a key/value pair in the JSONObject, where the value will be a JSONArray which is produced from a Collection. * * @param key A key string. * @param value A Collection value. - * * @return this. - * * @throws JSONException */ public JSONObject put(String key, Collection value) throws JSONException { this.put(key, new JSONArray(value)); return this; } - + /** * Put a key/double pair in the JSONObject. * * @param key A key string. * @param value A double which is the value. - * * @return this. - * * @throws JSONException If the key is null or if the number is invalid. */ public JSONObject put(String key, double value) throws JSONException { this.put(key, new Double(value)); return this; } - + /** * Put a key/int pair in the JSONObject. * * @param key A key string. * @param value An int which is the value. - * * @return this. - * * @throws JSONException If the key is null. */ public JSONObject put(String key, int value) throws JSONException { this.put(key, Integer.valueOf(value)); return this; } - + /** * Put a key/long pair in the JSONObject. * * @param key A key string. * @param value A long which is the value. - * * @return this. - * * @throws JSONException If the key is null. */ public JSONObject put(String key, long value) throws JSONException { this.put(key, Long.valueOf(value)); return this; } - + /** * Put a key/value pair in the JSONObject, where the value will be a JSONObject which is produced from a Map. * * @param key A key string. * @param value A Map value. - * * @return this. - * * @throws JSONException */ public JSONObject put(String key, Map value) throws JSONException { this.put(key, new JSONObject(value)); return this; } - + /** * Put a key/value pair in the JSONObject. If the value is null, then the key will be removed from the JSONObject if * it is present. @@ -1225,9 +1167,7 @@ public class JSONObject { * @param key A key string. * @param value An object which is the value. It should be of one of these types: Boolean, Double, Integer, * JSONArray, JSONObject, Long, String, or the JSONObject.NULL object. - * * @return this. - * * @throws JSONException If the value is non-finite number or if the key is null. */ public JSONObject put(String key, Object value) throws JSONException { @@ -1242,16 +1182,14 @@ public class JSONObject { } return this; } - + /** * Put a key/value pair in the JSONObject, but only if the key and the value are both non-null, and only if there is * not already a member with that name. * * @param key string * @param value object - * * @return this. - * * @throws JSONException if the key is a duplicate */ public JSONObject putOnce(String key, Object value) throws JSONException { @@ -1263,16 +1201,14 @@ public class JSONObject { } return this; } - + /** * Put a key/value pair in the JSONObject, but only if the key and the value are both non-null. * * @param key A key string. * @param value An object which is the value. It should be of one of these types: Boolean, Double, Integer, * JSONArray, JSONObject, Long, String, or the JSONObject.NULL object. - * * @return this. - * * @throws JSONException If the value is a non-finite number. */ public JSONObject putOpt(String key, Object value) throws JSONException { @@ -1281,24 +1217,22 @@ public class JSONObject { } return this; } - + /** * Remove a name and its value, if present. * * @param key The name to be removed. - * * @return The value that was associated with the name, or null if there was no value. */ public Object remove(String key) { return this.map.remove(key); } - + /** * Determine if two JSONObjects are similar. They must contain the same set of names which must be associated with * similar values. * * @param other The other JSONObject - * * @return true if they are equal */ public boolean similar(Object other) { @@ -1330,15 +1264,13 @@ public class JSONObject { return false; } } - + /** * Produce a JSONArray containing the values of the members of this JSONObject. * * @param names A JSONArray containing a list of key strings. This determines the sequence of the values in the * result. - * * @return A JSONArray of values. - * * @throws JSONException If any of the values are non-finite numbers. */ public JSONArray toJSONArray(JSONArray names) throws JSONException { @@ -1351,37 +1283,34 @@ public class JSONObject { } return ja; } - + /** * Make a JSON text of this JSONObject. For compactness, no whitespace is added. If this would not result in a * syntactically correct JSON text, then null will be returned instead. - * + *

    * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, portable, transmittable representation of the object, beginning with * { (left brace) and ending with } (right * brace). */ - @Override - public String toString() { + @Override public String toString() { try { return this.toString(0); } catch (JSONException ignored) { return null; } } - + /** * Make a prettyprinted JSON text of this JSONObject. - * + *

    * Warning: This method assumes that the data structure is acyclical. * * @param indentFactor The number of spaces to add to each level of indentation. - * * @return a printable, displayable, portable, transmittable representation of the object, beginning with * { (left brace) and ending with } (right * brace). - * * @throws JSONException If the object contains an invalid number. */ public String toString(int indentFactor) throws JSONException { @@ -1390,27 +1319,25 @@ public class JSONObject { return this.write(w, indentFactor, 0).toString(); } } - + /** * Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace is added. - * + *

    * Warning: This method assumes that the data structure is acyclical. * * @return The writer. - * * @throws JSONException */ public Writer write(Writer writer) throws JSONException { return this.write(writer, 0, 0); } - + /** * Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace is added. - * + *

    * Warning: This method assumes that the data structure is acyclical. * * @return The writer. - * * @throws JSONException */ Writer write(Writer writer, int indentFactor, int indent) throws JSONException { @@ -1457,7 +1384,7 @@ public class JSONObject { throw new JSONException(exception); } } - + /** * JSONObject.NULL is equivalent to the value that JavaScript calls null, whilst Java's null is equivalent to the * value that JavaScript calls undefined. @@ -1468,34 +1395,30 @@ public class JSONObject { * * @return NULL. */ - @Override - protected final Object clone() { + @Override protected final Object clone() { try { return super.clone(); } catch (CloneNotSupportedException ignored) { return this; } } - + /** * A Null object is equal to the null value and to itself. * * @param object An object to test for nullness. - * * @return true if the object parameter is the JSONObject.NULL object or null. */ - @Override - public boolean equals(Object object) { + @Override public boolean equals(Object object) { return (object == null) || (object == this); } - + /** * Get the "null" string value. * * @return The string "null". */ - @Override - public String toString() { + @Override public String toString() { return "null"; } } diff --git a/Core/src/main/java/com/intellectualcrafters/json/JSONString.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONString.java similarity index 92% rename from Core/src/main/java/com/intellectualcrafters/json/JSONString.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONString.java index 231506795..019776e58 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/JSONString.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONString.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.json; +package com.github.intellectualsites.plotsquared.json; /** * The JSONString interface allows a toJSONString() method so that a class can change the diff --git a/Core/src/main/java/com/intellectualcrafters/json/JSONStringer.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONStringer.java similarity index 94% rename from Core/src/main/java/com/intellectualcrafters/json/JSONStringer.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONStringer.java index ecacb861e..bbb89133b 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/JSONStringer.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONStringer.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.json; +package com.github.intellectualsites.plotsquared.json; import java.io.StringWriter; @@ -6,7 +6,7 @@ import java.io.StringWriter; * JSONStringer provides a quick and convenient way of producing JSON text. The texts produced strictly conform to JSON * syntax rules. No whitespace is added, so the results are ready for transmission or storage. Each instance of * JSONStringer can produce one JSON text. - * + *

    * A JSONStringer instance provides a value method for appending values to the text, and a key * method for adding keys before values in objects. There are array and endArray methods that * make and bound array values, and object and endObject methods which make and bound object @@ -17,17 +17,17 @@ import java.io.StringWriter; * myString = new JSONStringer().object().key("JSON").value("Hello, * World!").endObject().toString(); * - * + *

    * which produces the string * * *

      * {"JSON":"Hello, World!"}
      * 
    - * + *

    * The first method called must be array or object. There are no methods for adding commas or * colons. JSONStringer adds them for you. Objects and arrays can be nested up to 20 levels deep. - * + *

    * This can sometimes be easier than using a JSONObject to build a string. * * @author JSON.org @@ -40,7 +40,7 @@ public class JSONStringer extends JSONWriter { public JSONStringer() { super(new StringWriter()); } - + /** * Return the JSON text. This method is used to obtain the product of the JSONStringer instance. It will return * null if there was a problem in the construction of the JSON text (such as the calls to @@ -48,8 +48,7 @@ public class JSONStringer extends JSONWriter { * * @return The JSON text. */ - @Override - public String toString() { + @Override public String toString() { return mode == 'd' ? writer.toString() : null; } } diff --git a/Core/src/main/java/com/intellectualcrafters/json/JSONTokener.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONTokener.java similarity index 95% rename from Core/src/main/java/com/intellectualcrafters/json/JSONTokener.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONTokener.java index fa23fb91d..290b9ea0b 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/JSONTokener.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONTokener.java @@ -1,11 +1,6 @@ -package com.intellectualcrafters.json; +package com.github.intellectualsites.plotsquared.json; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; +import java.io.*; /** * A JSONTokener takes a source string and extracts characters and tokens from it. It is used by the JSONObject and @@ -22,7 +17,7 @@ public class JSONTokener { private long line; private char previous; private boolean usePrevious; - + /** * Construct a JSONTokener from a Reader. * @@ -37,7 +32,7 @@ public class JSONTokener { character = 1; line = 1; } - + /** * Construct a JSONTokener from an InputStream. * @@ -46,7 +41,7 @@ public class JSONTokener { public JSONTokener(final InputStream inputStream) throws JSONException { this(new InputStreamReader(inputStream)); } - + /** * Construct a JSONTokener from a string. * @@ -55,12 +50,11 @@ public class JSONTokener { public JSONTokener(final String s) { this(new StringReader(s)); } - + /** * Get the hex value of a character (base16). * * @param c A character between '0' and '9' or between 'A' and 'F' or between 'a' and 'f'. - * * @return An int between 0 and 15, or -1 if c was not a hex digit. */ public static int dehexchar(final char c) { @@ -75,7 +69,7 @@ public class JSONTokener { } return -1; } - + /** * Back up one character. This provides a sort of lookahead capability, so that you can test for a digit or letter * before attempting to parse the next number or identifier. @@ -89,11 +83,11 @@ public class JSONTokener { usePrevious = true; eof = false; } - + public boolean end() { return eof && !usePrevious; } - + /** * Determine if the source string still contains characters that next() can consume. * @@ -107,7 +101,7 @@ public class JSONTokener { back(); return true; } - + /** * Get the next character in the source string. * @@ -142,14 +136,12 @@ public class JSONTokener { previous = (char) c; return previous; } - + /** * Consume the next character, and check that it matches a specified character. * * @param c The character to match. - * * @return The character. - * * @throws JSONException if the character does not match. */ public char next(final char c) throws JSONException { @@ -159,14 +151,12 @@ public class JSONTokener { } return n; } - + /** * Get the next n characters. * * @param n The number of characters to take. - * * @return A string of n characters. - * * @throws JSONException Substring bounds error if there are not n characters remaining in the source string. */ public String next(final int n) throws JSONException { @@ -184,38 +174,35 @@ public class JSONTokener { } return new String(chars); } - + /** * Get the next char in the string, skipping whitespace. * * @return A character, or 0 if there are no more characters. - * * @throws JSONException */ public char nextClean() throws JSONException { - for (;;) { + for (; ; ) { final char c = this.next(); if ((c == 0) || (c > ' ')) { return c; } } } - + /** * Return the characters up to the next close quote character. Backslash processing is done. The formal JSON format * does not allow strings in single quotes, but an implementation is allowed to accept them. * * @param quote The quoting character, either "  (double quote) or ' *  (single quote). - * * @return A String. - * * @throws JSONException Unterminated string. */ public String nextString(final char quote) throws JSONException { char c; final StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { c = this.next(); switch (c) { case 0: @@ -261,17 +248,16 @@ public class JSONTokener { } } } - + /** * Get the text up but not including the specified character or the end of line, whichever comes first. * * @param delimiter A delimiter character. - * * @return A string. */ public String nextTo(final char delimiter) throws JSONException { final StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { final char c = this.next(); if ((c == delimiter) || (c == 0) || (c == '\n') || (c == '\r')) { if (c != 0) { @@ -282,19 +268,18 @@ public class JSONTokener { sb.append(c); } } - + /** * Get the text up but not including one of the specified delimiter characters or the end of line, whichever comes * first. * * @param delimiters A set of delimiter characters. - * * @return A string, trimmed. */ public String nextTo(final String delimiters) throws JSONException { char c; final StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { c = this.next(); if ((delimiters.indexOf(c) >= 0) || (c == 0) || (c == '\n') || (c == '\r')) { if (c != 0) { @@ -305,13 +290,12 @@ public class JSONTokener { sb.append(c); } } - + /** * Get the next value. The value can be a Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the * JSONObject.NULL object. * * @return An object. - * * @throws JSONException If syntax error. */ public Object nextValue() throws JSONException { @@ -347,13 +331,12 @@ public class JSONTokener { } return JSONObject.stringToValue(string); } - + /** * Skip characters until the next character is the requested character. If the requested character is not found, no * characters are skipped. * * @param to A character to skip to. - * * @return The requested character, or zero if the requested character is not found. */ public char skipTo(final char to) throws JSONException { @@ -379,25 +362,23 @@ public class JSONTokener { back(); return c; } - + /** * Make a JSONException to signal a syntax error. * * @param message The error message. - * * @return A JSONException object, suitable for throwing */ public JSONException syntaxError(final String message) { return new JSONException(message + toString()); } - + /** * Make a printable string of this JSONTokener. * * @return " at {index} [character {character} line {line}]" */ - @Override - public String toString() { + @Override public String toString() { return " at " + index + " [character " + character + " line " + line + "]"; } } diff --git a/Core/src/main/java/com/intellectualcrafters/json/JSONWriter.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONWriter.java similarity index 97% rename from Core/src/main/java/com/intellectualcrafters/json/JSONWriter.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONWriter.java index 44f893ce6..de6af2c75 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/JSONWriter.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONWriter.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.json; +package com.github.intellectualsites.plotsquared.json; import java.io.IOException; import java.io.Writer; @@ -7,7 +7,7 @@ import java.io.Writer; * JSONWriter provides a quick and convenient way of producing JSON text. The texts produced strictly conform to JSON * syntax rules. No whitespace is added, so the results are ready for transmission or storage. Each instance of * JSONWriter can produce one JSON text. - * + *

    * A JSONWriter instance provides a value method for appending values to the text, and a key * method for adding keys before values in objects. There are array and endArray methods that * make and bound array values, and object and endObject methods which make and bound object @@ -17,17 +17,17 @@ import java.io.Writer; *

      * new JSONWriter(myWriter).object().key("JSON").value("Hello, World!").endObject();
      * 
    - * + *

    * which writes * * *

      * {"JSON":"Hello, World!"}
      * 
    - * + *

    * The first method called must be array or object. There are no methods for adding commas or * colons. JSONWriter adds them for you. Objects and arrays can be nested up to 20 levels deep. - * + *

    * This can sometimes be easier than using a JSONObject to build a string. * * @author JSON.org @@ -55,7 +55,7 @@ public class JSONWriter { * The stack top index. A value of 0 indicates that the stack is empty. */ private int top; - + /** * Make a fresh JSONWriter. It can be used to build one JSON text. */ @@ -66,14 +66,12 @@ public class JSONWriter { top = 0; writer = w; } - + /** * Append a value. * * @param string A string value. - * * @return this - * * @throws JSONException If the value is out of sequence. */ private JSONWriter append(final String string) throws JSONException { @@ -97,13 +95,12 @@ public class JSONWriter { } throw new JSONException("Value out of sequence."); } - + /** * Begin appending a new array. All values until the balancing endArray will be appended to this array. * The endArray method must be called to mark the array's end. * * @return this - * * @throws JSONException If the nesting is too deep, or if the object is started in the wrong place (for example as * a key or after the end of the outermost array or object). */ @@ -116,15 +113,13 @@ public class JSONWriter { } throw new JSONException("Misplaced array."); } - + /** * End something. * * @param mode Mode * @param c Closing character - * * @return this - * * @throws JSONException If unbalanced. */ private JSONWriter end(final char mode, final char c) throws JSONException { @@ -140,37 +135,33 @@ public class JSONWriter { comma = true; return this; } - + /** * End an array. This method most be called to balance calls to array. * * @return this - * * @throws JSONException If incorrectly nested. */ public JSONWriter endArray() throws JSONException { return end('a', ']'); } - + /** * End an object. This method most be called to balance calls to object. * * @return this - * * @throws JSONException If incorrectly nested. */ public JSONWriter endObject() throws JSONException { return end('k', '}'); } - + /** * Append a key. The key will be associated with the next value. In an object, every value must be preceded by a * key. * * @param string A key string. - * * @return this - * * @throws JSONException If the key is out of place. For example, keys do not belong in arrays or if the key is * null. */ @@ -195,13 +186,12 @@ public class JSONWriter { } throw new JSONException("Misplaced key."); } - + /** * Begin appending a new object. All keys and values until the balancing endObject will be appended to * this object. The endObject method must be called to mark the object's end. * * @return this - * * @throws JSONException If the nesting is too deep, or if the object is started in the wrong place (for example as * a key or after the end of the outermost array or object). */ @@ -217,12 +207,11 @@ public class JSONWriter { } throw new JSONException("Misplaced object."); } - + /** * Pop an array or object scope. * * @param c The scope to close. - * * @throws JSONException If nesting is wrong. */ private void pop(final char c) throws JSONException { @@ -236,12 +225,11 @@ public class JSONWriter { top -= 1; mode = top == 0 ? 'd' : stack[top - 1] == null ? 'a' : 'k'; } - + /** * Push an array or object scope. * * @param jo The scope to open. - * * @throws JSONException If nesting is too deep. */ private void push(final JSONObject jo) throws JSONException { @@ -252,54 +240,46 @@ public class JSONWriter { mode = jo == null ? 'a' : 'k'; top += 1; } - + /** * Append either the value true or the value false . * * @param b A boolean. - * * @return this - * * @throws JSONException */ public JSONWriter value(final boolean b) throws JSONException { return append(b ? "true" : "false"); } - + /** * Append a double value. * * @param d A double. - * * @return this - * * @throws JSONException If the number is not finite. */ public JSONWriter value(final double d) throws JSONException { return this.value(new Double(d)); } - + /** * Append a long value. * * @param l A long. - * * @return this - * * @throws JSONException */ public JSONWriter value(final long l) throws JSONException { return append(Long.toString(l)); } - + /** * Append an object value. * * @param object The object to append. It can be null, or a Boolean, Number, String, JSONObject, or JSONArray, or an * object that implements JSONString. - * * @return this - * * @throws JSONException If the value is out of sequence. */ public JSONWriter value(final Object object) throws JSONException { diff --git a/Core/src/main/java/com/intellectualcrafters/json/Kim.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/Kim.java similarity index 95% rename from Core/src/main/java/com/intellectualcrafters/json/Kim.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/json/Kim.java index 7209e26c3..adf696179 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/Kim.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/Kim.java @@ -1,26 +1,26 @@ -package com.intellectualcrafters.json; +package com.github.intellectualsites.plotsquared.json; /** * Kim makes immutable eight bit Unicode strings. If the MSB of a byte is set, then the next byte is a continuation * byte. The last byte of a character never has the MSB reset. Every byte that is not the last byte has the MSB set. Kim * stands for "Keep it minimal". A Unicode character is never longer than 3 bytes. Every byte contributes 7 bits to the * character. ASCII is unmodified. - * + *

    * Kim UTF-8 one byte U+007F U+007F two bytes U+3FFF U+07FF three bytes U+10FFF U+FFFF four bytes U+10FFFF - * + *

    * Characters in the ranges U+0800..U+3FFF and U+10000..U+10FFFF will be one byte smaller when encoded in Kim compared * to UTF-8. - * + *

    * Kim is beneficial when using scripts such as Old South Arabian, Aramaic, Avestan, Balinese, Batak, Bopomofo, * Buginese, Buhid, Carian, Cherokee, Coptic, Cyrillic, Deseret, Egyptian Hieroglyphs, Ethiopic, Georgian, Glagolitic, * Gothic, Hangul Jamo, Hanunoo, Hiragana, Kanbun, Kaithi, Kannada, Katakana, Kharoshthi, Khmer, Lao, Lepcha, Limbu, * Lycian, Lydian, Malayalam, Mandaic, Meroitic, Miao, Mongolian, Myanmar, New Tai Lue, Ol Chiki, Old Turkic, Oriya, * Osmanya, Pahlavi, Parthian, Phags-Pa, Phoenician, Samaritan, Sharada, Sinhala, Sora Sompeng, Tagalog, Tagbanwa, * Takri, Tai Le, Tai Tham, Tamil, Telugu, Thai, Tibetan, Tifinagh, UCAS. - * + *

    * A kim object can be constructed from an ordinary UTF-16 string, or from a byte array. A kim object can produce a * UTF-16 string. - * + *

    * As with UTF-8, it is possible to detect character boundaries within a byte sequence. UTF-8 is one of the world's * great inventions. While Kim is more efficient, it is not clear that it is worth the expense of transition. * @@ -43,7 +43,7 @@ public class Kim { * The memoization of toString(). */ private String string = null; - + /** * Make a kim from a portion of a byte array. * @@ -70,7 +70,7 @@ public class Kim { hashcode += sum << 16; } } - + /** * Make a kim from a byte array. * @@ -80,7 +80,7 @@ public class Kim { public Kim(final byte[] bytes, final int length) { this(bytes, 0, length); } - + /** * Make a new kim from a substring of an existing kim. The coordinates are in byte units, not character units. * @@ -91,12 +91,11 @@ public class Kim { public Kim(final Kim kim, final int from, final int thru) { this(kim.bytes, from, thru); } - + /** * Make a kim from a string. * * @param string The string. - * * @throws JSONException if surrogate pair mismatch. */ public Kim(final String string) throws JSONException { @@ -151,7 +150,8 @@ public class Kim { } else { if ((character >= 0xD800) && (character <= 0xDBFF)) { i += 1; - character = (((character & 0x3FF) << 10) | (string.charAt(i) & 0x3FF)) + 65536; + character = + (((character & 0x3FF) << 10) | (string.charAt(i) & 0x3FF)) + 65536; } b = 0x80 | (character >>> 14); bytes[at] = (byte) b; @@ -173,14 +173,12 @@ public class Kim { hashcode += sum << 16; } } - + /** * Returns the number of bytes needed to contain the character in Kim format. * * @param character a Unicode character between 0 and 0x10FFFF. - * * @return 1, 2, or 3 - * * @throws JSONException if the character is not representable in a kim. */ public static int characterSize(final int character) throws JSONException { @@ -189,15 +187,14 @@ public class Kim { } return character <= 0x7F ? 1 : character <= 0x3FFF ? 2 : 3; } - + /** * Returns the character at the specified index. The index refers to byte values and ranges from 0 to length - 1. * The index of the next character is at index + Kim.characterSize(kim.characterAt(index)). * * @param at the index of the char value. The first character is at 0. - * - * @throws JSONException if at does not point to a valid character. * @return a Unicode character between 0 and 0x10FFFF. + * @throws JSONException if at does not point to a valid character. */ public int characterAt(final int at) throws JSONException { final int c = get(at); @@ -214,35 +211,33 @@ public class Kim { } else { final int c2 = get(at + 2); character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2; - if (((c2 & 0x80) == 0) && (character > 0x3FFF) && (character <= 0x10FFFF) && ((character < 0xD800) || (character > 0xDFFF))) { + if (((c2 & 0x80) == 0) && (character > 0x3FFF) && (character <= 0x10FFFF) && ( + (character < 0xD800) || (character > 0xDFFF))) { return character; } } throw new JSONException("Bad character at " + at); } - + /** * Copy the contents of this kim to a byte array. * * @param bytes A byte array of sufficient size. * @param at The position within the byte array to take the byes. - * * @return The position immediately after the copy. */ public int copy(final byte[] bytes, final int at) { System.arraycopy(this.bytes, 0, bytes, at, length); return at + length; } - + /** * Two kim objects containing exactly the same bytes in the same order are equal to each other. * * @param obj the other kim with which to compare. - * * @return true if this and obj are both kim objects containing identical byte sequences. */ - @Override - public boolean equals(final Object obj) { + @Override public boolean equals(final Object obj) { if (!(obj instanceof Kim)) { return false; } @@ -255,14 +250,12 @@ public class Kim { } return java.util.Arrays.equals(bytes, that.bytes); } - + /** * Get a byte from a kim. * * @param at The position of the byte. The first byte is at 0. - * * @return The byte. - * * @throws JSONException if there is no byte at that position. */ public int get(final int at) throws JSONException { @@ -271,25 +264,22 @@ public class Kim { } return (bytes[at]) & 0xFF; } - + /** * Returns a hash code value for the kim. */ - @Override - public int hashCode() { + @Override public int hashCode() { return hashcode; } - + /** * Produce a UTF-16 String from this kim. The number of codepoints in the string will not be greater than the number * of bytes in the kim, although it could be less. * * @return The string. A kim memoizes its string representation. - * * @throws JSONException if the kim is not valid. */ - @Override - public String toString() throws JSONException { + @Override public String toString() throws JSONException { if (string == null) { int c; int length = 0; diff --git a/Core/src/main/java/com/intellectualcrafters/json/Property.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/Property.java similarity index 93% rename from Core/src/main/java/com/intellectualcrafters/json/Property.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/json/Property.java index cef76fc83..7ace1989b 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/Property.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/Property.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.json; +package com.github.intellectualsites.plotsquared.json; import java.util.Enumeration; import java.util.Iterator; @@ -15,12 +15,11 @@ public class Property { * Converts a property file object into a JSONObject. The property file object is a table of name value pairs. * * @param properties java.util.Properties - * * @return JSONObject - * * @throws JSONException */ - public static JSONObject toJSONObject(final java.util.Properties properties) throws JSONException { + public static JSONObject toJSONObject(final java.util.Properties properties) + throws JSONException { final JSONObject jo = new JSONObject(); if ((properties != null) && !properties.isEmpty()) { final Enumeration enumProperties = properties.propertyNames(); @@ -31,14 +30,12 @@ public class Property { } return jo; } - + /** * Converts the JSONObject into a property file object. * * @param jo JSONObject - * * @return java.util.Properties - * * @throws JSONException */ public static Properties toProperties(final JSONObject jo) throws JSONException { diff --git a/Core/src/main/java/com/intellectualcrafters/json/XML.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/XML.java similarity index 95% rename from Core/src/main/java/com/intellectualcrafters/json/XML.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/json/XML.java index 58ecb4407..51a0cdb10 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/XML.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/XML.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.json; +package com.github.intellectualsites.plotsquared.json; import java.util.Iterator; @@ -46,12 +46,11 @@ class XML { } return sb.toString(); } - + /** * Throw an exception if the string contains whitespace. Whitespace is not allowed in tagNames and attributes. * * @param string A string. - * * @throws JSONException */ static void noSpace(String string) throws JSONException { @@ -65,19 +64,18 @@ class XML { } } } - + /** * Scan the content following the named tag, attaching it to the context. * * @param x The XMLTokener containing the source string. * @param context The JSONObject that will include the new material. * @param name The tag name. - * * @return true if the close tag is processed. - * * @throws JSONException */ - private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException { + private static boolean parse(XMLTokener x, JSONObject context, String name) + throws JSONException { // Test for and skip past these forms: // // @@ -147,7 +145,7 @@ class XML { String tagName = (String) token; token = null; JSONObject jsonobject = new JSONObject(); - for (;;) { + for (; ; ) { if (token == null) { token = x.nextToken(); } @@ -178,7 +176,7 @@ class XML { return false; // Content, between <...> and } else if (token == GT) { - for (;;) { + for (; ; ) { token = x.nextContent(); if (token == null) { if (tagName != null) { @@ -195,7 +193,8 @@ class XML { if (parse(x, jsonobject, tagName)) { if (jsonobject.length() == 0) { context.accumulate(tagName, ""); - } else if ((jsonobject.length() == 1) && (jsonobject.opt("content") != null)) { + } else if ((jsonobject.length() == 1) && (jsonobject.opt("content") + != null)) { context.accumulate(tagName, jsonobject.opt("content")); } else { context.accumulate(tagName, jsonobject); @@ -210,14 +209,13 @@ class XML { } } } - + /** * Try to convert a string into a number, boolean, or null. If the string can't be converted, return the string. * This is much less ambitious than JSONObject.stringToValue, especially because it does not attempt to convert plus * forms, octal forms, hex forms, or E forms lacking decimal points. * * @param string A String. - * * @return A simple JSON value. */ static Object stringToValue(String string) { @@ -245,7 +243,8 @@ class XML { if (value.toString().equals(string)) { return value; } - } catch (NumberFormatException ignored) {} + } catch (NumberFormatException ignored) { + } } return string; } @@ -258,28 +257,24 @@ class XML { } return jo; } - + /** * Convert a JSONObject into a well-formed, element-normal XML string. * * @param object A JSONObject. - * * @return A string. - * * @throws JSONException */ public static String toString(Object object) throws JSONException { return toString(object, null); } - + /** * Convert a JSONObject into a well-formed, element-normal XML string. * * @param object A JSONObject. * @param tagName The optional name of the enclosing tag. - * * @return A string. - * * @throws JSONException */ public static String toString(Object object, String tagName) throws JSONException { @@ -369,8 +364,11 @@ class XML { return sb.toString(); } else { string = escape(object.toString()); - return (tagName == null) ? '"' + string + '"' : - string.isEmpty() ? '<' + tagName + "/>" : '<' + tagName + '>' + string + "'; + return (tagName == null) ? + '"' + string + '"' : + string.isEmpty() ? + '<' + tagName + "/>" : + '<' + tagName + '>' + string + "'; } } } diff --git a/Core/src/main/java/com/intellectualcrafters/json/XMLTokener.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/XMLTokener.java similarity index 96% rename from Core/src/main/java/com/intellectualcrafters/json/XMLTokener.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/json/XMLTokener.java index 51f7ff639..96d65541f 100644 --- a/Core/src/main/java/com/intellectualcrafters/json/XMLTokener.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/XMLTokener.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.json; +package com.github.intellectualsites.plotsquared.json; import java.util.HashMap; @@ -13,6 +13,7 @@ public class XMLTokener extends JSONTokener { * The table of entity values. It initially contains Character values for amp, apos, gt, lt, quot. */ public static final HashMap entity; + static { entity = new HashMap<>(8); entity.put("amp", XML.AMP); @@ -21,7 +22,7 @@ public class XMLTokener extends JSONTokener { entity.put("lt", XML.LT); entity.put("quot", XML.QUOT); } - + /** * Construct an XMLTokener from a string. * @@ -30,36 +31,35 @@ public class XMLTokener extends JSONTokener { public XMLTokener(final String s) { super(s); } - + /** * Get the text in the CDATA block. * * @return The string up to the ]]>. - * * @throws JSONException If the ]]> is not found. */ public String nextCDATA() throws JSONException { final StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { char c = next(); if (end()) { throw syntaxError("Unclosed CDATA"); } sb.append(c); int i = sb.length() - 3; - if ((i >= 0) && (sb.charAt(i) == ']') && (sb.charAt(i + 1) == ']') && (sb.charAt(i + 2) == '>')) { + if ((i >= 0) && (sb.charAt(i) == ']') && (sb.charAt(i + 1) == ']') && (sb.charAt(i + 2) + == '>')) { sb.setLength(i); return sb.toString(); } } } - + /** * Get the next XML outer token, trimming whitespace. There are two kinds of tokens: the '<' character which begins * a markup tag, and the content text between markup tags. * * @return A string, or a '<' Character, or null if there is no more source text. - * * @throws JSONException */ public Object nextContent() throws JSONException { @@ -74,7 +74,7 @@ public class XMLTokener extends JSONTokener { return XML.LT; } StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { if ((c == '<') || (c == 0)) { back(); return sb.toString().trim(); @@ -87,20 +87,18 @@ public class XMLTokener extends JSONTokener { c = next(); } } - + /** * Return the next entity. These entities are translated to Characters: & " > < * ". * * @param ampersand An ampersand character. - * * @return A Character or an entity String if the entity is not recognized. - * * @throws JSONException If missing ';' in XML entity. */ public Object nextEntity(final char ampersand) throws JSONException { final StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { final char c = next(); if (Character.isLetterOrDigit(c) || (c == '#')) { sb.append(Character.toLowerCase(c)); @@ -114,13 +112,12 @@ public class XMLTokener extends JSONTokener { final Object object = entity.get(string); return object != null ? object : ampersand + string + ';'; } - + /** * Returns the next XML meta token. This is used for skipping over and structures. * * @return Syntax characters (< > / = ! ?) are returned as Character, and strings and names are * returned as Boolean. We don't care what the values actually are. - * * @throws JSONException If a string is not properly closed or if the XML is badly structured. */ public Object nextMeta() throws JSONException { @@ -147,7 +144,7 @@ public class XMLTokener extends JSONTokener { case '"': case '\'': q = c; - for (;;) { + for (; ; ) { c = next(); if (c == 0) { throw syntaxError("Unterminated string"); @@ -157,7 +154,7 @@ public class XMLTokener extends JSONTokener { } } default: - for (;;) { + for (; ; ) { c = next(); if (Character.isWhitespace(c)) { return Boolean.TRUE; @@ -178,13 +175,12 @@ public class XMLTokener extends JSONTokener { } } } - + /** * Get the next XML Token. These tokens are found inside of angle brackets. It may be one of these characters: * / >= ! ? or it may be a string wrapped in single quotes or double quotes, or it may be a name. * * @return a String or a Character. - * * @throws JSONException If the XML is not well formed. */ public Object nextToken() throws JSONException { @@ -209,12 +205,12 @@ public class XMLTokener extends JSONTokener { return XML.BANG; case '?': return XML.QUEST; - // Quoted string + // Quoted string case '"': case '\'': q = c; sb = new StringBuilder(); - for (;;) { + for (; ; ) { c = next(); if (c == 0) { throw syntaxError("Unterminated string"); @@ -231,7 +227,7 @@ public class XMLTokener extends JSONTokener { default: // Name sb = new StringBuilder(); - for (;;) { + for (; ; ) { sb.append(c); c = next(); if (Character.isWhitespace(c)) { @@ -257,13 +253,12 @@ public class XMLTokener extends JSONTokener { } } } - + /** * Skip characters until past the requested string. If it is not found, we are left at the end of the source with a * result of false. * * @param to A string to skip past. - * * @throws JSONException */ public boolean skipPast(final String to) throws JSONException { @@ -283,7 +278,7 @@ public class XMLTokener extends JSONTokener { circle[i] = c; } /* We will loop, possibly for all of the remaining characters. */ - for (int offset = 0; ;) { + for (int offset = 0; ; ) { int j = offset; boolean b = true; /* Compare the circle buffer with the to string. */ diff --git a/Core/src/main/java/com/intellectualcrafters/plot/IPlotMain.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/IPlotMain.java similarity index 80% rename from Core/src/main/java/com/intellectualcrafters/plot/IPlotMain.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/IPlotMain.java index 5ce7beb64..a1ea8e725 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/IPlotMain.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/IPlotMain.java @@ -1,22 +1,13 @@ -package com.intellectualcrafters.plot; +package com.github.intellectualsites.plotsquared.plot; -import com.intellectualcrafters.plot.generator.GeneratorWrapper; -import com.intellectualcrafters.plot.generator.HybridUtils; -import com.intellectualcrafters.plot.generator.IndependentPlotGenerator; -import com.intellectualcrafters.plot.logger.ILogger; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.AbstractTitle; -import com.intellectualcrafters.plot.util.ChatManager; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.InventoryUtil; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.SetupUtils; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandlerImplementation; -import com.intellectualcrafters.plot.util.WorldUtil; -import com.intellectualcrafters.plot.util.block.QueueProvider; +import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; +import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; +import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator; +import com.github.intellectualsites.plotsquared.plot.logger.ILogger; +import com.github.intellectualsites.plotsquared.plot.object.BlockRegistry; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.block.QueueProvider; import java.io.File; import java.util.List; @@ -25,24 +16,28 @@ public interface IPlotMain extends ILogger { /** * Log a message to console. + * * @param message The message to log */ void log(String message); /** * Get the `PlotSquared` directory. + * * @return The plugin directory */ File getDirectory(); /** * Get the directory containing all the worlds. + * * @return The directory containing the worlds */ File getWorldContainer(); /** * Wrap a player into a PlotPlayer object. + * * @param player The player to convert to a PlotPlayer * @return A PlotPlayer */ @@ -52,55 +47,63 @@ public interface IPlotMain extends ILogger { * Disable the implementation. * *

      - *
    • If a full disable isn't feasibly, just disable what it can. + *
    • If a full disable isn't feasibly, just disable what it can. *
    */ void disable(); /** * Get the version of the PlotSquared being used. + * * @return the plugin version */ int[] getPluginVersion(); /** * Get the version of the PlotSquared being used as a string. + * * @return the plugin version as a string */ String getPluginVersionString(); /** * Usually PlotSquared + * * @return */ String getPluginName(); /** * Get the version of Minecraft that is running. + * * @return */ int[] getServerVersion(); /** * Get the NMS package prefix. + * * @return The NMS package prefix */ String getNMSPackage(); /** * Get the schematic handler. + * * @return The {@link SchematicHandler} */ SchematicHandler initSchematicHandler(); /** * Get the Chat Manager. + * * @return The {@link ChatManager} */ ChatManager initChatManager(); /** * The task manager will run and manage Minecraft tasks. + * * @return */ TaskManager getTaskManager(); @@ -142,42 +145,49 @@ public interface IPlotMain extends ILogger { /** * Get the economy provider. + * * @return */ EconHandler getEconomyHandler(); /** - * Get the {@link com.intellectualcrafters.plot.util.block.QueueProvider} class. + * Get the {@link QueueProvider} class. + * * @return */ QueueProvider initBlockQueue(); /** * Get the {@link WorldUtil} class. + * * @return */ WorldUtil initWorldUtil(); /** * Get the EventUtil class. + * * @return */ EventUtil initEventUtil(); /** * Get the chunk manager. + * * @return */ ChunkManager initChunkManager(); /** * Get the {@link SetupUtils} class. + * * @return */ SetupUtils initSetupUtils(); /** * Get {@link HybridUtils} class. + * * @return */ HybridUtils initHybridUtils(); @@ -189,6 +199,7 @@ public interface IPlotMain extends ILogger { /** * If a world is already loaded, set the generator (use NMS if required). + * * @param world The world to set the generator */ void setGenerator(String world); @@ -196,6 +207,7 @@ public interface IPlotMain extends ILogger { /** * Get the {@link UUIDHandlerImplementation} which will cache and * provide UUIDs. + * * @return */ UUIDHandlerImplementation initUUIDHandler(); @@ -203,6 +215,7 @@ public interface IPlotMain extends ILogger { /** * Get the {@link InventoryUtil} class (used for implementation specific * inventory guis). + * * @return */ InventoryUtil initInventoryUtil(); @@ -210,18 +223,21 @@ public interface IPlotMain extends ILogger { /** * Run the converter for the implementation (not necessarily PlotMe, just * any plugin that we can convert from). + * * @return */ boolean initPlotMeConverter(); /** * Unregister a PlotPlayer from cache e.g. if they have logged off. + * * @param player */ void unregister(PlotPlayer player); /** * Get the generator wrapper for a world (world) and generator (name). + * * @param world * @param name * @return @@ -244,15 +260,22 @@ public interface IPlotMain extends ILogger { /** * Usually HybridGen + * * @return Default implementation generator */ IndependentPlotGenerator getDefaultGenerator(); /** * Get the class that will manage player titles. + * * @return */ AbstractTitle initTitleManager(); List getPluginIds(); + + BlockRegistry getBlockRegistry(); + + LegacyMappings getLegacyMappings(); + } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/Platform.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/Platform.java new file mode 100644 index 000000000..b7eb33b83 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/Platform.java @@ -0,0 +1,6 @@ +package com.github.intellectualsites.plotsquared.plot; + +public enum Platform { + Bukkit, Sponge, Spigot, Cauldron + +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/PS.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotSquared.java similarity index 69% rename from Core/src/main/java/com/intellectualcrafters/plot/PS.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotSquared.java index 98a2a6af5..a13faac54 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/PS.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotSquared.java @@ -1,85 +1,45 @@ -package com.intellectualcrafters.plot; +package com.github.intellectualsites.plotsquared.plot; -import com.intellectualcrafters.configuration.ConfigurationSection; -import com.intellectualcrafters.configuration.MemorySection; -import com.intellectualcrafters.configuration.file.YamlConfiguration; -import com.intellectualcrafters.plot.commands.WE_Anywhere; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Configuration; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.config.Storage; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.database.Database; -import com.intellectualcrafters.plot.database.SQLManager; -import com.intellectualcrafters.plot.generator.GeneratorWrapper; -import com.intellectualcrafters.plot.generator.HybridPlotWorld; -import com.intellectualcrafters.plot.generator.HybridUtils; -import com.intellectualcrafters.plot.generator.IndependentPlotGenerator; -import com.intellectualcrafters.plot.logger.DelegateLogger; -import com.intellectualcrafters.plot.logger.ILogger; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotCluster; -import com.intellectualcrafters.plot.object.PlotFilter; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotManager; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RegionWrapper; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.StringWrapper; -import com.intellectualcrafters.plot.object.worlds.DefaultPlotAreaManager; -import com.intellectualcrafters.plot.object.worlds.PlotAreaManager; -import com.intellectualcrafters.plot.object.worlds.SinglePlotArea; -import com.intellectualcrafters.plot.object.worlds.SinglePlotAreaManager; -import com.intellectualcrafters.plot.util.AbstractTitle; -import com.intellectualcrafters.plot.util.ChatManager; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.CommentManager; -import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.InventoryUtil; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.ReflectionUtils; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.SetupUtils; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.WorldUtil; -import com.intellectualcrafters.plot.util.block.GlobalBlockQueue; -import com.intellectualcrafters.plot.util.expiry.ExpireManager; -import com.intellectualcrafters.plot.util.expiry.ExpiryTask; -import com.plotsquared.listener.WESubscriber; +import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection; +import com.github.intellectualsites.plotsquared.configuration.MemorySection; +import com.github.intellectualsites.plotsquared.configuration.file.YamlConfiguration; +import com.github.intellectualsites.plotsquared.configuration.serialization.ConfigurationSerialization; +import com.github.intellectualsites.plotsquared.plot.commands.WE_Anywhere; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Configuration; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.config.Storage; +import com.github.intellectualsites.plotsquared.plot.database.*; +import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; +import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld; +import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; +import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator; +import com.github.intellectualsites.plotsquared.plot.listener.WESubscriber; +import com.github.intellectualsites.plotsquared.plot.logger.ILogger; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.worlds.DefaultPlotAreaManager; +import com.github.intellectualsites.plotsquared.plot.object.worlds.PlotAreaManager; +import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea; +import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotAreaManager; +import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; +import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpiryTask; import com.sk89q.worldedit.WorldEdit; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; +import lombok.Getter; +import lombok.NonNull; +import lombok.Setter; + +import javax.annotation.Nullable; +import java.io.*; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.sql.SQLException; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -87,75 +47,92 @@ import java.util.zip.ZipInputStream; /** * An implementation of the core, with a static getter for easy access. */ -public class PS{ - private static PS instance; +@SuppressWarnings({"unused", "WeakerAccess"}) public class PlotSquared { + private static final Set EMPTY_SET = + Collections.unmodifiableSet(Collections.emptySet()); + private static PlotSquared instance; // Implementation public final IPlotMain IMP; - // Implementation logger - private ILogger logger; // Current thread private final Thread thread; - // Platform / Version / Update URL - private Updater updater; - private PlotVersion version; // WorldEdit instance public WorldEdit worldedit; - // Files and configuration - private File jarFile = null; // This file public File styleFile; public File configFile; public File worldsFile; public File commandsFile; public File translationFile; - private File storageFile; public YamlConfiguration style; public YamlConfiguration config; public YamlConfiguration worlds; public YamlConfiguration storage; public YamlConfiguration commands; - // Temporary hold the plots/clusters before the worlds load + // Temporary hold the plots/clusters before the worlds load public HashMap> clusters_tmp; public HashMap> plots_tmp; - - private PlotAreaManager manager; + // Implementation logger + @Setter @Getter private ILogger logger; + // Platform / Version / Update URL + @Getter private Updater updater; + private PlotVersion version; + // Files and configuration + @Getter private File jarFile = null; // This file + private File storageFile; + @Getter private PlotAreaManager plotAreaManager; /** * Initialize PlotSquared with the desired Implementation class. + * * @param iPlotMain Implementation of {@link IPlotMain} used - * @param platform The platform being used + * @param platform The platform being used */ - public PS(IPlotMain iPlotMain, String platform) { - PS.instance = this; + public PlotSquared(final IPlotMain iPlotMain, final String platform) { + if (instance != null) { + throw new IllegalStateException("Cannot re-initialize the PlotSquared singleton"); + } + instance = this; + this.thread = Thread.currentThread(); this.IMP = iPlotMain; this.logger = iPlotMain; Settings.PLATFORM = platform; + + // + // Register configuration serializable classes + // + ConfigurationSerialization.registerClass(PlotBlock.class); + ConfigurationSerialization.registerClass(BlockBucket.class); + try { new ReflectionUtils(this.IMP.getNMSPackage()); try { - URL url = PS.class.getProtectionDomain().getCodeSource().getLocation(); - this.jarFile = new File(new URL(url.toURI().toString().split("\\!")[0].replaceAll("jar:file", "file")).toURI().getPath()); + URL url = PlotSquared.class.getProtectionDomain().getCodeSource().getLocation(); + this.jarFile = new File( + new URL(url.toURI().toString().split("\\!")[0].replaceAll("jar:file", "file")) + .toURI().getPath()); } catch (MalformedURLException | URISyntaxException | SecurityException e) { e.printStackTrace(); this.jarFile = new File(this.IMP.getDirectory().getParentFile(), "PlotSquared.jar"); if (!this.jarFile.exists()) { - this.jarFile = new File(this.IMP.getDirectory().getParentFile(), "PlotSquared-" + platform + ".jar"); + this.jarFile = new File(this.IMP.getDirectory().getParentFile(), + "PlotSquared-" + platform + ".jar"); } } if (getJavaVersion() < 1.8) { - PS.log(C.CONSOLE_JAVA_OUTDATED.f(IMP.getPluginName())); + PlotSquared.log(C.CONSOLE_JAVA_OUTDATED.f(IMP.getPluginName())); } TaskManager.IMP = this.IMP.getTaskManager(); setupConfigs(); - this.translationFile = - MainUtil.getFile(this.IMP.getDirectory(), Settings.Paths.TRANSLATIONS + File.separator + IMP.getPluginName() + ".use_THIS.yml"); + this.translationFile = MainUtil.getFile(this.IMP.getDirectory(), + Settings.Paths.TRANSLATIONS + File.separator + IMP.getPluginName() + + ".use_THIS.yml"); C.load(this.translationFile); - // Setup manager + // Setup plotAreaManager if (Settings.Enabled_Components.WORLDS) { - this.manager = new SinglePlotAreaManager(); + this.plotAreaManager = new SinglePlotAreaManager(); } else { - this.manager = new DefaultPlotAreaManager(); + this.plotAreaManager = new DefaultPlotAreaManager(); } // Database @@ -165,7 +142,8 @@ public class PS{ // Comments CommentManager.registerDefaultInboxes(); // Kill entities - if (Settings.Enabled_Components.KILL_ROAD_MOBS || Settings.Enabled_Components.KILL_ROAD_VEHICLES) { + if (Settings.Enabled_Components.KILL_ROAD_MOBS + || Settings.Enabled_Components.KILL_ROAD_VEHICLES) { this.IMP.runEntityTask(); } if (Settings.Enabled_Components.EVENTS) { @@ -178,7 +156,7 @@ public class PS{ if (Settings.Enabled_Components.METRICS) { this.IMP.startMetrics(); } else { - PS.log(C.CONSOLE_PLEASE_ENABLE_METRICS.f(IMP.getPluginName())); + PlotSquared.log(C.CONSOLE_PLEASE_ENABLE_METRICS.f(IMP.getPluginName())); } if (Settings.Enabled_Components.CHUNK_PROCESSOR) { this.IMP.registerChunkProcessor(); @@ -189,7 +167,7 @@ public class PS{ startUuidCatching(); } else { // Start these separately - UUIDHandler.add(new StringWrapper("*"), DBFunc.everyone); + UUIDHandler.add(new StringWrapper("*"), DBFunc.EVERYONE); startExpiryTasks(); startPlotMeConversion(); } @@ -222,7 +200,7 @@ public class PS{ if (Settings.Enabled_Components.WORLDEDIT_RESTRICTIONS) { try { if (this.IMP.initWorldEdit()) { - PS.debug(IMP.getPluginName() + " hooked into WorldEdit."); + PlotSquared.debug(IMP.getPluginName() + " hooked into WorldEdit."); this.worldedit = WorldEdit.getInstance(); WorldEdit.getInstance().getEventBus().register(new WESubscriber()); if (Settings.Enabled_Components.COMMANDS) { @@ -231,15 +209,15 @@ public class PS{ } } catch (Throwable e) { - PS.debug("Incompatible version of WorldEdit, please upgrade: http://builds.enginehub.org/job/worldedit?branch=master"); + PlotSquared.debug( + "Incompatible version of WorldEdit, please upgrade: http://builds.enginehub.org/job/worldedit?branch=master"); } } // Economy if (Settings.Enabled_Components.ECONOMY) { TaskManager.runTask(new Runnable() { - @Override - public void run() { - EconHandler.manager = PS.this.IMP.getEconomyHandler(); + @Override public void run() { + EconHandler.manager = PlotSquared.this.IMP.getEconomyHandler(); } }); } @@ -248,14 +226,12 @@ public class PS{ if (Settings.Enabled_Components.UPDATER) { updater = new Updater(); TaskManager.IMP.taskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { updater.update(getPlatform(), getVersion()); } }); TaskManager.IMP.taskRepeatAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { updater.update(getPlatform(), getVersion()); } }, 36000); @@ -273,17 +249,19 @@ public class PS{ } } TaskManager.runTaskLater(new Runnable() { - @Override - public void run() { + @Override public void run() { for (String world : section.getKeys(false)) { if (world.equals("CheckingPlotSquaredGenerator")) { continue; } if (!WorldUtil.IMP.isWorld(world) && !world.equals("*")) { - debug("&c`" + world + "` was not properly loaded - " + IMP.getPluginName() + " will now try to load it properly: "); - debug("&8 - &7Are you trying to delete this world? Remember to remove it from the settings.yml, bukkit.yml and multiverse worlds.yml"); - debug("&8 - &7Your world management plugin may be faulty (or non existent)"); - PS.this.IMP.setGenerator(world); + debug("&c`" + world + "` was not properly loaded - " + IMP + .getPluginName() + " will now try to load it properly: "); + debug( + "&8 - &7Are you trying to delete this world? Remember to remove it from the settings.yml, bukkit.yml and multiverse worlds.yml"); + debug( + "&8 - &7Your world management plugin may be faulty (or non existent)"); + PlotSquared.this.IMP.setGenerator(world); } } } @@ -305,7 +283,8 @@ public class PS{ } catch (Throwable e) { e.printStackTrace(); } - PS.log(C.ENABLED.f(IMP.getPluginName())); + + PlotSquared.log(C.ENABLED.f(IMP.getPluginName())); } /** @@ -313,8 +292,8 @@ public class PS{ * * @return instance of PlotSquared */ - public static PS get() { - return PS.instance; + public static PlotSquared get() { + return PlotSquared.instance; } public static IPlotMain imp() { @@ -334,7 +313,7 @@ public class PS{ if (message == null || message.toString().isEmpty()) { return; } - PS.get().getLogger().log(StringMan.getString(message)); + PlotSquared.get().getLogger().log(StringMan.getString(message)); } /** @@ -343,55 +322,21 @@ public class PS{ * @param message Message to log * @see IPlotMain#log(String) */ - public static void debug(Object message) { + public static void debug(@Nullable Object message) { if (Settings.DEBUG) { - PS.log(message); + PlotSquared.log(message); } } - /** - * Get the current logger. - * - * @return The assigned logger - */ - public ILogger getLogger() { - return logger; - } - - /** - * The plugin updater - * @return - */ - public Updater getUpdater() { - return updater; - } - - public PlotAreaManager getPlotAreaManager() { - return manager; - } - - /** - * Set the Logger. - * @see DelegateLogger - * @see #getLogger() - * @param logger the logger the plugin should use - */ - public void setLogger(ILogger logger) { - this.logger = logger; - } - private void startUuidCatching() { TaskManager.runTaskLater(new Runnable() { - @Override - public void run() { + @Override public void run() { debug("Starting UUID caching"); UUIDHandler.startCaching(new Runnable() { - @Override - public void run() { - UUIDHandler.add(new StringWrapper("*"), DBFunc.everyone); + @Override public void run() { + UUIDHandler.add(new StringWrapper("*"), DBFunc.EVERYONE); foreachPlotRaw(new RunnableVal() { - @Override - public void run(Plot plot) { + @Override public void run(Plot plot) { if (plot.hasOwner() && plot.temp != -1) { if (UUIDHandler.getName(plot.owner) == null) { UUIDHandler.implementation.unknown.add(plot.owner); @@ -421,14 +366,17 @@ public class PS{ private void startPlotMeConversion() { if (Settings.Enabled_Components.PLOTME_CONVERTER || Settings.PlotMe.CACHE_UUDS) { TaskManager.IMP.taskAsync(new Runnable() { - @Override - public void run() { - if (PS.this.IMP.initPlotMeConverter()) { - PS.log("&c=== IMPORTANT ==="); - PS.log("&cTHIS MESSAGE MAY BE EXTREMELY HELPFUL IF YOU HAVE TROUBLE CONVERTING PlotMe!"); - PS.log("&c - Make sure 'UUID.read-from-disk' is disabled (false)!"); - PS.log("&c - Sometimes the database can be locked, deleting PlotMe.jar beforehand will fix the issue!"); - PS.log("&c - After the conversion is finished, please set 'plotme-converter' to false in the " + @Override public void run() { + if (PlotSquared.this.IMP.initPlotMeConverter()) { + PlotSquared.log("&c=== IMPORTANT ==="); + PlotSquared.log( + "&cTHIS MESSAGE MAY BE EXTREMELY HELPFUL IF YOU HAVE TROUBLE CONVERTING PlotMe!"); + PlotSquared + .log("&c - Make sure 'UUID.read-from-disk' is disabled (false)!"); + PlotSquared.log( + "&c - Sometimes the database can be locked, deleting PlotMe.jar beforehand will fix the issue!"); + PlotSquared.log( + "&c - After the conversion is finished, please set 'plotme-converter' to false in the " + "'settings.yml'"); } Settings.Enabled_Components.PLOTME_CONVERTER = false; @@ -443,17 +391,19 @@ public class PS{ /** * Check if `version` is >= `version2`. - * @param version - * @param version2 + * + * @param version First version + * @param version2 Second version * @return true if `version` is >= `version2` */ public boolean checkVersion(int[] version, int... version2) { - return version[0] > version2[0] || version[0] == version2[0] && version[1] > version2[1] || version[0] == version2[0] - && version[1] == version2[1] && version[2] >= version2[2]; + return version[0] > version2[0] || version[0] == version2[0] && version[1] > version2[1] + || version[0] == version2[0] && version[1] == version2[1] && version[2] >= version2[2]; } /** * Get the current PlotSquared version. + * * @return current version in config or null */ public PlotVersion getVersion() { @@ -462,8 +412,9 @@ public class PS{ /** * Get the server platform this plugin is running on this is running on. - * + *

    *

    This will be either Bukkit or Sponge

    + * * @return the server implementation */ public String getPlatform() { @@ -510,7 +461,8 @@ public class PS{ Set clusters; if (clusters_tmp == null || (clusters = clusters_tmp.remove(plotArea.toString())) == null) { if (plotArea.TYPE == 2) { - clusters = this.clusters_tmp != null ? this.clusters_tmp.get(plotArea.worldname) : null; + clusters = + this.clusters_tmp != null ? this.clusters_tmp.get(plotArea.worldname) : null; if (clusters != null) { Iterator iterator = clusters.iterator(); while (iterator.hasNext()) { @@ -527,7 +479,7 @@ public class PS{ cluster.setArea(plotArea); } } - manager.addPlotArea(plotArea); + plotAreaManager.addPlotArea(plotArea); plotArea.setupBorder(); } @@ -537,7 +489,7 @@ public class PS{ * @param area the {@code PlotArea} to remove */ public void removePlotArea(PlotArea area) { - manager.removePlotArea(area); + plotAreaManager.removePlotArea(area); setPlotsTmp(area); } @@ -568,25 +520,25 @@ public class PS{ } public Set getClusters(String world) { - HashSet set = new HashSet<>(); + Set set = new HashSet<>(); for (PlotArea area : getPlotAreas(world)) { set.addAll(area.getClusters()); } - return set; + return Collections.unmodifiableSet(set); } /** * Get all the base plots in a single set (for merged plots it just returns * the bottom plot). + * * @return Set of base Plots */ public Set getBasePlots() { int size = getPlotCount(); final Set result = new HashSet<>(size); foreachPlotArea(new RunnableVal() { - @Override - public void run(PlotArea value) { + @Override public void run(PlotArea value) { for (Plot plot : value.getPlots()) { if (!plot.isBasePlot()) { continue; @@ -595,7 +547,7 @@ public class PS{ } } }); - return result; + return Collections.unmodifiableSet(result); } public List sortPlotsByTemp(Collection plots) { @@ -626,8 +578,7 @@ public class PS{ } } Collections.sort(overflow, new Comparator() { - @Override - public int compare(Plot a, Plot b) { + @Override public int compare(Plot a, Plot b) { return a.hashCode() - b.hashCode(); } }); @@ -637,14 +588,15 @@ public class PS{ /** * Sort plots by hashcode. + * * @param plots the collection of plots to sort * @return the sorted collection * @deprecated Unchecked, please use - * {@link #sortPlots(Collection, SortType, PlotArea)} which has - * additional checks before calling this + * {@link #sortPlots(Collection, SortType, PlotArea)} which has + * additional checks before calling this */ - @Deprecated - public ArrayList sortPlotsByHash(Collection plots) { + // TODO: Re-evaluate deprecation of this, as it's being used internally + @Deprecated public ArrayList sortPlotsByHash(Collection plots) { int hardmax = 256000; int max = 0; int overflowSize = 0; @@ -693,10 +645,11 @@ public class PS{ /** * Unchecked, use {@link #sortPlots(Collection, SortType, PlotArea)} instead which will in turn call this. + * * @param input an array of plots to sort */ - @Deprecated - public void sortPlotsByHash(Plot[] input) { + // TODO: Re-evaluate deprecation of this, as it's being used internally + @Deprecated public void sortPlotsByHash(Plot[] input) { List[] bucket = new ArrayList[32]; for (int i = 0; i < bucket.length; i++) { bucket[i] = new ArrayList<>(); @@ -723,8 +676,8 @@ public class PS{ } } - @Deprecated - public ArrayList sortPlotsByTimestamp(Collection plots) { + // TODO: Re-evaluate deprecation of this, as it's being used internally + @Deprecated public ArrayList sortPlotsByTimestamp(Collection plots) { int hardMax = 256000; int max = 0; int overflowSize = 0; @@ -773,12 +726,13 @@ public class PS{ /** * Sort plots by creation timestamp. + * * @param input - * @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, PlotArea)} instead which will call this after checks * @return + * @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, PlotArea)} instead which will call this after checks */ - @Deprecated - public List sortPlotsByModified(Collection input) { + // TODO: Re-evaluate deprecation of this, as it's being used internally + @Deprecated public List sortPlotsByModified(Collection input) { List list; if (input instanceof List) { list = (List) input; @@ -786,9 +740,9 @@ public class PS{ list = new ArrayList<>(input); } Collections.sort(list, new Comparator() { - @Override - public int compare(Plot a, Plot b) { - return Long.compare(ExpireManager.IMP.getTimestamp(a.owner), ExpireManager.IMP.getTimestamp(b.owner)); + @Override public int compare(Plot a, Plot b) { + return Long.compare(ExpireManager.IMP.getTimestamp(a.owner), + ExpireManager.IMP.getTimestamp(b.owner)); } }); return list; @@ -797,23 +751,25 @@ public class PS{ /** * Sort a collection of plots by world (with a priority world), then * by hashcode. - * @param plots the plots to sort - * @param type The sorting method to use for each world (timestamp, or hash) + * + * @param plots the plots to sort + * @param type The sorting method to use for each world (timestamp, or hash) * @param priorityArea Use null, "world", or "gibberish" if you - * want default world order + * want default world order * @return ArrayList of plot */ - public ArrayList sortPlots(Collection plots, SortType type, final PlotArea priorityArea) { + public ArrayList sortPlots(Collection plots, SortType type, + final PlotArea priorityArea) { // group by world // sort each HashMap> map = new HashMap<>(); int totalSize = getPlotCount(); if (plots.size() == totalSize) { - for (PlotArea area : manager.getAllPlotAreas()) { + for (PlotArea area : plotAreaManager.getAllPlotAreas()) { map.put(area, area.getPlots()); } } else { - for (PlotArea area : manager.getAllPlotAreas()) { + for (PlotArea area : plotAreaManager.getAllPlotAreas()) { map.put(area, new ArrayList(0)); } Collection lastList = null; @@ -828,10 +784,9 @@ public class PS{ } } } - List areas = Arrays.asList(manager.getAllPlotAreas()); + List areas = Arrays.asList(plotAreaManager.getAllPlotAreas()); Collections.sort(areas, new Comparator() { - @Override - public int compare(PlotArea a, PlotArea b) { + @Override public int compare(PlotArea a, PlotArea b) { if (priorityArea != null) { if (a.equals(priorityArea)) { return -1; @@ -867,14 +822,14 @@ public class PS{ /** * A more generic way to filter plots - make your own method * if you need complex filters. + * * @param filters the filter * @return a filtered set of plots */ public Set getPlots(final PlotFilter... filters) { final HashSet set = new HashSet<>(); foreachPlotArea(new RunnableVal() { - @Override - public void run(PlotArea value) { + @Override public void run(PlotArea value) { for (PlotFilter filter : filters) { if (!filter.allowsArea(value)) { return; @@ -897,14 +852,14 @@ public class PS{ /** * Get all the plots in a single set. + * * @return Set of Plots */ public Set getPlots() { int size = getPlotCount(); final Set result = new HashSet<>(size); foreachPlotArea(new RunnableVal() { - @Override - public void run(PlotArea value) { + @Override public void run(PlotArea value) { result.addAll(value.getPlots()); } }); @@ -936,18 +891,20 @@ public class PS{ /** * Get all the plots owned by a player name. - * @param world the world + * + * @param world the world * @param player the plot owner * @return Set of Plot */ public Set getPlots(String world, String player) { - UUID uuid = UUIDHandler.getUUID(player, null); + final UUID uuid = UUIDHandler.getUUID(player, null); return getPlots(world, uuid); } /** * Get all the plots owned by a player name. - * @param area the PlotArea + * + * @param area the PlotArea * @param player the plot owner * @return Set of Plot */ @@ -958,7 +915,8 @@ public class PS{ /** * Get all plots by a PlotPlayer. - * @param world the world + * + * @param world the world * @param player the plot owner * @return Set of plot */ @@ -968,7 +926,8 @@ public class PS{ /** * Get all plots by a PlotPlayer. - * @param area the PlotArea + * + * @param area the PlotArea * @param player the plot owner * @return Set of plot */ @@ -978,67 +937,53 @@ public class PS{ /** * Get all plots by a UUID in a world. + * * @param world the world - * @param uuid the plot owner + * @param uuid the plot owner * @return Set of plot */ public Set getPlots(String world, UUID uuid) { - ArrayList myPlots = new ArrayList<>(); - for (Plot plot : getPlots(world)) { - if (plot.hasOwner()) { - if (plot.isOwnerAbs(uuid)) { - myPlots.add(plot); - } + final Set plots = new HashSet<>(); + for (final Plot plot : getPlots(world)) { + if (plot.hasOwner() && plot.isOwnerAbs(uuid)) { + plots.add(plot); } } - return new HashSet<>(myPlots); + return Collections.unmodifiableSet(plots); } /** * Get all plots by a UUID in an area. + * * @param area the {@code PlotArea} * @param uuid the plot owner - * @return Set of plot + * @return Set of plots */ public Set getPlots(PlotArea area, UUID uuid) { - ArrayList myplots = new ArrayList<>(); + final Set plots = new HashSet<>(); for (Plot plot : getPlots(area)) { - if (plot.hasOwner()) { - if (plot.isOwnerAbs(uuid)) { - myplots.add(plot); - } + if (plot.hasOwner() && plot.isOwnerAbs(uuid)) { + plots.add(plot); } } - return new HashSet<>(myplots); - } - - /** - * Use {@link #hasPlotArea(String)}. - * Note: Worlds may have more than one plot area - * @deprecated - * @param world the world - * @return if the world is a plotworld - */ - @Deprecated - public boolean isPlotWorld(String world) { - return hasPlotArea(world); + return Collections.unmodifiableSet(plots); } /** * Check if a plot world. + * * @param world the world - * @see #getPlotAreaByString(String) to get the PlotArea object * @return if a plot world is registered + * @see #getPlotAreaByString(String) to get the PlotArea object */ public boolean hasPlotArea(String world) { - return manager.getPlotAreas(world, null).length != 0; + return plotAreaManager.getPlotAreas(world, null).length != 0; } public Collection getPlots(String world) { - final HashSet set = new HashSet<>(); + final Set set = new HashSet<>(); foreachPlotArea(world, new RunnableVal() { - @Override - public void run(PlotArea value) { + @Override public void run(PlotArea value) { set.addAll(value.getPlots()); } }); @@ -1047,6 +992,7 @@ public class PS{ /** * Get the plots for a PlotPlayer. + * * @param player the player to retrieve the plots for * @return Set of Plot */ @@ -1055,7 +1001,7 @@ public class PS{ } public Collection getPlots(PlotArea area) { - return area == null ? new HashSet() : area.getPlots(); + return area == null ? EMPTY_SET : area.getPlots(); } public Plot getPlot(PlotArea area, PlotId id) { @@ -1068,63 +1014,64 @@ public class PS{ /** * Get the plots for a UUID. + * * @param uuid the plot owner * @return Set of Plot's owned by the player */ public Set getPlots(final UUID uuid) { - final ArrayList myPlots = new ArrayList<>(); + final Set plots = new HashSet<>(); foreachPlot(new RunnableVal() { - @Override - public void run(Plot value) { + @Override public void run(Plot value) { if (value.isOwnerAbs(uuid)) { - myPlots.add(value); + plots.add(value); } } }); - return new HashSet<>(myPlots); + return Collections.unmodifiableSet(plots); } public boolean hasPlot(final UUID uuid) { - for (PlotArea area : manager.getAllPlotAreas()) { - if (area.hasPlot(uuid)) return true; + for (final PlotArea area : plotAreaManager.getAllPlotAreas()) { + if (area.hasPlot(uuid)) + return true; } return false; } public Set getBasePlots(final UUID uuid) { - final ArrayList myplots = new ArrayList<>(); + final Set plots = new HashSet<>(); foreachBasePlot(new RunnableVal() { - @Override - public void run(Plot value) { + @Override public void run(Plot value) { if (value.isOwner(uuid)) { - myplots.add(value); + plots.add(value); } } }); - return new HashSet<>(myplots); + return Collections.unmodifiableSet(plots); } /** * Get the plots for a UUID. + * * @param uuid the UUID of the owner * @return Set of Plot */ public Set getPlotsAbs(final UUID uuid) { - final ArrayList myPlots = new ArrayList<>(); + final Set plots = new HashSet<>(); foreachPlot(new RunnableVal() { - @Override - public void run(Plot value) { + @Override public void run(Plot value) { if (value.isOwnerAbs(uuid)) { - myPlots.add(value); + plots.add(value); } } }); - return new HashSet<>(myPlots); + return Collections.unmodifiableSet(plots); } /** * Unregister a plot from local memory (does not call DB). - * @param plot the plot to remove + * + * @param plot the plot to remove * @param callEvent If to call an event about the plot being removed * @return true if plot existed | false if it didn't */ @@ -1150,25 +1097,26 @@ public class PS{ /** * This method is called by the PlotGenerator class normally. *
      - *
    • Initializes the PlotArea and PlotManager classes - *
    • Registers the PlotArea and PlotManager classes - *
    • Loads (and/or generates) the PlotArea configuration - *
    • Sets up the world border if configured + *
    • Initializes the PlotArea and PlotManager classes + *
    • Registers the PlotArea and PlotManager classes + *
    • Loads (and/or generates) the PlotArea configuration + *
    • Sets up the world border if configured *
    * *

    If loading an augmented plot world: *

      - *
    • Creates the AugmentedPopulator classes - *
    • Injects the AugmentedPopulator classes if required + *
    • Creates the AugmentedPopulator classes + *
    • Injects the AugmentedPopulator classes if required *
    - * @param world the world to load + * + * @param world the world to load * @param baseGenerator The generator for that world, or null */ public void loadWorld(String world, GeneratorWrapper baseGenerator) { if (world.equals("CheckingPlotSquaredGenerator")) { return; } - this.manager.addWorld(world); + this.plotAreaManager.addWorld(world); Set worlds; if (this.worlds.contains("worlds")) { worlds = this.worlds.getConfigurationSection("worlds").getKeys(false); @@ -1184,7 +1132,7 @@ public class PS{ type = 0; } if (type == 0) { - if (manager.getPlotAreas(world, null).length != 0) { + if (plotAreaManager.getPlotAreas(world, null).length != 0) { debug("World possibly already loaded: " + world); return; } @@ -1193,12 +1141,14 @@ public class PS{ plotGenerator = baseGenerator.getPlotGenerator(); } else if (worldSection != null) { String secondaryGeneratorName = worldSection.getString("generator.plugin"); - GeneratorWrapper secondaryGenerator = this.IMP.getGenerator(world, secondaryGeneratorName); + GeneratorWrapper secondaryGenerator = + this.IMP.getGenerator(world, secondaryGeneratorName); if (secondaryGenerator != null && secondaryGenerator.isFull()) { plotGenerator = secondaryGenerator.getPlotGenerator(); } else { String primaryGeneratorName = worldSection.getString("generator.init"); - GeneratorWrapper primaryGenerator = this.IMP.getGenerator(world, primaryGeneratorName); + GeneratorWrapper primaryGenerator = + this.IMP.getGenerator(world, primaryGeneratorName); if (primaryGenerator != null && primaryGenerator.isFull()) { plotGenerator = primaryGenerator.getPlotGenerator(); } else { @@ -1211,10 +1161,11 @@ public class PS{ // Conventional plot generator PlotArea plotArea = plotGenerator.getNewPlotArea(world, null, null, null); PlotManager plotManager = plotGenerator.getNewPlotManager(); - PS.log(C.PREFIX + "&aDetected world load for '" + world + "'"); - PS.log(C.PREFIX + "&3 - generator: &7" + baseGenerator + ">" + plotGenerator); - PS.log(C.PREFIX + "&3 - plotworld: &7" + plotArea.getClass().getName()); - PS.log(C.PREFIX + "&3 - manager: &7" + plotManager.getClass().getName()); + PlotSquared.log(C.PREFIX + "&aDetected world load for '" + world + "'"); + PlotSquared.log(C.PREFIX + "&3 - generator: &7" + baseGenerator + ">" + plotGenerator); + PlotSquared.log(C.PREFIX + "&3 - plotworld: &7" + plotArea.getClass().getName()); + PlotSquared + .log(C.PREFIX + "&3 - plotAreaManager: &7" + plotManager.getClass().getName()); if (!this.worlds.contains(path)) { this.worlds.createSection(path); worldSection = this.worlds.getConfigurationSection(path); @@ -1235,14 +1186,16 @@ public class PS{ } ConfigurationSection areasSection = worldSection.getConfigurationSection("areas"); if (areasSection == null) { - if (manager.getPlotAreas(world, null).length != 0) { + if (plotAreaManager.getPlotAreas(world, null).length != 0) { debug("World possibly already loaded: " + world); return; } - PS.log(C.PREFIX + "&aDetected world load for '" + world + "'"); + PlotSquared.log(C.PREFIX + "&aDetected world load for '" + world + "'"); String gen_string = worldSection.getString("generator.plugin", IMP.getPluginName()); if (type == 2) { - Set clusters = this.clusters_tmp != null ? this.clusters_tmp.get(world) : new HashSet(); + Set clusters = this.clusters_tmp != null ? + this.clusters_tmp.get(world) : + new HashSet(); if (clusters == null) { throw new IllegalArgumentException("No cluster exists for world: " + world); } @@ -1255,12 +1208,13 @@ public class PS{ worldSection.createSection("areas." + fullId); DBFunc.replaceWorld(world, world + ";" + name, pos1, pos2); // NPE - PS.log(C.PREFIX + "&3 - " + name + "-" + pos1 + "-" + pos2); + PlotSquared.log(C.PREFIX + "&3 - " + name + "-" + pos1 + "-" + pos2); GeneratorWrapper areaGen = this.IMP.getGenerator(world, gen_string); if (areaGen == null) { throw new IllegalArgumentException("Invalid Generator: " + gen_string); } - PlotArea pa = areaGen.getPlotGenerator().getNewPlotArea(world, name, pos1, pos2); + PlotArea pa = + areaGen.getPlotGenerator().getNewPlotArea(world, name, pos1, pos2); pa.saveConfiguration(worldSection); pa.loadDefaultConfiguration(worldSection); try { @@ -1268,10 +1222,12 @@ public class PS{ } catch (IOException e) { e.printStackTrace(); } - PS.log(C.PREFIX + "&c | &9generator: &7" + baseGenerator + ">" + areaGen); - PS.log(C.PREFIX + "&c | &9plotworld: &7" + pa); - PS.log(C.PREFIX + "&c | &9manager: &7" + pa); - PS.log(C.PREFIX + "&cNote: &7Area created for cluster:" + name + " (invalid or old configuration?)"); + PlotSquared + .log(C.PREFIX + "&c | &9generator: &7" + baseGenerator + ">" + areaGen); + PlotSquared.log(C.PREFIX + "&c | &9plotworld: &7" + pa); + PlotSquared.log(C.PREFIX + "&c | &9manager: &7" + pa); + PlotSquared.log(C.PREFIX + "&cNote: &7Area created for cluster:" + name + + " (invalid or old configuration?)"); areaGen.getPlotGenerator().initialize(pa); areaGen.augment(pa); toLoad.add(pa); @@ -1293,28 +1249,31 @@ public class PS{ } catch (IOException e) { e.printStackTrace(); } - PS.log(C.PREFIX + "&3 - generator: &7" + baseGenerator + ">" + areaGen); - PS.log(C.PREFIX + "&3 - plotworld: &7" + pa); - PS.log(C.PREFIX + "&3 - manager: &7" + pa.getPlotManager()); + PlotSquared.log(C.PREFIX + "&3 - generator: &7" + baseGenerator + ">" + areaGen); + PlotSquared.log(C.PREFIX + "&3 - plotworld: &7" + pa); + PlotSquared.log(C.PREFIX + "&3 - plotAreaManager: &7" + pa.getPlotManager()); areaGen.getPlotGenerator().initialize(pa); areaGen.augment(pa); addPlotArea(pa); return; } if (type == 1) { - throw new IllegalArgumentException("Invalid type for multi-area world. Expected `2`, got `" + 1 + "`"); + throw new IllegalArgumentException( + "Invalid type for multi-area world. Expected `2`, got `" + 1 + "`"); } for (String areaId : areasSection.getKeys(false)) { - PS.log(C.PREFIX + "&3 - " + areaId); + PlotSquared.log(C.PREFIX + "&3 - " + areaId); String[] split = areaId.split("(?<=[^;-])-"); if (split.length != 3) { - throw new IllegalArgumentException("Invalid Area identifier: " + areaId + ". Expected form `--`"); + throw new IllegalArgumentException("Invalid Area identifier: " + areaId + + ". Expected form `--`"); } String name = split[0]; PlotId pos1 = PlotId.fromString(split[1]); PlotId pos2 = PlotId.fromString(split[2]); if (pos1 == null || pos2 == null || name.isEmpty()) { - throw new IllegalArgumentException("Invalid Area identifier: " + areaId + ". Expected form `--`"); + throw new IllegalArgumentException("Invalid Area identifier: " + areaId + + ". Expected form `--`"); } PlotArea existing = getPlotArea(world, name); if (existing != null && name.equals(existing.id)) { @@ -1365,10 +1324,10 @@ public class PS{ } catch (IOException e) { e.printStackTrace(); } - PS.log(C.PREFIX + "&aDetected area load for '" + world + "'"); - PS.log(C.PREFIX + "&c | &9generator: &7" + baseGenerator + ">" + areaGen); - PS.log(C.PREFIX + "&c | &9plotworld: &7" + pa); - PS.log(C.PREFIX + "&c | &9manager: &7" + pa.getPlotManager()); + PlotSquared.log(C.PREFIX + "&aDetected area load for '" + world + "'"); + PlotSquared.log(C.PREFIX + "&c | &9generator: &7" + baseGenerator + ">" + areaGen); + PlotSquared.log(C.PREFIX + "&c | &9plotworld: &7" + pa); + PlotSquared.log(C.PREFIX + "&c | &9manager: &7" + pa.getPlotManager()); areaGen.getPlotGenerator().initialize(pa); areaGen.augment(pa); addPlotArea(pa); @@ -1379,11 +1338,11 @@ public class PS{ /** * Setup the configuration for a plot world based on world arguments. * - *

    + * * e.g. /mv create <world> normal -g PlotSquared:<args> * - * @param world The name of the world - * @param args The arguments + * @param world The name of the world + * @param args The arguments * @param generator the plot generator * @return boolean | if valid arguments were provided */ @@ -1395,7 +1354,7 @@ public class PS{ for (String element : split) { String[] pair = element.split("="); if (pair.length != 2) { - PS.log("&cNo value provided for: &7" + element); + PlotSquared.log("&cNo value provided for: &7" + element); return false; } String key = pair[0].toLowerCase(); @@ -1405,48 +1364,58 @@ public class PS{ switch (key) { case "s": case "size": - this.worlds.set(base + "plot.size", Configuration.INTEGER.parseString(value).shortValue()); + this.worlds.set(base + "plot.size", + Configuration.INTEGER.parseString(value).shortValue()); break; case "g": case "gap": - this.worlds.set(base + "road.width", Configuration.INTEGER.parseString(value).shortValue()); + this.worlds.set(base + "road.width", + Configuration.INTEGER.parseString(value).shortValue()); break; case "h": case "height": - this.worlds.set(base + "road.height", Configuration.INTEGER.parseString(value).shortValue()); - this.worlds.set(base + "plot.height", Configuration.INTEGER.parseString(value).shortValue()); - this.worlds.set(base + "wall.height", Configuration.INTEGER.parseString(value).shortValue()); + this.worlds.set(base + "road.height", + Configuration.INTEGER.parseString(value).shortValue()); + this.worlds.set(base + "plot.height", + Configuration.INTEGER.parseString(value).shortValue()); + this.worlds.set(base + "wall.height", + Configuration.INTEGER.parseString(value).shortValue()); break; case "f": case "floor": - this.worlds.set(base + "plot.floor", - new ArrayList<>(Arrays.asList(StringMan.join(Configuration.BLOCKLIST.parseString(value), ",").split(",")))); + this.worlds.set(base + "plot.floor", new ArrayList<>(Arrays.asList( + StringMan.join(Configuration.BLOCKLIST.parseString(value), ",") + .split(",")))); break; case "m": case "main": - this.worlds.set(base + "plot.filling", - new ArrayList<>(Arrays.asList(StringMan.join(Configuration.BLOCKLIST.parseString(value), ",").split(",")))); + this.worlds.set(base + "plot.filling", new ArrayList<>(Arrays.asList( + StringMan.join(Configuration.BLOCKLIST.parseString(value), ",") + .split(",")))); break; case "w": case "wall": - this.worlds.set(base + "wall.filling", Configuration.BLOCK.parseString(value).toString()); + this.worlds.set(base + "wall.filling", + Configuration.BLOCK.parseString(value).toString()); break; case "b": case "border": - this.worlds.set(base + "wall.block", Configuration.BLOCK.parseString(value).toString()); + this.worlds.set(base + "wall.block", + Configuration.BLOCK.parseString(value).toString()); break; default: - PS.log("&cKey not found: &7" + element); + PlotSquared.log("&cKey not found: &7" + element); return false; } } catch (Exception e) { e.printStackTrace(); - PS.log("&cInvalid value: &7" + value + " in arg " + element); + PlotSquared.log("&cInvalid value: &7" + value + " in arg " + element); return false; } } try { - ConfigurationSection section = this.worlds.getConfigurationSection("worlds." + world); + ConfigurationSection section = + this.worlds.getConfigurationSection("worlds." + world); plotworld.saveConfiguration(section); plotworld.loadConfiguration(section); this.worlds.save(this.worldsFile); @@ -1457,26 +1426,21 @@ public class PS{ return true; } - public boolean canUpdate(String current, String other) { - String s1 = normalisedVersion(current); - String s2 = normalisedVersion(other); - int cmp = s1.compareTo(s2); - return cmp < 0; + public boolean canUpdate(@NonNull final String current, @NonNull final String other) { + final String s1 = normalisedVersion(current); + final String s2 = normalisedVersion(other); + return s1.compareTo(s2) < 0; } - public String normalisedVersion(String version) { - String[] split = Pattern.compile(".", Pattern.LITERAL).split(version); - StringBuilder sb = new StringBuilder(); - for (String s : split) { + public String normalisedVersion(@NonNull final String version) { + final String[] split = Pattern.compile(".", Pattern.LITERAL).split(version); + final StringBuilder sb = new StringBuilder(); + for (final String s : split) { sb.append(String.format("%" + 4 + 's', s)); } return sb.toString(); } - public File getJarFile() { - return jarFile; - } - public boolean update(PlotPlayer sender, URL url) { try { String name = this.jarFile.getName(); @@ -1496,21 +1460,23 @@ public class PS{ } Files.copy(stream, newJar.toPath()); } - MainUtil.sendMessage(sender, "$1The update will take effect when the server is restarted next"); + MainUtil.sendMessage(sender, + "$1The update will take effect when the server is restarted next"); return true; } catch (IOException e) { MainUtil.sendMessage(sender, "Failed to update " + IMP.getPluginName() + ""); MainUtil.sendMessage(sender, " - Please update manually"); - PS.log("============ Stacktrace ============"); + PlotSquared.log("============ Stacktrace ============"); e.printStackTrace(); - PS.log("===================================="); + PlotSquared.log("===================================="); } return false; } /** * Copy a file from inside the jar to a location - * @param file Name of the file inside PlotSquared.jar + * + * @param file Name of the file inside PlotSquared.jar * @param folder The output location relative to /plugins/PlotSquared/ */ public void copyFile(String file, String folder) { @@ -1526,7 +1492,8 @@ public class PS{ try (InputStream stream = this.IMP.getClass().getResourceAsStream(file)) { byte[] buffer = new byte[2048]; if (stream == null) { - try (ZipInputStream zis = new ZipInputStream(new FileInputStream(this.jarFile))) { + try (ZipInputStream zis = new ZipInputStream( + new FileInputStream(this.jarFile))) { ZipEntry ze = zis.getNextEntry(); while (ze != null) { String name = ze.getName(); @@ -1557,13 +1524,13 @@ public class PS{ } } catch (IOException e) { e.printStackTrace(); - PS.log("&cCould not save " + file); + PlotSquared.log("&cCould not save " + file); } } private Map> getPlotsRaw() { HashMap> map = new HashMap<>(); - for (PlotArea area : this.manager.getAllPlotAreas()) { + for (PlotArea area : this.plotAreaManager.getAllPlotAreas()) { Map map2 = map.get(area.toString()); if (map2 == null) { map.put(area.toString(), area.getPlotsRaw()); @@ -1582,8 +1549,7 @@ public class PS{ // Validate that all data in the db is correct final HashSet plots = new HashSet<>(); foreachPlotRaw(new RunnableVal() { - @Override - public void run(Plot value) { + @Override public void run(Plot value) { plots.add(value); } }); @@ -1594,7 +1560,7 @@ public class PS{ UUIDHandler.handleShutdown(); } catch (NullPointerException ignored) { ignored.printStackTrace(); - PS.log("&cCould not close database connection!"); + PlotSquared.log("&cCould not close database connection!"); } } @@ -1608,20 +1574,20 @@ public class PS{ } Database database; if (Storage.MySQL.USE) { - database = new com.intellectualcrafters.plot.database.MySQL(Storage.MySQL.HOST, Storage.MySQL.PORT, Storage.MySQL.DATABASE, - Storage.MySQL.USER, Storage.MySQL.PASSWORD); + database = new MySQL(Storage.MySQL.HOST, Storage.MySQL.PORT, Storage.MySQL.DATABASE, + Storage.MySQL.USER, Storage.MySQL.PASSWORD); } else if (Storage.SQLite.USE) { File file = MainUtil.getFile(IMP.getDirectory(), Storage.SQLite.DB + ".db"); - database = new com.intellectualcrafters.plot.database.SQLite(file); + database = new SQLite(file); } else { - PS.log(C.PREFIX + "&cNo storage type is set!"); + PlotSquared.log(C.PREFIX + "&cNo storage type is set!"); this.IMP.disable(); return; } DBFunc.dbManager = new SQLManager(database, Storage.PREFIX, false); this.plots_tmp = DBFunc.getPlots(); - if (manager instanceof SinglePlotAreaManager) { - SinglePlotArea area = ((SinglePlotAreaManager) manager).getArea(); + if (plotAreaManager instanceof SinglePlotAreaManager) { + SinglePlotArea area = ((SinglePlotAreaManager) plotAreaManager).getArea(); addPlotArea(area); ConfigurationSection section = worlds.getConfigurationSection("worlds.*"); if (section == null) { @@ -1632,30 +1598,35 @@ public class PS{ } this.clusters_tmp = DBFunc.getClusters(); } catch (ClassNotFoundException | SQLException e) { - PS.log(C.PREFIX + "&cFailed to open DATABASE connection. The plugin will disable itself."); + PlotSquared.log( + C.PREFIX + "&cFailed to open DATABASE connection. The plugin will disable itself."); if (Storage.MySQL.USE) { - PS.log("$4MYSQL"); + PlotSquared.log("$4MYSQL"); } else if (Storage.SQLite.USE) { - PS.log("$4SQLITE"); + PlotSquared.log("$4SQLITE"); } - PS.log("&d==== Here is an ugly stacktrace, if you are interested in those things ==="); + PlotSquared.log( + "&d==== Here is an ugly stacktrace, if you are interested in those things ==="); e.printStackTrace(); - PS.log("&d==== End of stacktrace ===="); - PS.log("&6Please go to the " + IMP.getPluginName() + " 'storage.yml' and configure the database correctly."); + PlotSquared.log("&d==== End of stacktrace ===="); + PlotSquared.log("&6Please go to the " + IMP.getPluginName() + + " 'storage.yml' and configure the database correctly."); this.IMP.disable(); } } /** * Setup the default configuration. + * * @throws IOException if the config failed to save */ public void setupConfig() throws IOException { String lastVersionString = this.config.getString("version"); if (lastVersionString != null) { String[] split = lastVersionString.split("\\."); - int[] lastVersion = new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2])}; - if (checkVersion(new int[]{3, 4, 0}, lastVersion)) { + int[] lastVersion = new int[] {Integer.parseInt(split[0]), Integer.parseInt(split[1]), + Integer.parseInt(split[2])}; + if (checkVersion(new int[] {3, 4, 0}, lastVersion)) { Settings.convertLegacy(configFile); if (config.contains("worlds")) { ConfigurationSection worldSection = config.getConfigurationSection("worlds"); @@ -1663,7 +1634,7 @@ public class PS{ try { worlds.save(worldsFile); } catch (IOException e) { - PS.debug("Failed to save " + IMP.getPluginName() + " worlds.yml"); + PlotSquared.debug("Failed to save " + IMP.getPluginName() + " worlds.yml"); e.printStackTrace(); } } @@ -1679,7 +1650,8 @@ public class PS{ this.version = PlotVersion.tryParse(versionString); Settings.DATE = new Date(100 + version.year, version.month, version.day).toGMTString(); Settings.BUILD = "https://ci.athion.net/job/PlotSquared/" + version.build; - Settings.COMMIT = "https://github.com/IntellectualSites/PlotSquared/commit/" + Integer.toHexString(version.hash); + Settings.COMMIT = "https://github.com/IntellectualSites/PlotSquared/commit/" + Integer + .toHexString(version.hash); System.out.println("Version is " + this.version); } catch (Throwable ignore) { ignore.printStackTrace(); @@ -1690,74 +1662,81 @@ public class PS{ /** * Setup all configuration files
    - * - Config: settings.yml
    - * - Storage: storage.yml
    - * - Translation: PlotSquared.use_THIS.yml, style.yml
    + * - Config: settings.yml
    + * - Storage: storage.yml
    + * - Translation: PlotSquared.use_THIS.yml, style.yml
    */ public void setupConfigs() { File folder = new File(this.IMP.getDirectory(), "config"); if (!folder.exists() && !folder.mkdirs()) { - PS.log(C.PREFIX + "&cFailed to create the /plugins/config folder. Please create it manually."); + PlotSquared.log(C.PREFIX + + "&cFailed to create the /plugins/config folder. Please create it manually."); } try { this.worldsFile = new File(folder, "worlds.yml"); if (!this.worldsFile.exists() && !this.worldsFile.createNewFile()) { - PS.log("Could not create the worlds file, please create \"worlds.yml\" manually."); + PlotSquared.log( + "Could not create the worlds file, please create \"worlds.yml\" manually."); } this.worlds = YamlConfiguration.loadConfiguration(this.worldsFile); } catch (IOException ignored) { - PS.log("Failed to save settings.yml"); + PlotSquared.log("Failed to save settings.yml"); } try { this.configFile = new File(folder, "settings.yml"); if (!this.configFile.exists() && !this.configFile.createNewFile()) { - PS.log("Could not create the settings file, please create \"settings.yml\" manually."); + PlotSquared.log( + "Could not create the settings file, please create \"settings.yml\" manually."); } this.config = YamlConfiguration.loadConfiguration(this.configFile); setupConfig(); } catch (IOException ignored) { - PS.log("Failed to save settings.yml"); + PlotSquared.log("Failed to save settings.yml"); } try { - this.styleFile = MainUtil.getFile(IMP.getDirectory(), Settings.Paths.TRANSLATIONS + File.separator + "style.yml"); + this.styleFile = MainUtil.getFile(IMP.getDirectory(), + Settings.Paths.TRANSLATIONS + File.separator + "style.yml"); if (!this.styleFile.exists()) { if (!this.styleFile.getParentFile().exists()) { this.styleFile.getParentFile().mkdirs(); } if (!this.styleFile.createNewFile()) { - PS.log("Could not create the style file, please create \"translations/style.yml\" manually"); + PlotSquared.log( + "Could not create the style file, please create \"translations/style.yml\" manually"); } } this.style = YamlConfiguration.loadConfiguration(this.styleFile); setupStyle(); } catch (IOException err) { err.printStackTrace(); - PS.log("failed to save style.yml"); + PlotSquared.log("failed to save style.yml"); } try { this.storageFile = new File(folder, "storage.yml"); if (!this.storageFile.exists() && !this.storageFile.createNewFile()) { - PS.log("Could not the storage settings file, please create \"storage.yml\" manually."); + PlotSquared.log( + "Could not the storage settings file, please create \"storage.yml\" manually."); } this.storage = YamlConfiguration.loadConfiguration(this.storageFile); setupStorage(); } catch (IOException ignored) { - PS.log("Failed to save storage.yml"); + PlotSquared.log("Failed to save storage.yml"); } try { this.commandsFile = new File(folder, "commands.yml"); if (!this.commandsFile.exists() && !this.commandsFile.createNewFile()) { - PS.log("Could not the storage settings file, please create \"commands.yml\" manually."); + PlotSquared.log( + "Could not the storage settings file, please create \"commands.yml\" manually."); } this.commands = YamlConfiguration.loadConfiguration(this.commandsFile); } catch (IOException ignored) { - PS.log("Failed to save commands.yml"); + PlotSquared.log("Failed to save commands.yml"); } try { this.style.save(this.styleFile); this.commands.save(this.commandsFile); } catch (IOException e) { - PS.log("Configuration file saving failed"); + PlotSquared.log("Configuration file saving failed"); e.printStackTrace(); } } @@ -1778,7 +1757,9 @@ public class PS{ if (Settings.DEBUG) { Map components = Settings.getFields(Settings.Enabled_Components.class); for (Entry component : components.entrySet()) { - PS.log(C.PREFIX + String.format("&cKey: &6%s&c, Value: &6%s", component.getKey(), component.getValue())); + PlotSquared.log(C.PREFIX + String + .format("&cKey: &6%s&c, Value: &6%s", component.getKey(), + component.getValue())); } } } @@ -1804,158 +1785,136 @@ public class PS{ /** * Get the Java version. + * * @return the java version */ public double getJavaVersion() { return Double.parseDouble(System.getProperty("java.specification.version")); } - public void foreachPlotArea(RunnableVal runnable) { - for (PlotArea area : this.manager.getAllPlotAreas()) { + public void foreachPlotArea(@NonNull final RunnableVal runnable) { + for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) { runnable.run(area); } } - public void foreachPlotArea(String world, RunnableVal runnable) { - PlotArea[] array = this.manager.getPlotAreas(world, null); + public void foreachPlotArea(@NonNull final String world, + @NonNull final RunnableVal runnable) { + final PlotArea[] array = this.plotAreaManager.getPlotAreas(world, null); if (array == null) { return; } - for (PlotArea area : array) { + for (final PlotArea area : array) { runnable.run(area); } } - public void foreachPlot(RunnableVal runnable) { - for (PlotArea area : this.manager.getAllPlotAreas()) { - for (Plot plot : area.getPlots()) { - runnable.run(plot); - } + public void foreachPlot(@NonNull final RunnableVal runnable) { + for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) { + area.getPlots().forEach(runnable::run); } } - public void foreachPlotRaw(RunnableVal runnable) { - for (PlotArea area : this.manager.getAllPlotAreas()) { - for (Plot plot : area.getPlots()) { - runnable.run(plot); - } + public void foreachPlotRaw(@NonNull final RunnableVal runnable) { + for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) { + area.getPlots().forEach(runnable::run); } if (this.plots_tmp != null) { - for (HashMap entry : this.plots_tmp.values()) { - for (Plot entry2 : entry.values()) { - runnable.run(entry2); - } + for (final HashMap entry : this.plots_tmp.values()) { + entry.values().forEach(runnable::run); } } } - public void foreachBasePlot(RunnableVal run) { - for (PlotArea area : this.manager.getAllPlotAreas()) { + public void foreachBasePlot(@NonNull final RunnableVal run) { + for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) { area.foreachBasePlot(run); } } public PlotArea getFirstPlotArea() { - PlotArea[] areas = manager.getAllPlotAreas(); + PlotArea[] areas = plotAreaManager.getAllPlotAreas(); return areas.length > 0 ? areas[0] : null; } public int getPlotAreaCount() { - return this.manager.getAllPlotAreas().length; + return this.plotAreaManager.getAllPlotAreas().length; } public int getPlotCount() { int count = 0; - for (PlotArea area : this.manager.getAllPlotAreas()) { + for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) { count += area.getPlotCount(); } return count; } public Set getPlotAreas() { - HashSet set = new HashSet<>(); - Collections.addAll(set, manager.getAllPlotAreas()); - return set; + final Set set = new HashSet<>(); + Collections.addAll(set, plotAreaManager.getAllPlotAreas()); + return Collections.unmodifiableSet(set); } - /** - * Not recommended for use since worlds can have multiple PlotAreas. - * @return Set of world names - */ - @Deprecated - public Set getPlotWorldStrings() { - HashSet set = new HashSet<>(manager.getAllPlotAreas().length); - for (String world : manager.getAllWorlds()) { - if (manager.getPlotAreas(world, null).length != 0) { - set.add(world); - } - } - return set; - } - - public boolean isAugmented(String world) { - PlotArea[] areas = manager.getPlotAreas(world, null); - if (areas == null) { - return false; - } - if (areas.length > 1) { - return true; - } - return areas[0].TYPE != 0; + public boolean isAugmented(@NonNull final String world) { + final PlotArea[] areas = plotAreaManager.getPlotAreas(world, null); + return areas != null && (areas.length > 1 || areas[0].TYPE != 0); } /** * Get a list of PlotArea objects. + * * @param world the world * @return Collection of PlotArea objects */ - public Set getPlotAreas(String world) { - Set set = new HashSet<>(); - Collections.addAll(set, manager.getPlotAreas(world, null)); + public Set getPlotAreas(@NonNull final String world) { + final Set set = new HashSet<>(); + Collections.addAll(set, plotAreaManager.getPlotAreas(world, null)); return set; } /** * Get the relevant plot area for a specified location. *

      - *
    • If there is only one plot area globally that will be returned. - *
    • If there is only one plot area in the world, it will return that. - *
    • If the plot area for a location cannot be unambiguously - * resolved, null will be returned. + *
    • If there is only one plot area globally that will be returned. + *
    • If there is only one plot area in the world, it will return that. + *
    • If the plot area for a location cannot be unambiguously + * resolved, null will be returned. *
    * Note: An applicable plot area may not include the location i.e. clusters + * * @param location the location * @return */ - public PlotArea getApplicablePlotArea(Location location) { - return manager.getApplicablePlotArea(location); + public PlotArea getApplicablePlotArea(@NonNull final Location location) { + return plotAreaManager.getApplicablePlotArea(location); } - public PlotArea getPlotArea(String world, String id) { - return manager.getPlotArea(world, id); + public PlotArea getPlotArea(@NonNull final String world, final String id) { + return plotAreaManager.getPlotArea(world, id); } /** * Get the {@code PlotArea} which contains a location. *
      - *
    • If the plot area does not contain a location, null - * will be returned. + *
    • If the plot area does not contain a location, null + * will be returned. *
    * * @param location the location * @return the {@link PlotArea} in the location, null if non existent */ - public PlotArea getPlotAreaAbs(Location location) { - return manager.getPlotArea(location); + public PlotArea getPlotAreaAbs(@NonNull final Location location) { + return plotAreaManager.getPlotArea(location); } - public PlotArea getPlotAreaByString(String search) { - String[] split = search.split(";|,"); - PlotArea[] areas = manager.getPlotAreas(split[0], null); + public PlotArea getPlotAreaByString(@NonNull final String search) { + String[] split = search.split("[;,]"); + PlotArea[] areas = plotAreaManager.getPlotAreas(split[0], null); if (areas == null) { - for (PlotArea area : manager.getAllPlotAreas()) { + for (PlotArea area : plotAreaManager.getAllPlotAreas()) { if (area.worldname.equalsIgnoreCase(split[0])) { - if (area.id == null || split.length == 2 && area.id.equalsIgnoreCase(split[1])) { + if (area.id == null || split.length == 2 && area.id + .equalsIgnoreCase(split[1])) { return area; } } @@ -1975,34 +1934,33 @@ public class PS{ return null; } } - + /** * Get Plots based on alias * - * @param alias to search plots + * @param alias to search plots * @param worldname to filter alias to a specific world [optional] null means all worlds - * - * @return Set<{@link Plot}> empty if nothing found + * @return Set<{ @ link Plot }> empty if nothing found */ - public Set getPlotsByAlias(String alias, String worldname) { - Set result = new HashSet<>(); - - if (alias != null) { - for (Plot plot : getPlots()) { - if (alias.equals(plot.getAlias()) && (worldname == null || worldname.equals(plot.getWorldName()))) { - result.add(plot); - } - } - } - - return result; + public Set getPlotsByAlias(@Nullable final String alias, + @NonNull final String worldname) { + final Set result = new HashSet<>(); + if (alias != null) { + for (final Plot plot : getPlots()) { + if (alias.equals(plot.getAlias()) && (worldname == null || worldname + .equals(plot.getWorldName()))) { + result.add(plot); + } + } + } + return Collections.unmodifiableSet(result); } - public Set getPlotAreas(String world, RegionWrapper region) { - PlotArea[] areas = manager.getPlotAreas(world, region); - Set set = new HashSet<>(); + public Set getPlotAreas(final String world, final RegionWrapper region) { + final PlotArea[] areas = plotAreaManager.getPlotAreas(world, region); + final Set set = new HashSet<>(); Collections.addAll(set, areas); - return set; + return Collections.unmodifiableSet(set); } public enum SortType { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/PlotVersion.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotVersion.java similarity index 83% rename from Core/src/main/java/com/intellectualcrafters/plot/PlotVersion.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotVersion.java index 937d0af73..3abf51fde 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/PlotVersion.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotVersion.java @@ -1,4 +1,4 @@ -package com.intellectualcrafters.plot; +package com.github.intellectualsites.plotsquared.plot; public class PlotVersion { public final int year, month, day, hash, build; @@ -11,15 +11,6 @@ public class PlotVersion { this.build = build; } - public static PlotVersion tryParse(String version) { - try { - return new PlotVersion(version); - } catch (Exception ignore) { - ignore.printStackTrace(); - return new PlotVersion(0, 0, 0, 0, 0); - } - } - public PlotVersion(String version) { String[] split = version.substring(version.indexOf('=') + 1).split("-"); if (split[0].equals("unknown")) { @@ -30,7 +21,7 @@ public class PlotVersion { this.year = Integer.parseInt(date[0]); this.month = Integer.parseInt(date[1]); this.day = Integer.parseInt(date[2]); - if(split[1].equals("SNAPSHOT")) { // fallback when compiling with Maven + if (split[1].equals("SNAPSHOT")) { // fallback when compiling with Maven this.hash = 0; this.build = 0; } else { @@ -39,12 +30,21 @@ public class PlotVersion { } } - @Override - public String toString() { - if(hash == 0 && build == 0) { + public static PlotVersion tryParse(String version) { + try { + return new PlotVersion(version); + } catch (Exception ignore) { + ignore.printStackTrace(); + return new PlotVersion(0, 0, 0, 0, 0); + } + } + + @Override public String toString() { + if (hash == 0 && build == 0) { return "PlotSquared-" + year + "." + month + "." + day + "-SNAPSHOT"; } else { - return "PlotSquared-" + year + "." + month + "." + day + "-" + Integer.toHexString(hash) + "-" + build; + return "PlotSquared-" + year + "." + month + "." + day + "-" + Integer.toHexString(hash) + + "-" + build; } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/Updater.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/Updater.java similarity index 67% rename from Core/src/main/java/com/intellectualcrafters/plot/Updater.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/Updater.java index dd7f15cd0..bd780ae90 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/Updater.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/Updater.java @@ -1,6 +1,7 @@ -package com.intellectualcrafters.plot; +package com.github.intellectualsites.plotsquared.plot; + +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MainUtil; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -16,7 +17,8 @@ public class Updater { public String getChanges() { if (changes == null) { - try (Scanner scanner = new Scanner(new URL("http://empcraft.com/plots/cl?" + Integer.toHexString(PS.get().getVersion().hash)).openStream(), "UTF-8")) { + try (Scanner scanner = new Scanner(new URL("http://empcraft.com/plots/cl?" + Integer + .toHexString(PlotSquared.get().getVersion().hash)).openStream(), "UTF-8")) { changes = scanner.useDelimiter("\\A").next(); } catch (IOException e) { e.printStackTrace(); @@ -35,7 +37,8 @@ public class Updater { return; } try { - String downloadUrl = "https://ci.athion.net/job/PlotSquared/lastSuccessfulBuild/artifact/target/PlotSquared-%platform%-%version%.jar"; + String downloadUrl = + "https://ci.athion.net/job/PlotSquared/lastSuccessfulBuild/artifact/target/PlotSquared-%platform%-%version%.jar"; String versionUrl = "http://empcraft.com/plots/version.php?%platform%"; URL url = new URL(versionUrl.replace("%platform%", platform)); try (Scanner reader = new Scanner(url.openStream())) { @@ -43,12 +46,15 @@ public class Updater { PlotVersion version = new PlotVersion(versionString); if (version.isNewer(newVersion != null ? newVersion : currentVersion)) { newVersion = version; - URL download = new URL(downloadUrl.replaceAll("%platform%", platform).replaceAll("%version%", versionString)); + URL download = new URL(downloadUrl.replaceAll("%platform%", platform) + .replaceAll("%version%", versionString)); try (ReadableByteChannel rbc = Channels.newChannel(download.openStream())) { - File jarFile = PS.get().getJarFile(); + File jarFile = PlotSquared.get().getJarFile(); - File finalFile = new File(jarFile.getParent(), "update" + File.separator + jarFile.getName()); - File outFile = new File(jarFile.getParent(), "update" + File.separator + jarFile.getName().replace(".jar", ".part")); + File finalFile = new File(jarFile.getParent(), + "update" + File.separator + jarFile.getName()); + File outFile = new File(jarFile.getParent(), + "update" + File.separator + jarFile.getName().replace(".jar", ".part")); boolean exists = outFile.exists(); if (exists) { outFile.delete(); @@ -62,12 +68,15 @@ public class Updater { fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } outFile.renameTo(finalFile); - PS.debug("Updated PlotSquared to " + versionString); - MainUtil.sendAdmin("&7Restart to update PlotSquared with these changes: &c/plot changelog &7or&c " + "http://empcraft.com/plots/cl?" + Integer.toHexString(currentVersion.hash)); + PlotSquared.debug("Updated PlotSquared to " + versionString); + MainUtil.sendAdmin( + "&7Restart to update PlotSquared with these changes: &c/plot changelog &7or&c " + + "http://empcraft.com/plots/cl?" + Integer + .toHexString(currentVersion.hash)); } } } } catch (Throwable ignore) { } } -} \ No newline at end of file +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Add.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Add.java similarity index 53% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Add.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Add.java index 4f0aabf80..8d9df2774 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Add.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Add.java @@ -1,39 +1,35 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal2; -import com.intellectualcrafters.plot.object.RunnableVal3; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.plotsquared.general.commands.Command; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; +import com.github.intellectualsites.plotsquared.plot.util.EventUtil; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; import java.util.Iterator; import java.util.Set; import java.util.UUID; -@CommandDeclaration( - command = "add", - description = "Allow a user to build in a plot while you are online", - usage = "/plot add ", - category = CommandCategory.SETTINGS, - permission = "plots.add", - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "add", description = "Allow a user to build in a plot while you are online", usage = "/plot add ", category = CommandCategory.SETTINGS, permission = "plots.add", requiredType = RequiredType.NONE) public class Add extends Command { public Add() { super(MainCommand.getInstance(), true); } - @Override - public void execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { + @Override public void execute(final PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) throws CommandException { final Plot plot = check(player.getCurrentPlot(), C.NOT_IN_PLOT); checkTrue(plot.hasOwner(), C.PLOT_UNOWNED); - checkTrue(plot.isOwner(player.getUUID()) || Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_TRUST), C.NO_PLOT_PERMS); + checkTrue(plot.isOwner(player.getUUID()) || Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_TRUST), C.NO_PLOT_PERMS); checkTrue(args.length == 1, C.COMMAND_SYNTAX, getUsage()); final Set uuids = MainUtil.getUUIDsFromString(args[0]); checkTrue(!uuids.isEmpty(), C.INVALID_PLAYER, args[0]); @@ -41,7 +37,9 @@ public class Add extends Command { int size = plot.getTrusted().size() + plot.getMembers().size(); while (iter.hasNext()) { UUID uuid = iter.next(); - if (uuid == DBFunc.everyone && !(Permissions.hasPermission(player, C.PERMISSION_TRUST_EVERYONE) || Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_TRUST))) { + if (uuid == DBFunc.EVERYONE && !( + Permissions.hasPermission(player, C.PERMISSION_TRUST_EVERYONE) || Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_TRUST))) { MainUtil.sendMessage(player, C.INVALID_PLAYER, MainUtil.getName(uuid)); iter.remove(); continue; @@ -59,12 +57,13 @@ public class Add extends Command { size += plot.getTrusted().contains(uuid) ? 0 : 1; } checkTrue(!uuids.isEmpty(), null); - checkTrue(size <= plot.getArea().MAX_PLOT_MEMBERS || Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_TRUST), C.PLOT_MAX_MEMBERS); + checkTrue(size <= plot.getArea().MAX_PLOT_MEMBERS || Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_TRUST), C.PLOT_MAX_MEMBERS); confirm.run(this, new Runnable() { @Override // Success public void run() { for (UUID uuid : uuids) { - if (uuid != DBFunc.everyone) { + if (uuid != DBFunc.EVERYONE) { if (!plot.removeTrusted(uuid)) { if (plot.getDenied().contains(uuid)) { plot.removeDenied(uuid); @@ -78,4 +77,4 @@ public class Add extends Command { } }, null); } -} \ No newline at end of file +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Alias.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Alias.java new file mode 100644 index 000000000..b5e248fab --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Alias.java @@ -0,0 +1,122 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.StringWrapper; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; + +@CommandDeclaration(command = "setalias", permission = "plots.alias", description = "Set the plot name", usage = "/plot alias ", aliases = { + "alias", "sa", "name", "rename", "setname", "seta", + "nameplot"}, category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE) +public class Alias extends SubCommand { + + @Override public boolean onCommand(PlotPlayer player, String[] args) { + + if (args.length == 0) { + C.COMMAND_SYNTAX.send(player, "/plot alias "); + return false; + } + + Location loc = player.getLocation(); + Plot plot = loc.getPlotAbs(); + if (plot == null) { + return !sendMessage(player, C.NOT_IN_PLOT); + } + + if (!plot.hasOwner()) { + sendMessage(player, C.PLOT_NOT_CLAIMED); + return false; + } + + if (!plot.isOwner(player.getUUID())) { + MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + return false; + } + + boolean result = false; + + switch (args[0].toLowerCase()) { + case "set": + if (args.length != 2) { + C.COMMAND_SYNTAX.send(player, "/plot alias "); + return false; + } + + if (canExecuteCommand(player, C.PERMISSION_ALIAS_SET, false) || canExecuteCommand( + player, C.PERMISSION_ALIAS_SET_OBSOLETE, false)) { + result = setAlias(player, plot, args[1]); + } else { + MainUtil.sendMessage(player, C.NO_PERMISSION); + } + + break; + case "remove": + if (canExecuteCommand(player, C.PERMISSION_ALIAS_REMOVE, true)) { + result = removeAlias(player, plot); + } + break; + default: + C.COMMAND_SYNTAX.send(player, "/plot alias "); + result = false; + } + + return result; + } + + + private boolean setAlias(PlotPlayer player, Plot plot, String alias) { + if (alias.isEmpty()) { + C.COMMAND_SYNTAX.send(player, "/plot alias "); + return false; + } + if (alias.length() >= 50) { + MainUtil.sendMessage(player, C.ALIAS_TOO_LONG); + return false; + } + if (alias.contains(" ")) { + C.NOT_VALID_VALUE.send(player); + return false; + } + if (MathMan.isInteger(alias)) { + C.NOT_VALID_VALUE.send(player); + return false; + } + for (Plot p : PlotSquared.get().getPlots(plot.getArea())) { + if (p.getAlias().equalsIgnoreCase(alias)) { + MainUtil.sendMessage(player, C.ALIAS_IS_TAKEN); + return false; + } + } + if (UUIDHandler.nameExists(new StringWrapper(alias)) || PlotSquared.get() + .hasPlotArea(alias)) { + MainUtil.sendMessage(player, C.ALIAS_IS_TAKEN); + return false; + } + plot.setAlias(alias); + MainUtil.sendMessage(player, C.ALIAS_SET_TO.s().replaceAll("%alias%", alias)); + return true; + } + + private boolean removeAlias(PlotPlayer player, Plot plot) { + plot.setAlias(null); + MainUtil.sendMessage(player, C.ALIAS_REMOVED.s()); + return true; + } + + private boolean canExecuteCommand(PlotPlayer player, C caption, boolean sendMessage) { + if (!Permissions.hasPermission(player, caption)) { + if (sendMessage) { + MainUtil.sendMessage(player, C.NO_PERMISSION); + } + return false; + } + return true; + } +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Area.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Area.java similarity index 60% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Area.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Area.java index cfab9a55e..7f7f64dba 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Area.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Area.java @@ -1,47 +1,24 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Configuration; +import com.github.intellectualsites.plotsquared.plot.generator.AugmentedUtils; +import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.*; -import com.intellectualcrafters.configuration.ConfigurationSection; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Configuration; -import com.intellectualcrafters.plot.generator.AugmentedUtils; -import com.intellectualcrafters.plot.generator.HybridPlotWorld; -import com.intellectualcrafters.plot.object.ChunkLoc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotMessage; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RegionWrapper; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.RunnableVal3; -import com.intellectualcrafters.plot.object.SetupObject; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.CmdConfirm; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.SetupUtils; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.WorldUtil; -import com.plotsquared.general.commands.CommandDeclaration; import java.io.IOException; import java.util.ArrayList; import java.util.Objects; import java.util.Set; -@CommandDeclaration(command = "area", - permission = "plots.area", - category = CommandCategory.ADMINISTRATION, - requiredType = RequiredType.NONE, - description = "Create a new PlotArea", - aliases = "world", - usage = "/plot area ", - confirmation = true) +@CommandDeclaration(command = "area", permission = "plots.area", category = CommandCategory.ADMINISTRATION, requiredType = RequiredType.NONE, description = "Create a new PlotArea", aliases = "world", usage = "/plot area ", confirmation = true) public class Area extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length == 0) { C.COMMAND_SYNTAX.send(player, getUsage()); return false; @@ -56,48 +33,59 @@ public class Area extends SubCommand { } switch (args.length) { case 1: - C.COMMAND_SYNTAX.send(player, "/plot area create [world[:id]] [=]..."); + C.COMMAND_SYNTAX + .send(player, "/plot area create [world[:id]] [=]..."); return false; case 2: switch (args[1].toLowerCase()) { case "pos1": { // Set position 1 HybridPlotWorld area = player.getMeta("area_create_area"); if (area == null) { - C.COMMAND_SYNTAX.send(player, "/plot area create [world[:id]] [=]..."); + C.COMMAND_SYNTAX.send(player, + "/plot area create [world[:id]] [=]..."); return false; } Location location = player.getLocation(); player.setMeta("area_pos1", location); - C.SET_ATTRIBUTE.send(player, "area_pos1", location.getX() + "," + location.getZ()); - MainUtil.sendMessage(player, "You will now set pos2: /plot area create pos2" + C.SET_ATTRIBUTE.send(player, "area_pos1", + location.getX() + "," + location.getZ()); + MainUtil.sendMessage(player, + "You will now set pos2: /plot area create pos2" + "\nNote: The chosen plot size may result in the created area not exactly matching your second position."); return true; } case "pos2": // Set position 2 and finish creation for type=2 (partial) final HybridPlotWorld area = player.getMeta("area_create_area"); if (area == null) { - C.COMMAND_SYNTAX.send(player, "/plot area create [world[:id]] [=]..."); + C.COMMAND_SYNTAX.send(player, + "/plot area create [world[:id]] [=]..."); return false; } Location pos1 = player.getLocation(); Location pos2 = player.getMeta("area_pos1"); int dx = Math.abs(pos1.getX() - pos2.getX()); int dz = Math.abs(pos1.getZ() - pos2.getZ()); - int numX = Math.max(1, (dx + 1 + area.ROAD_WIDTH + area.SIZE / 2) / area.SIZE); - int numZ = Math.max(1, (dz + 1 + area.ROAD_WIDTH + area.SIZE / 2) / area.SIZE); + int numX = Math.max(1, + (dx + 1 + area.ROAD_WIDTH + area.SIZE / 2) / area.SIZE); + int numZ = Math.max(1, + (dz + 1 + area.ROAD_WIDTH + area.SIZE / 2) / area.SIZE); int ddx = dx - (numX * area.SIZE - area.ROAD_WIDTH); int ddz = dz - (numZ * area.SIZE - area.ROAD_WIDTH); int bx = Math.min(pos1.getX(), pos2.getX()) + ddx; int bz = Math.min(pos1.getZ(), pos2.getZ()) + ddz; int tx = Math.max(pos1.getX(), pos2.getX()) - ddx; int tz = Math.max(pos1.getZ(), pos2.getZ()) - ddz; - int lower = (area.ROAD_WIDTH & 1) == 0 ? area.ROAD_WIDTH / 2 - 1 : area.ROAD_WIDTH / 2; + int lower = (area.ROAD_WIDTH & 1) == 0 ? + area.ROAD_WIDTH / 2 - 1 : + area.ROAD_WIDTH / 2; final int offsetX = bx - (area.ROAD_WIDTH == 0 ? 0 : lower); final int offsetZ = bz - (area.ROAD_WIDTH == 0 ? 0 : lower); final RegionWrapper region = new RegionWrapper(bx, tx, bz, tz); - Set areas = PS.get().getPlotAreas(area.worldname, region); + Set areas = + PlotSquared.get().getPlotAreas(area.worldname, region); if (!areas.isEmpty()) { - C.CLUSTER_INTERSECTION.send(player, areas.iterator().next().toString()); + C.CLUSTER_INTERSECTION + .send(player, areas.iterator().next().toString()); return false; } final SetupObject object = new SetupObject(); @@ -107,39 +95,47 @@ public class Area extends SubCommand { object.type = area.TYPE; object.min = new PlotId(1, 1); object.max = new PlotId(numX, numZ); - object.plotManager = PS.imp().getPluginName(); - object.setupGenerator = PS.imp().getPluginName(); + object.plotManager = PlotSquared.imp().getPluginName(); + object.setupGenerator = PlotSquared.imp().getPluginName(); object.step = area.getSettingNodes(); - final String path = "worlds." + area.worldname + ".areas." + area.id + '-' + object.min + '-' + object.max; + final String path = + "worlds." + area.worldname + ".areas." + area.id + '-' + + object.min + '-' + object.max; Runnable run = new Runnable() { - @Override - public void run() { + @Override public void run() { if (offsetX != 0) { - PS.get().worlds.set(path + ".road.offset.x", offsetX); + PlotSquared.get().worlds + .set(path + ".road.offset.x", offsetX); } if (offsetZ != 0) { - PS.get().worlds.set(path + ".road.offset.z", offsetZ); + PlotSquared.get().worlds + .set(path + ".road.offset.z", offsetZ); } final String world = SetupUtils.manager.setupWorld(object); if (WorldUtil.IMP.isWorld(world)) { - PS.get().loadWorld(world, null); + PlotSquared.get().loadWorld(world, null); C.SETUP_FINISHED.send(player); player.teleport(WorldUtil.IMP.getSpawn(world)); if (area.TERRAIN != 3) { - ChunkManager.largeRegionTask(world, region, new RunnableVal() { - @Override - public void run(ChunkLoc value) { - AugmentedUtils.generate(world, value.x, value.z, null); - } - }, null); + ChunkManager.largeRegionTask(world, region, + new RunnableVal() { + @Override public void run(ChunkLoc value) { + AugmentedUtils + .generate(world, value.x, value.z, + null); + } + }, null); } } else { - MainUtil.sendMessage(player, "An error occurred while creating the world: " + area.worldname); + MainUtil.sendMessage(player, + "An error occurred while creating the world: " + + area.worldname); } } }; if (hasConfirmation(player)) { - CmdConfirm.addPending(player, getCommandString() + " create pos2 (Creates world)", run); + CmdConfirm.addPending(player, + getCommandString() + " create pos2 (Creates world)", run); } else { run.run(); } @@ -155,13 +151,14 @@ public class Area extends SubCommand { id = null; } object.world = split[0]; - final HybridPlotWorld pa = new HybridPlotWorld(object.world, id, PS.get().IMP.getDefaultGenerator(), null, null); - PlotArea other = PS.get().getPlotArea(pa.worldname, id); + final HybridPlotWorld pa = new HybridPlotWorld(object.world, id, + PlotSquared.get().IMP.getDefaultGenerator(), null, null); + PlotArea other = PlotSquared.get().getPlotArea(pa.worldname, id); if (other != null && Objects.equals(pa.id, other.id)) { C.SETUP_WORLD_TAKEN.send(player, pa.toString()); return false; } - Set areas = PS.get().getPlotAreas(pa.worldname); + Set areas = PlotSquared.get().getPlotAreas(pa.worldname); if (!areas.isEmpty()) { PlotArea area = areas.iterator().next(); pa.TYPE = area.TYPE; @@ -170,7 +167,8 @@ public class Area extends SubCommand { for (int i = 2; i < args.length; i++) { String[] pair = args[i].split("="); if (pair.length != 2) { - C.COMMAND_SYNTAX.send(player, getCommandString() + " create [world[:id]] [=]..."); + C.COMMAND_SYNTAX.send(player, getCommandString() + + " create [world[:id]] [=]..."); return false; } switch (pair[0].toLowerCase()) { @@ -193,19 +191,20 @@ public class Area extends SubCommand { break; case "f": case "floor": - pa.TOP_BLOCK = Configuration.BLOCKLIST.parseString(pair[1]); + pa.TOP_BLOCK = Configuration.BLOCK_BUCKET.parseString(pair[1]); break; case "m": case "main": - pa.MAIN_BLOCK = Configuration.BLOCKLIST.parseString(pair[1]); + pa.MAIN_BLOCK = Configuration.BLOCK_BUCKET.parseString(pair[1]); break; case "w": case "wall": - pa.WALL_FILLING = Configuration.BLOCK.parseString(pair[1]); + pa.WALL_FILLING = + Configuration.BLOCK_BUCKET.parseString(pair[1]); break; case "b": case "border": - pa.WALL_BLOCK = Configuration.BLOCK.parseString(pair[1]); + pa.WALL_BLOCK = Configuration.BLOCK_BUCKET.parseString(pair[1]); break; case "terrain": pa.TERRAIN = Integer.parseInt(pair[1]); @@ -216,7 +215,8 @@ public class Area extends SubCommand { object.type = pa.TYPE; break; default: - C.COMMAND_SYNTAX.send(player, getCommandString() + " create [world[:id]] [=]..."); + C.COMMAND_SYNTAX.send(player, getCommandString() + + " create [world[:id]] [=]..."); return false; } } @@ -226,40 +226,44 @@ public class Area extends SubCommand { return false; } Runnable run = new Runnable() { - @Override - public void run() { + @Override public void run() { String path = "worlds." + pa.worldname; - if (!PS.get().worlds.contains(path)) { - PS.get().worlds.createSection(path); + if (!PlotSquared.get().worlds.contains(path)) { + PlotSquared.get().worlds.createSection(path); } - ConfigurationSection section = PS.get().worlds.getConfigurationSection(path); + ConfigurationSection section = + PlotSquared.get().worlds.getConfigurationSection(path); pa.saveConfiguration(section); pa.loadConfiguration(section); - object.plotManager = PS.imp().getPluginName(); - object.setupGenerator = PS.imp().getPluginName(); + object.plotManager = PlotSquared.imp().getPluginName(); + object.setupGenerator = PlotSquared.imp().getPluginName(); String world = SetupUtils.manager.setupWorld(object); if (WorldUtil.IMP.isWorld(world)) { C.SETUP_FINISHED.send(player); player.teleport(WorldUtil.IMP.getSpawn(world)); } else { - MainUtil.sendMessage(player, "An error occurred while creating the world: " + pa.worldname); + MainUtil.sendMessage(player, + "An error occurred while creating the world: " + + pa.worldname); } try { - PS.get().worlds.save(PS.get().worldsFile); + PlotSquared.get().worlds.save(PlotSquared.get().worldsFile); } catch (IOException e) { e.printStackTrace(); } } }; if (hasConfirmation(player)) { - CmdConfirm.addPending(player, getCommandString() + ' ' + StringMan.join(args, " "), run); + CmdConfirm.addPending(player, + getCommandString() + ' ' + StringMan.join(args, " "), run); } else { run.run(); } return true; } if (pa.id == null) { - C.COMMAND_SYNTAX.send(player, getCommandString() + " create [world[:id]] [=]..."); + C.COMMAND_SYNTAX.send(player, getCommandString() + + " create [world[:id]] [=]..."); return false; } if (WorldUtil.IMP.isWorld(pa.worldname)) { @@ -273,7 +277,9 @@ public class Area extends SubCommand { player.teleport(WorldUtil.IMP.getSpawn(pa.worldname)); } player.setMeta("area_create_area", pa); - MainUtil.sendMessage(player, "$1Go to the first corner and use: $2 " + getCommandString() + " create pos1"); + MainUtil.sendMessage(player, + "$1Go to the first corner and use: $2 " + getCommandString() + + " create pos1"); break; } return true; @@ -289,7 +295,7 @@ public class Area extends SubCommand { area = player.getApplicablePlotArea(); break; case 2: - area = PS.get().getPlotAreaByString(args[1]); + area = PlotSquared.get().getPlotAreaByString(args[1]); break; default: C.COMMAND_SYNTAX.send(player, getCommandString() + " info [area]"); @@ -321,15 +327,12 @@ public class Area extends SubCommand { percent = claimed == 0 ? 0 : 100d * claimed / Integer.MAX_VALUE; region = "N/A"; } - String value = "&r$1NAME: " + name - + "\n$1Type: $2" + area.TYPE - + "\n$1Terrain: $2" + area.TERRAIN - + "\n$1Usage: $2" + String.format("%.2f", percent) + '%' - + "\n$1Claimed: $2" + claimed - + "\n$1Clusters: $2" + clusters - + "\n$1Region: $2" + region - + "\n$1Generator: $2" + generator; - MainUtil.sendMessage(player, C.PLOT_INFO_HEADER.s() + '\n' + value + '\n' + C.PLOT_INFO_FOOTER.s(), false); + String value = "&r$1NAME: " + name + "\n$1Type: $2" + area.TYPE + "\n$1Terrain: $2" + + area.TERRAIN + "\n$1Usage: $2" + String.format("%.2f", percent) + '%' + + "\n$1Claimed: $2" + claimed + "\n$1Clusters: $2" + clusters + "\n$1Region: $2" + + region + "\n$1Generator: $2" + generator; + MainUtil.sendMessage(player, + C.PLOT_INFO_HEADER.s() + '\n' + value + '\n' + C.PLOT_INFO_FOOTER.s(), false); return true; } case "l": @@ -352,45 +355,46 @@ public class Area extends SubCommand { C.COMMAND_SYNTAX.send(player, getCommandString() + " list [#]"); return false; } - ArrayList areas = new ArrayList<>(PS.get().getPlotAreas()); - paginate(player, areas, 8, page, new RunnableVal3() { - @Override - public void run(Integer i, PlotArea area, PlotMessage message) { - String name; - double percent; - int claimed = area.getPlotCount(); - int clusters = area.getClusters().size(); - String region; - String generator = String.valueOf(area.getGenerator()); - if (area.TYPE == 2) { - PlotId min = area.getMin(); - PlotId max = area.getMax(); - name = area.worldname + ';' + area.id + ';' + min + ';' + max; - int size = (max.x - min.x + 1) * (max.y - min.y + 1); - percent = claimed == 0 ? 0 : size / (double) claimed; - region = area.getRegion().toString(); - } else { - name = area.worldname; - percent = claimed == 0 ? 0 : Short.MAX_VALUE * Short.MAX_VALUE / (double) claimed; - region = "N/A"; - } - PlotMessage tooltip = new PlotMessage() - .text("Claimed=").color("$1").text(String.valueOf(claimed)).color("$2") - .text("\nUsage=").color("$1").text(String.format("%.2f", percent) + '%').color("$2") - .text("\nClusters=").color("$1").text(String.valueOf(clusters)).color("$2") - .text("\nRegion=").color("$1").text(region).color("$2") + ArrayList areas = new ArrayList<>(PlotSquared.get().getPlotAreas()); + paginate(player, areas, 8, page, + new RunnableVal3() { + @Override public void run(Integer i, PlotArea area, PlotMessage message) { + String name; + double percent; + int claimed = area.getPlotCount(); + int clusters = area.getClusters().size(); + String region; + String generator = String.valueOf(area.getGenerator()); + if (area.TYPE == 2) { + PlotId min = area.getMin(); + PlotId max = area.getMax(); + name = area.worldname + ';' + area.id + ';' + min + ';' + max; + int size = (max.x - min.x + 1) * (max.y - min.y + 1); + percent = claimed == 0 ? 0 : size / (double) claimed; + region = area.getRegion().toString(); + } else { + name = area.worldname; + percent = claimed == 0 ? + 0 : + Short.MAX_VALUE * Short.MAX_VALUE / (double) claimed; + region = "N/A"; + } + PlotMessage tooltip = new PlotMessage().text("Claimed=").color("$1") + .text(String.valueOf(claimed)).color("$2").text("\nUsage=") + .color("$1").text(String.format("%.2f", percent) + '%').color("$2") + .text("\nClusters=").color("$1").text(String.valueOf(clusters)) + .color("$2").text("\nRegion=").color("$1").text(region).color("$2") .text("\nGenerator=").color("$1").text(generator).color("$2"); - // type / terrain - String visit = "/plot area tp " + area.toString(); - message.text("[").color("$3") - .text(String.valueOf(i)).command(visit).tooltip(visit).color("$1") - .text("]").color("$3") - .text(' ' + name).tooltip(tooltip).command(getCommandString() + " info " + area).color("$1").text(" - ") - .color("$2") + // type / terrain + String visit = "/plot area tp " + area.toString(); + message.text("[").color("$3").text(String.valueOf(i)).command(visit) + .tooltip(visit).color("$1").text("]").color("$3").text(' ' + name) + .tooltip(tooltip).command(getCommandString() + " info " + area) + .color("$1").text(" - ").color("$2") .text(area.TYPE + ":" + area.TERRAIN).color("$3"); - } - }, "/plot area list", C.AREA_LIST_HEADER_PAGED.s()); + } + }, "/plot area list", C.AREA_LIST_HEADER_PAGED.s()); return true; case "regen": case "clear": @@ -406,20 +410,20 @@ public class Area extends SubCommand { return false; } if (area.TYPE != 2) { - MainUtil.sendMessage(player, "$4Stop the server and delete: " + area.worldname + "/region"); + MainUtil.sendMessage(player, + "$4Stop the server and delete: " + area.worldname + "/region"); return false; } - ChunkManager.largeRegionTask(area.worldname, area.getRegion(), new RunnableVal() { - @Override - public void run(ChunkLoc value) { - AugmentedUtils.generate(area.worldname, value.x, value.z, null); - } - }, new Runnable() { - @Override - public void run() { - player.sendMessage("Regen complete"); - } - }); + ChunkManager + .largeRegionTask(area.worldname, area.getRegion(), new RunnableVal() { + @Override public void run(ChunkLoc value) { + AugmentedUtils.generate(area.worldname, value.x, value.z, null); + } + }, new Runnable() { + @Override public void run() { + player.sendMessage("Regen complete"); + } + }); return true; } case "goto": @@ -435,7 +439,7 @@ public class Area extends SubCommand { C.COMMAND_SYNTAX.send(player, "/plot visit [area]"); return false; } - PlotArea area = PS.get().getPlotAreaByString(args[1]); + PlotArea area = PlotSquared.get().getPlotAreaByString(args[1]); if (area == null) { C.NOT_VALID_PLOT_WORLD.send(player, args[1]); return false; @@ -445,17 +449,20 @@ public class Area extends SubCommand { center = WorldUtil.IMP.getSpawn(area.worldname); } else { RegionWrapper region = area.getRegion(); - center = new Location(area.worldname, region.minX + (region.maxX - region.minX) / 2, 0, - region.minZ + (region.maxZ - region.minZ) / 2); - center.setY(1 + WorldUtil.IMP.getHighestBlock(area.worldname, center.getX(), center.getZ())); + center = + new Location(area.worldname, region.minX + (region.maxX - region.minX) / 2, + 0, region.minZ + (region.maxZ - region.minZ) / 2); + center.setY(1 + WorldUtil.IMP + .getHighestBlock(area.worldname, center.getX(), center.getZ())); } player.teleport(center); return true; case "delete": case "remove": - MainUtil.sendMessage(player, "$1World creation settings may be stored in multiple locations:" - + "\n$3 - $2Bukkit bukkit.yml" - + "\n$3 - $2" + PS.imp().getPluginName() + " settings.yml" + MainUtil.sendMessage(player, + "$1World creation settings may be stored in multiple locations:" + + "\n$3 - $2Bukkit bukkit.yml" + "\n$3 - $2" + PlotSquared.imp() + .getPluginName() + " settings.yml" + "\n$3 - $2Multiverse worlds.yml (or any world management plugin)" + "\n$1Stop the server and delete it from these locations."); return true; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Auto.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Auto.java similarity index 68% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Auto.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Auto.java index 874f2aed7..428b76b15 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Auto.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Auto.java @@ -1,46 +1,146 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.Expression; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.ByteArrayUtilities; -import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.TaskManager; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.*; import javax.annotation.Nullable; import java.util.Set; -@CommandDeclaration(command = "auto", - permission = "plots.auto", - category = CommandCategory.CLAIMING, - requiredType = RequiredType.NONE, - description = "Claim the nearest plot", - aliases = "a", - usage = "/plot auto [length,width]") +@CommandDeclaration(command = "auto", permission = "plots.auto", category = CommandCategory.CLAIMING, requiredType = RequiredType.NONE, description = "Claim the nearest plot", aliases = "a", usage = "/plot auto [length,width]") public class Auto extends SubCommand { - @Deprecated - public static PlotId getNextPlotId(PlotId id, int step) { + @Deprecated public static PlotId getNextPlotId(PlotId id, int step) { return id.getNextId(step); } - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + private static boolean checkAllowedPlots(PlotPlayer player, PlotArea plotarea, + @Nullable Integer allowed_plots, int size_x, int size_z) { + if (allowed_plots == null) + allowed_plots = player.getAllowedPlots(); + int currentPlots = + Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(plotarea.worldname); + int diff = currentPlots - allowed_plots; + if (diff + size_x * size_z > 0) { + if (diff < 0) { + MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS_NUM, -diff + ""); + return false; + } else if (player.hasPersistentMeta("grantedPlots")) { + int grantedPlots = + ByteArrayUtilities.bytesToInteger(player.getPersistentMeta("grantedPlots")); + if (grantedPlots - diff < size_x * size_z) { + player.removePersistentMeta("grantedPlots"); + MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS); + return false; + } else { + int left = grantedPlots - diff - size_x * size_z; + if (left == 0) { + player.removePersistentMeta("grantedPlots"); + } else { + player.setPersistentMeta("grantedPlots", + ByteArrayUtilities.integerToBytes(left)); + } + MainUtil.sendMessage(player, C.REMOVED_GRANTED_PLOT, "" + left, + "" + (grantedPlots - left)); + } + } else { + MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS); + return false; + } + } + return true; + } + + /** + * Teleport the player home, or claim a new plot + * + * @param player + * @param area + * @param start + * @param schem + */ + public static void homeOrAuto(final PlotPlayer player, final PlotArea area, PlotId start, + final String schem) { + Set plots = player.getPlots(); + if (!plots.isEmpty()) { + plots.iterator().next().teleportPlayer(player); + } else { + autoClaimSafe(player, area, start, schem); + } + } + + /** + * Claim a new plot for a player + * + * @param player + * @param area + * @param start + * @param schem + */ + public static void autoClaimSafe(final PlotPlayer player, final PlotArea area, PlotId start, + final String schem) { + autoClaimSafe(player, area, start, schem, null); + } + + /** + * Claim a new plot for a player + * + * @param player + * @param area + * @param start + * @param schem + */ + public static void autoClaimSafe(final PlotPlayer player, final PlotArea area, PlotId start, + final String schem, @Nullable final Integer allowed_plots) { + player.setMeta(Auto.class.getName(), true); + autoClaimFromDatabase(player, area, start, new RunnableVal() { + @Override public void run(final Plot plot) { + TaskManager.IMP.sync(new RunnableVal() { + @Override public void run(Object ignore) { + player.deleteMeta(Auto.class.getName()); + if (plot == null) { + MainUtil.sendMessage(player, C.NO_FREE_PLOTS); + } else if (checkAllowedPlots(player, area, allowed_plots, 1, 1)) { + plot.claim(player, true, schem, false); + if (area.AUTO_MERGE) { + plot.autoMerge(-1, Integer.MAX_VALUE, player.getUUID(), true); + } + } else { + DBFunc.delete(plot); + } + } + }); + } + }); + } + + public static void autoClaimFromDatabase(final PlotPlayer player, final PlotArea area, + PlotId start, final RunnableVal whenDone) { + final Plot plot = area.getNextFreePlot(player, start); + if (plot == null) { + whenDone.run(null); + return; + } + whenDone.value = plot; + plot.owner = player.getUUID(); + DBFunc.createPlotSafe(plot, whenDone, new Runnable() { + @Override public void run() { + autoClaimFromDatabase(player, area, plot.getId(), whenDone); + } + }); + } + + @Override public boolean onCommand(final PlotPlayer player, String[] args) { PlotArea plotarea = player.getApplicablePlotArea(); if (plotarea == null) { if (EconHandler.manager != null) { - for (PlotArea area : PS.get().getPlotAreaManager().getAllPlotAreas()) { - if (EconHandler.manager.hasPermission(area.worldname, player.getName(), "plots.auto")) { + for (PlotArea area : PlotSquared.get().getPlotAreaManager().getAllPlotAreas()) { + if (EconHandler.manager + .hasPermission(area.worldname, player.getName(), "plots.auto")) { if (plotarea != null) { plotarea = null; break; @@ -84,25 +184,32 @@ public class Auto extends SubCommand { } } if (size_x * size_z > Settings.Claim.MAX_AUTO_AREA) { - MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS_NUM, Settings.Claim.MAX_AUTO_AREA + ""); + MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS_NUM, + Settings.Claim.MAX_AUTO_AREA + ""); return false; } final int allowed_plots = player.getAllowedPlots(); - if (player.getMeta(Auto.class.getName(), false) || !checkAllowedPlots(player, plotarea, allowed_plots, size_x, size_z)) return false; + if (player.getMeta(Auto.class.getName(), false) || !checkAllowedPlots(player, plotarea, + allowed_plots, size_x, size_z)) + return false; if (schematic != null && !schematic.isEmpty()) { if (!plotarea.SCHEMATICS.contains(schematic.toLowerCase())) { sendMessage(player, C.SCHEMATIC_INVALID, "non-existent: " + schematic); return true; } - if (!Permissions.hasPermission(player, C.PERMISSION_CLAIM_SCHEMATIC.f(schematic)) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLAIM_SCHEMATIC.f(schematic)); + if (!Permissions.hasPermission(player, C.PERMISSION_CLAIM_SCHEMATIC.f(schematic)) + && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC)) { + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLAIM_SCHEMATIC.f(schematic)); return true; } } if (EconHandler.manager != null && plotarea.USE_ECONOMY) { Expression costExp = plotarea.PRICES.get("claim"); - double cost = costExp.evaluate((double) (Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(plotarea.worldname))); + double cost = costExp.evaluate((double) (Settings.Limit.GLOBAL ? + player.getPlotCount() : + player.getPlotCount(plotarea.worldname))); cost = (size_x * size_z) * cost; if (cost > 0d) { if (EconHandler.manager.getMoney(player) < cost) { @@ -134,7 +241,8 @@ public class Auto extends SubCommand { plot.claim(player, teleport, null); } } - if (!plotarea.mergePlots(MainUtil.getPlotSelectionIds(start, end), true, true)) { + if (!plotarea + .mergePlots(MainUtil.getPlotSelectionIds(start, end), true, true)) { return false; } break; @@ -144,135 +252,4 @@ public class Auto extends SubCommand { return true; } } - - private static boolean checkAllowedPlots(PlotPlayer player, PlotArea plotarea, @Nullable Integer allowed_plots, int size_x, int size_z) { - if (allowed_plots == null) - allowed_plots = player.getAllowedPlots(); - int currentPlots = Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(plotarea.worldname); - int diff = currentPlots - allowed_plots; - if (diff + size_x * size_z > 0) { - if (diff < 0) { - MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS_NUM, -diff + ""); - return false; - } else if (player.hasPersistentMeta("grantedPlots")) { - int grantedPlots = ByteArrayUtilities.bytesToInteger(player.getPersistentMeta("grantedPlots")); - if (grantedPlots - diff < size_x * size_z) { - player.removePersistentMeta("grantedPlots"); - MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS); - return false; - } else { - int left = grantedPlots - diff - size_x * size_z; - if (left == 0) { - player.removePersistentMeta("grantedPlots"); - } else { - player.setPersistentMeta("grantedPlots", ByteArrayUtilities.integerToBytes(left)); - } - MainUtil.sendMessage(player, C.REMOVED_GRANTED_PLOT, "" + left, "" + (grantedPlots - left)); - } - } else { - MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS); - return false; - } - } - return true; - } - - /** - * Get the next plot id (spiral out from 0,0) - * @param start - * @return - */ - @Deprecated - public static PlotId getNextPlot(PlotId start) { - int plots; - PlotId center; - center = new PlotId(0, 0); - plots = Integer.MAX_VALUE; - PlotId currentId; - for (int i = 0; i < plots; i++) { - if (start == null) { - start = new PlotId(0, 0); - } else { - start = start.getNextId(1); - } - currentId = new PlotId(center.x + start.x, center.y + start.y); - return currentId; - } - return null; - } - - /** - * Teleport the player home, or claim a new plot - * @param player - * @param area - * @param start - * @param schem - */ - public static void homeOrAuto(final PlotPlayer player, final PlotArea area, PlotId start, final String schem) { - Set plots = player.getPlots(); - if (!plots.isEmpty()) { - plots.iterator().next().teleportPlayer(player); - } else { - autoClaimSafe(player, area, start, schem); - } - } - - /** - * Claim a new plot for a player - * @param player - * @param area - * @param start - * @param schem - */ - public static void autoClaimSafe(final PlotPlayer player, final PlotArea area, PlotId start, final String schem) { - autoClaimSafe(player, area, start, schem, null); - } - - /** - * Claim a new plot for a player - * @param player - * @param area - * @param start - * @param schem - */ - public static void autoClaimSafe(final PlotPlayer player, final PlotArea area, PlotId start, final String schem, @Nullable final Integer allowed_plots) { - player.setMeta(Auto.class.getName(), true); - autoClaimFromDatabase(player, area, start, new RunnableVal() { - @Override - public void run(final Plot plot) { - TaskManager.IMP.sync(new RunnableVal() { - @Override - public void run(Object ignore) { - player.deleteMeta(Auto.class.getName()); - if (plot == null) { - MainUtil.sendMessage(player, C.NO_FREE_PLOTS); - } else if (checkAllowedPlots(player, area, allowed_plots, 1, 1)) { - plot.claim(player, true, schem, false); - if (area.AUTO_MERGE) { - plot.autoMerge(-1, Integer.MAX_VALUE, player.getUUID(), true); - } - } else { - DBFunc.delete(plot); - } - } - }); - } - }); - } - - public static void autoClaimFromDatabase(final PlotPlayer player, final PlotArea area, PlotId start, final RunnableVal whenDone) { - final Plot plot = area.getNextFreePlot(player, start); - if (plot == null) { - whenDone.run(null); - return; - } - whenDone.value = plot; - plot.owner = player.getUUID(); - DBFunc.createPlotSafe(plot, whenDone, new Runnable() { - @Override - public void run() { - autoClaimFromDatabase(player, area, plot.getId(), whenDone); - } - }); - } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Biome.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Biome.java new file mode 100644 index 000000000..d9c16f1f6 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Biome.java @@ -0,0 +1,38 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; + +@CommandDeclaration(command = "setbiome", permission = "plots.set.biome", description = "Set the plot biome", usage = "/plot biome [biome]", aliases = { + "biome", "sb", "setb", + "b"}, category = CommandCategory.APPEARANCE, requiredType = RequiredType.NONE) +public class Biome extends SetCommand { + + @Override public boolean set(final PlotPlayer player, final Plot plot, final String value) { + int biome = WorldUtil.IMP.getBiomeFromString(value); + if (biome == -1) { + String biomes = + StringMan.join(WorldUtil.IMP.getBiomeList(), C.BLOCK_LIST_SEPARATER.s()); + C.NEED_BIOME.send(player); + MainUtil.sendMessage(player, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + biomes); + return false; + } + if (plot.getRunning() > 0) { + MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); + return false; + } + plot.addRunning(); + plot.setBiome(value.toUpperCase(), new Runnable() { + @Override public void run() { + plot.removeRunning(); + MainUtil.sendMessage(player, C.BIOME_SET_TO.s() + value.toLowerCase()); + } + }); + return true; + } +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Buy.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Buy.java similarity index 56% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Buy.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Buy.java index 38d260ebf..370f18493 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Buy.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Buy.java @@ -1,35 +1,30 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.flag.Flags; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; +import com.github.intellectualsites.plotsquared.plot.util.EconHandler; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; import com.google.common.base.Optional; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal2; -import com.intellectualcrafters.plot.object.RunnableVal3; -import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.plotsquared.general.commands.Command; -import com.plotsquared.general.commands.CommandDeclaration; import java.util.Set; -@CommandDeclaration( - command = "buy", - description = "Buy the plot you are standing on", - usage = "/plot buy", - permission = "plots.buy", - category = CommandCategory.CLAIMING, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "buy", description = "Buy the plot you are standing on", usage = "/plot buy", permission = "plots.buy", category = CommandCategory.CLAIMING, requiredType = RequiredType.NONE) public class Buy extends Command { public Buy() { super(MainCommand.getInstance(), true); } - @Override - public void execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, final RunnableVal2 whenDone) { + @Override public void execute(final PlotPlayer player, String[] args, + RunnableVal3 confirm, + final RunnableVal2 whenDone) { check(EconHandler.manager, C.ECON_DISABLED); final Plot plot; if (args.length != 0) { @@ -41,7 +36,8 @@ public class Buy extends Command { checkTrue(plot.hasOwner(), C.PLOT_UNOWNED); checkTrue(!plot.isOwner(player.getUUID()), C.CANNOT_BUY_OWN); Set plots = plot.getConnectedPlots(); - checkTrue(player.getPlotCount() + plots.size() <= player.getAllowedPlots(), C.CANT_CLAIM_MORE_PLOTS); + checkTrue(player.getPlotCount() + plots.size() <= player.getAllowedPlots(), + C.CANT_CLAIM_MORE_PLOTS); Optional flag = plot.getFlag(Flags.PRICE); if (!flag.isPresent()) { throw new CommandException(C.NOT_FOR_SALE); @@ -53,7 +49,8 @@ public class Buy extends Command { @Override // Success public void run() { C.REMOVED_BALANCE.send(player, price); - EconHandler.manager.depositMoney(UUIDHandler.getUUIDWrapper().getOfflinePlayer(plot.owner), price); + EconHandler.manager + .depositMoney(UUIDHandler.getUUIDWrapper().getOfflinePlayer(plot.owner), price); PlotPlayer owner = UUIDHandler.getPlayer(plot.owner); if (owner != null) { C.PLOT_SOLD.send(owner, plot.getId(), player.getName(), price); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Changelog.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Changelog.java new file mode 100644 index 000000000..720bff1bf --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Changelog.java @@ -0,0 +1,35 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.Updater; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; + +import java.io.IOException; +import java.net.URL; +import java.util.Scanner; + +@CommandDeclaration(command = "changelog", permission = "plots.admin.command.changelog", description = "View the changelog", usage = "/plot changelog", requiredType = RequiredType.NONE, aliases = { + "cl"}, category = CommandCategory.ADMINISTRATION) public class Changelog extends SubCommand { + + @Override public boolean onCommand(PlotPlayer player, String[] args) { + try { + Updater updater = PlotSquared.get().getUpdater(); + String changes = updater != null ? updater.getChanges() : null; + if (changes == null) { + try (Scanner scanner = new Scanner(new URL("http://empcraft.com/plots/cl?" + Integer + .toHexString(PlotSquared.get().getVersion().hash)).openStream(), "UTF-8")) { + changes = scanner.useDelimiter("\\A").next(); + } + } + changes = changes + .replaceAll("#([0-9]+)", "github.com/IntellectualSites/PlotSquared/pulls/$1"); + MainUtil.sendMessage(player, changes); + } catch (IOException e) { + throw new RuntimeException(e); + } + return true; + } + +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Chat.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Chat.java new file mode 100644 index 000000000..ef4dc5d33 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Chat.java @@ -0,0 +1,13 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; + +@CommandDeclaration(command = "chat", description = "Toggle plot chat on or off", usage = "/plot chat [on|off]", permission = "plots.chat", category = CommandCategory.CHAT, requiredType = RequiredType.NONE) +public class Chat extends SubCommand { + + @Override public boolean onCommand(PlotPlayer player, String[] args) { + MainCommand.getInstance().toggle.chat(this, player, new String[0], null, null); + return true; + } +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Claim.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Claim.java similarity index 63% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Claim.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Claim.java index eedc900ae..9edebd05e 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Claim.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Claim.java @@ -1,30 +1,19 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.Expression; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.ByteArrayUtilities; -import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.TaskManager; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.ByteArrayUtilities; +import com.github.intellectualsites.plotsquared.plot.util.EconHandler; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; -@CommandDeclaration(command = "claim", - aliases = "c", - description = "Claim the current plot you're standing on", - category = CommandCategory.CLAIMING, - requiredType = RequiredType.NONE, - permission = "plots.claim", usage = "/plot claim") +@CommandDeclaration(command = "claim", aliases = "c", description = "Claim the current plot you're standing on", category = CommandCategory.CLAIMING, requiredType = RequiredType.NONE, permission = "plots.claim", usage = "/plot claim") public class Claim extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { String schematic = ""; if (args.length >= 1) { schematic = args[0]; @@ -34,11 +23,13 @@ public class Claim extends SubCommand { if (plot == null) { return sendMessage(player, C.NOT_IN_PLOT); } - int currentPlots = Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(loc.getWorld()); + int currentPlots = + Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(loc.getWorld()); int grants = 0; if (currentPlots >= player.getAllowedPlots()) { if (player.hasPersistentMeta("grantedPlots")) { - grants = ByteArrayUtilities.bytesToInteger(player.getPersistentMeta("grantedPlots")); + grants = + ByteArrayUtilities.bytesToInteger(player.getPersistentMeta("grantedPlots")); if (grants <= 0) { player.removePersistentMeta("grantedPlots"); return sendMessage(player, C.CANT_CLAIM_MORE_PLOTS); @@ -56,7 +47,8 @@ public class Claim extends SubCommand { if (!area.SCHEMATICS.contains(schematic.toLowerCase())) { return sendMessage(player, C.SCHEMATIC_INVALID, "non-existent: " + schematic); } - if (!Permissions.hasPermission(player, C.PERMISSION_CLAIM_SCHEMATIC.f(schematic)) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC)) { + if (!Permissions.hasPermission(player, C.PERMISSION_CLAIM_SCHEMATIC.f(schematic)) + && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC)) { return sendMessage(player, C.NO_SCHEMATIC_PERMISSION, schematic); } } @@ -80,7 +72,8 @@ public class Claim extends SubCommand { if (grants == 1) { player.removePersistentMeta("grantedPlots"); } else { - player.setPersistentMeta("grantedPlots", ByteArrayUtilities.integerToBytes(grants - 1)); + player.setPersistentMeta("grantedPlots", + ByteArrayUtilities.integerToBytes(grants - 1)); } sendMessage(player, C.REMOVED_GRANTED_PLOT, "1", "" + (grants - 1)); } @@ -88,11 +81,9 @@ public class Claim extends SubCommand { plot.owner = player.getUUID(); final String finalSchematic = schematic; DBFunc.createPlotSafe(plot, new Runnable() { - @Override - public void run() { + @Override public void run() { TaskManager.IMP.sync(new RunnableVal() { - @Override - public void run(Object value) { + @Override public void run(Object value) { plot.claim(player, true, finalSchematic, false); if (area.AUTO_MERGE) { plot.autoMerge(-1, Integer.MAX_VALUE, player.getUUID(), true); @@ -101,8 +92,7 @@ public class Claim extends SubCommand { }); } }, new Runnable() { - @Override - public void run() { + @Override public void run() { sendMessage(player, C.PLOT_NOT_CLAIMED); } }); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Clear.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Clear.java new file mode 100644 index 000000000..a9dbe3e91 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Clear.java @@ -0,0 +1,67 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.flag.FlagManager; +import com.github.intellectualsites.plotsquared.plot.flag.Flags; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; + +@CommandDeclaration(command = "clear", description = "Clear the plot you stand on", permission = "plots.clear", category = CommandCategory.APPEARANCE, usage = "/plot clear", aliases = "reset", confirmation = true) +public class Clear extends Command { + + // Note: To clear a specific plot use /plot clear + // The syntax also works with any command: /plot + + public Clear() { + super(MainCommand.getInstance(), true); + } + + @Override public void execute(final PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) throws CommandException { + checkTrue(args.length == 0, C.COMMAND_SYNTAX, getUsage()); + final Plot plot = check(player.getCurrentPlot(), C.NOT_IN_PLOT); + checkTrue(plot.isOwner(player.getUUID()) || Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_CLEAR), C.NO_PLOT_PERMS); + checkTrue(plot.getRunning() == 0, C.WAIT_FOR_TIMER); + checkTrue(!Settings.Done.RESTRICT_BUILDING || !Flags.DONE.isSet(plot) || Permissions + .hasPermission(player, C.PERMISSION_CONTINUE), C.DONE_ALREADY_DONE); + confirm.run(this, new Runnable() { + @Override public void run() { + final long start = System.currentTimeMillis(); + boolean result = plot.clear(true, false, new Runnable() { + @Override public void run() { + plot.unlink(); + GlobalBlockQueue.IMP.addTask(new Runnable() { + @Override public void run() { + plot.removeRunning(); + // If the state changes, then mark it as no longer done + if (plot.getFlag(Flags.DONE).isPresent()) { + FlagManager.removePlotFlag(plot, Flags.DONE); + } + if (plot.getFlag(Flags.ANALYSIS).isPresent()) { + FlagManager.removePlotFlag(plot, Flags.ANALYSIS); + } + MainUtil.sendMessage(player, C.CLEARING_DONE, + "" + (System.currentTimeMillis() - start)); + } + }); + } + }); + if (!result) { + MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); + } else { + plot.addRunning(); + } + } + }, null); + } +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Cluster.java similarity index 88% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Cluster.java index 28572b8f5..cd605bf30 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Cluster.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Cluster.java @@ -1,35 +1,24 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.BlockLoc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotCluster; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.plotsquared.general.commands.CommandDeclaration; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import java.util.UUID; -@CommandDeclaration(command = "cluster", - aliases = "clusters", - category = CommandCategory.ADMINISTRATION, - requiredType = RequiredType.NONE, - permission = "plots.cluster", - description = "Manage a plot cluster") +@CommandDeclaration(command = "cluster", aliases = "clusters", category = CommandCategory.ADMINISTRATION, requiredType = RequiredType.NONE, permission = "plots.cluster", description = "Manage a plot cluster") public class Cluster extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { // list, create, delete, resize, invite, kick, leave, helpers, tp, sethome if (args.length == 0) { @@ -83,10 +72,13 @@ public class Cluster extends SubCommand { return false; } if (args.length != 4) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster create "); + MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + "/plot cluster create "); return false; } - int currentClusters = Settings.Limit.GLOBAL ? player.getClusterCount() : player.getPlotCount(player.getLocation().getWorld()); + int currentClusters = Settings.Limit.GLOBAL ? + player.getClusterCount() : + player.getPlotCount(player.getLocation().getWorld()); if (currentClusters >= player.getAllowedPlots()) { return sendMessage(player, C.CANT_CLAIM_MORE_CLUSTERS); } @@ -125,7 +117,8 @@ public class Cluster extends SubCommand { UUID uuid = player.getUUID(); for (Plot plot : plots) { if (!plot.isOwner(uuid)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_CREATE_OTHER); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLUSTER_CREATE_OTHER); return false; } } @@ -139,9 +132,11 @@ public class Cluster extends SubCommand { } else { current = player.getPlayerClusterCount(player.getLocation().getWorld()); } - int allowed = Permissions.hasPermissionRange(player, C.PERMISSION_CLUSTER_SIZE, Settings.Limit.MAX_PLOTS); + int allowed = Permissions.hasPermissionRange(player, C.PERMISSION_CLUSTER_SIZE, + Settings.Limit.MAX_PLOTS); if (current + cluster.getArea() > allowed) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_SIZE + "." + (current + cluster.getArea())); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLUSTER_SIZE + "." + (current + cluster.getArea())); return false; } // create cluster @@ -192,7 +187,8 @@ public class Cluster extends SubCommand { } if (!cluster.owner.equals(player.getUUID())) { if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_DELETE_OTHER)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_DELETE_OTHER); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLUSTER_DELETE_OTHER); return false; } } @@ -207,7 +203,8 @@ public class Cluster extends SubCommand { return false; } if (args.length != 3) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster resize "); + MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + "/plot cluster resize "); return false; } // check pos1 / pos2 @@ -234,7 +231,8 @@ public class Cluster extends SubCommand { } if (!cluster.hasHelperRights(player.getUUID())) { if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_RESIZE_OTHER)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_RESIZE_OTHER); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLUSTER_RESIZE_OTHER); return false; } } @@ -244,21 +242,24 @@ public class Cluster extends SubCommand { MainUtil.sendMessage(player, C.CLUSTER_INTERSECTION, intersect.getName()); return false; } - HashSet existing = area.getPlotSelectionOwned(cluster.getP1(), cluster.getP2()); + HashSet existing = + area.getPlotSelectionOwned(cluster.getP1(), cluster.getP2()); HashSet newPlots = area.getPlotSelectionOwned(pos1, pos2); HashSet removed = (HashSet) existing.clone(); removed.removeAll(newPlots); // Check expand / shrink if (!removed.isEmpty()) { if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_RESIZE_SHRINK)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_RESIZE_SHRINK); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLUSTER_RESIZE_SHRINK); return false; } } newPlots.removeAll(existing); if (!newPlots.isEmpty()) { if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_RESIZE_EXPAND)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_RESIZE_EXPAND); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLUSTER_RESIZE_EXPAND); return false; } } @@ -270,9 +271,11 @@ public class Cluster extends SubCommand { current = player.getPlayerClusterCount(player.getLocation().getWorld()); } current -= cluster.getArea() + (1 + pos2.x - pos1.x) * (1 + pos2.y - pos1.y); - int allowed = Permissions.hasPermissionRange(player, C.PERMISSION_CLUSTER, Settings.Limit.MAX_PLOTS); + int allowed = Permissions + .hasPermissionRange(player, C.PERMISSION_CLUSTER, Settings.Limit.MAX_PLOTS); if (current + cluster.getArea() > allowed) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER.s() + "." + (current + cluster.getArea())); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLUSTER.s() + "." + (current + cluster.getArea())); return false; } // resize cluster @@ -303,7 +306,8 @@ public class Cluster extends SubCommand { } if (!cluster.hasHelperRights(player.getUUID())) { if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_INVITE_OTHER)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_INVITE_OTHER); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLUSTER_INVITE_OTHER); return false; } } @@ -347,7 +351,8 @@ public class Cluster extends SubCommand { } if (!cluster.hasHelperRights(player.getUUID())) { if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_KICK_OTHER)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_KICK_OTHER); + MainUtil + .sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_KICK_OTHER); return false; } } @@ -358,7 +363,8 @@ public class Cluster extends SubCommand { return false; } // Can't kick if the player is yourself, the owner, or not added to the cluster - if (uuid.equals(player.getUUID()) || uuid.equals(cluster.owner) || !cluster.isAdded(uuid)) { + if (uuid.equals(player.getUUID()) || uuid.equals(cluster.owner) || !cluster + .isAdded(uuid)) { MainUtil.sendMessage(player, C.CANNOT_KICK_PLAYER, cluster.getName()); return false; } @@ -372,7 +378,8 @@ public class Cluster extends SubCommand { if (player2 != null) { MainUtil.sendMessage(player2, C.CLUSTER_REMOVED, cluster.getName()); } - for (Plot plot : new ArrayList<>(PS.get().getPlots(player2.getLocation().getWorld(), uuid))) { + for (Plot plot : new ArrayList<>( + PlotSquared.get().getPlots(player2.getLocation().getWorld(), uuid))) { PlotCluster current = plot.getCluster(); if (current != null && current.equals(cluster)) { plot.unclaim(); @@ -425,7 +432,8 @@ public class Cluster extends SubCommand { cluster.invited.remove(uuid); DBFunc.removeInvited(cluster, uuid); MainUtil.sendMessage(player, C.CLUSTER_REMOVED, cluster.getName()); - for (Plot plot : new ArrayList<>(PS.get().getPlots(player.getLocation().getWorld(), uuid))) { + for (Plot plot : new ArrayList<>( + PlotSquared.get().getPlots(player.getLocation().getWorld(), uuid))) { PlotCluster current = plot.getCluster(); if (current != null && current.equals(cluster)) { player.getLocation().getWorld(); @@ -443,7 +451,8 @@ public class Cluster extends SubCommand { return false; } if (args.length != 3) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster helpers "); + MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + "/plot cluster helpers "); return false; } PlotArea area = player.getApplicablePlotArea(); @@ -470,7 +479,8 @@ public class Cluster extends SubCommand { DBFunc.removeHelper(cluster, uuid); return MainUtil.sendMessage(player, C.CLUSTER_REMOVED_HELPER); } - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster helpers "); + MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + "/plot cluster helpers "); return false; } case "spawn": @@ -497,7 +507,8 @@ public class Cluster extends SubCommand { UUID uuid = player.getUUID(); if (!cluster.isAdded(uuid)) { if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_TP_OTHER)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_TP_OTHER); + MainUtil + .sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_TP_OTHER); return false; } } @@ -540,7 +551,8 @@ public class Cluster extends SubCommand { owner = "unknown"; } String name = cluster.getName(); - String size = (cluster.getP2().x - cluster.getP1().x + 1) + "x" + (cluster.getP2().y - cluster.getP1().y + 1); + String size = (cluster.getP2().x - cluster.getP1().x + 1) + "x" + ( + cluster.getP2().y - cluster.getP1().y + 1); String rights = cluster.isAdded(player.getUUID()) + ""; String message = C.CLUSTER_INFO.s(); message = message.replaceAll("%id%", id); @@ -573,7 +585,8 @@ public class Cluster extends SubCommand { } if (!cluster.hasHelperRights(player.getUUID())) { if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_SETHOME_OTHER)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_SETHOME_OTHER); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_CLUSTER_SETHOME_OTHER); return false; } } @@ -581,7 +594,8 @@ public class Cluster extends SubCommand { Location relative = player.getLocation().subtract(base.getX(), 0, base.getZ()); BlockLoc blockloc = new BlockLoc(relative.getX(), relative.getY(), relative.getZ()); cluster.settings.setPosition(blockloc); - DBFunc.setPosition(cluster, relative.getX() + "," + relative.getY() + "," + relative.getZ()); + DBFunc.setPosition(cluster, + relative.getX() + "," + relative.getY() + "," + relative.getZ()); return MainUtil.sendMessage(player, C.POSITION_SET); } MainUtil.sendMessage(player, C.CLUSTER_AVAILABLE_ARGS); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/CommandCategory.java similarity index 65% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/CommandCategory.java index f85efc302..4aeacf85c 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/CommandCategory.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/CommandCategory.java @@ -1,64 +1,56 @@ -package com.intellectualcrafters.plot.commands; - -/** - * CommandCategory. - */ -public enum CommandCategory { - /** - * Claiming CommandConfig. - * Such as: /plot claim - */ - CLAIMING("Claiming"), - /** - * Teleportation CommandConfig. - * Such as: /plot visit - */ - TELEPORT("Teleport"), - /** - * Protection. - */ - SETTINGS("Protection"), - /** - * Chat. - */ - CHAT("Chat"), - /** - * Web. - */ - SCHEMATIC("Web"), - /** - * Cosmetic. - */ - APPEARANCE("Cosmetic"), - /** - * Information CommandConfig. - * Such as: /plot info - */ - INFO("Info"), - /** - * Debug CommandConfig. - * Such as: /plot debug - */ - DEBUG("Debug"), - /** - * Administration commands. - */ - ADMINISTRATION("Admin"); - /** - * The category name (Readable). - */ - private final String name; - /** - * Constructor. - * - * @param name readable name - */ - CommandCategory(String name) { - this.name = name; - } - - @Override - public String toString() { - return this.name; - } -} +package com.github.intellectualsites.plotsquared.plot.commands; + +/** + * CommandCategory. + */ +public enum CommandCategory { + /** + * Claiming CommandConfig. + * Such as: /plot claim + */ + CLAIMING("Claiming"), /** + * Teleportation CommandConfig. + * Such as: /plot visit + */ + TELEPORT("Teleport"), /** + * Protection. + */ + SETTINGS("Protection"), /** + * Chat. + */ + CHAT("Chat"), /** + * Web. + */ + SCHEMATIC("Web"), /** + * Cosmetic. + */ + APPEARANCE("Cosmetic"), /** + * Information CommandConfig. + * Such as: /plot info + */ + INFO("Info"), /** + * Debug CommandConfig. + * Such as: /plot debug + */ + DEBUG("Debug"), /** + * Administration commands. + */ + ADMINISTRATION("Admin"); + /** + * The category name (Readable). + */ + private final String name; + + /** + * Constructor. + * + * @param name readable name + */ + CommandCategory(String name) { + this.name = name; + } + + @Override public String toString() { + return this.name; + } +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Comment.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Comment.java new file mode 100644 index 000000000..7df0d34d1 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Comment.java @@ -0,0 +1,74 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.comment.CommentInbox; +import com.github.intellectualsites.plotsquared.plot.object.comment.PlotComment; +import com.github.intellectualsites.plotsquared.plot.util.CommentManager; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; + +import java.util.Arrays; +import java.util.Map.Entry; + +@CommandDeclaration(command = "comment", aliases = { + "msg"}, description = "Comment on a plot", category = CommandCategory.CHAT, requiredType = RequiredType.NONE, permission = "plots.comment") +public class Comment extends SubCommand { + + @Override public boolean onCommand(PlotPlayer player, String[] args) { + if (args.length < 2) { + sendMessage(player, C.COMMENT_SYNTAX, + StringMan.join(CommentManager.inboxes.keySet(), "|")); + return false; + } + CommentInbox inbox = CommentManager.inboxes.get(args[0].toLowerCase()); + if (inbox == null) { + sendMessage(player, C.COMMENT_SYNTAX, + StringMan.join(CommentManager.inboxes.keySet(), "|")); + return false; + } + Location loc = player.getLocation(); + PlotId id = PlotId.fromString(args[1]); + Plot plot = MainUtil.getPlotFromString(player, args[1], false); + int index; + if (plot == null) { + index = 1; + plot = loc.getPlotAbs(); + } else { + if (args.length < 4) { + sendMessage(player, C.COMMENT_SYNTAX, + StringMan.join(CommentManager.inboxes.keySet(), "|")); + return false; + } + index = 2; + } + if (!inbox.canWrite(plot, player)) { + sendMessage(player, C.NO_PERM_INBOX, ""); + return false; + } + String message = StringMan.join(Arrays.copyOfRange(args, index, args.length), " "); + PlotComment comment = + new PlotComment(loc.getWorld(), id, message, player.getName(), inbox.toString(), + System.currentTimeMillis()); + boolean result = inbox.addComment(plot, comment); + if (!result) { + sendMessage(player, C.NO_PLOT_INBOX, ""); + sendMessage(player, C.COMMENT_SYNTAX, + StringMan.join(CommentManager.inboxes.keySet(), "|")); + return false; + } + for (Entry entry : UUIDHandler.getPlayers().entrySet()) { + PlotPlayer pp = entry.getValue(); + if (pp.getAttribute("chatspy")) { + MainUtil.sendMessage(pp, "/plot comment " + StringMan.join(args, " ")); + } + } + sendMessage(player, C.COMMENT_ADDED); + return true; + } +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Condense.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Condense.java similarity index 77% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Condense.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Condense.java index 17586dc82..94629e08d 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Condense.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Condense.java @@ -1,40 +1,31 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.WorldUtil; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; +import java.util.*; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; -@CommandDeclaration(command = "condense", - permission = "plots.admin", - description = "Condense a plotworld", - category = CommandCategory.ADMINISTRATION, - requiredType = RequiredType.CONSOLE) +@CommandDeclaration(command = "condense", permission = "plots.admin", description = "Condense a plotworld", category = CommandCategory.ADMINISTRATION, requiredType = RequiredType.CONSOLE) public class Condense extends SubCommand { public static boolean TASK = false; - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length != 2 && args.length != 3) { MainUtil.sendMessage(player, "/plot condense [radius]"); return false; } - PlotArea area = PS.get().getPlotAreaByString(args[0]); + PlotArea area = PlotSquared.get().getPlotAreaByString(args[0]); if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) { MainUtil.sendMessage(player, "INVALID AREA"); return false; @@ -42,7 +33,8 @@ public class Condense extends SubCommand { switch (args[1].toLowerCase()) { case "start": { if (args.length == 2) { - MainUtil.sendMessage(player, "/plot condense " + area.toString() + " start "); + MainUtil.sendMessage(player, + "/plot condense " + area.toString() + " start "); return false; } if (Condense.TASK) { @@ -54,7 +46,7 @@ public class Condense extends SubCommand { return false; } int radius = Integer.parseInt(args[2]); - ArrayList plots = new ArrayList<>(PS.get().getPlots(area)); + ArrayList plots = new ArrayList<>(PlotSquared.get().getPlots(area)); // remove non base plots Iterator iterator = plots.iterator(); int maxSize = 0; @@ -112,14 +104,14 @@ public class Condense extends SubCommand { } MainUtil.sendMessage(player, "TASK STARTED..."); Runnable run = new Runnable() { - @Override - public void run() { + @Override public void run() { if (!Condense.TASK) { MainUtil.sendMessage(player, "TASK CANCELLED."); } if (allPlots.isEmpty()) { Condense.TASK = false; - MainUtil.sendMessage(player, "TASK COMPLETE. PLEASE VERIFY THAT NO NEW PLOTS HAVE BEEN CLAIMED DURING TASK."); + MainUtil.sendMessage(player, + "TASK COMPLETE. PLEASE VERIFY THAT NO NEW PLOTS HAVE BEEN CLAIMED DURING TASK."); return; } final Runnable task = this; @@ -134,10 +126,10 @@ public class Condense extends SubCommand { i++; final AtomicBoolean result = new AtomicBoolean(false); result.set(origin.move(possible, new Runnable() { - @Override - public void run() { + @Override public void run() { if (result.get()) { - MainUtil.sendMessage(player, "Moving: " + origin + " -> " + possible); + MainUtil.sendMessage(player, + "Moving: " + origin + " -> " + possible); TaskManager.runTaskLater(task, 1); } } @@ -170,7 +162,8 @@ public class Condense extends SubCommand { return true; case "info": if (args.length == 2) { - MainUtil.sendMessage(player, "/plot condense " + area.toString() + " info "); + MainUtil.sendMessage(player, + "/plot condense " + area.toString() + " info "); return false; } if (!MathMan.isInteger(args[2])) { @@ -193,18 +186,21 @@ public class Condense extends SubCommand { MainUtil.sendMessage(player, "=== INPUT EVAL ==="); MainUtil.sendMessage(player, "INPUT RADIUS: " + radius); MainUtil.sendMessage(player, "ESTIMATED MOVES: " + userMove); - MainUtil.sendMessage(player, "ESTIMATED TIME: No idea, times will drastically change based on the system performance and load"); + MainUtil.sendMessage(player, + "ESTIMATED TIME: No idea, times will drastically change based on the system performance and load"); MainUtil.sendMessage(player, "&e - Radius is measured in plot width"); return true; } - MainUtil.sendMessage(player, "/plot condense " + area.worldname + " [radius]"); + MainUtil.sendMessage(player, + "/plot condense " + area.worldname + " [radius]"); return false; } public Set getPlots(Collection plots, int radius) { HashSet outside = new HashSet<>(); for (Plot plot : plots) { - if (plot.getId().x > radius || plot.getId().x < -radius || plot.getId().y > radius || plot.getId().y < -radius) { + if (plot.getId().x > radius || plot.getId().x < -radius || plot.getId().y > radius + || plot.getId().y < -radius) { outside.add(plot.getId()); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Confirm.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Confirm.java new file mode 100644 index 000000000..c4812b30f --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Confirm.java @@ -0,0 +1,30 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.object.CmdInstance; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.CmdConfirm; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; + +@CommandDeclaration(command = "confirm", permission = "plots.use", description = "Confirm an action", category = CommandCategory.INFO) +public class Confirm extends SubCommand { + + @Override public boolean onCommand(PlotPlayer player, String[] args) { + CmdInstance command = CmdConfirm.getPending(player); + if (command == null) { + MainUtil.sendMessage(player, C.FAILED_CONFIRM); + return false; + } + CmdConfirm.removePending(player); + if ((System.currentTimeMillis() - command.timestamp) + > Settings.Confirmation.CONFIRMATION_TIMEOUT_SECONDS * 1000) { + MainUtil.sendMessage(player, C.EXPIRED_CONFIRM); + return false; + } + TaskManager.runTask(command.command); + return true; + } +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Continue.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Continue.java new file mode 100644 index 000000000..9657f0a79 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Continue.java @@ -0,0 +1,43 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.flag.Flags; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; + +@CommandDeclaration(command = "continue", description = "Continue a plot that was previously marked as done", permission = "plots.continue", category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE) +public class Continue extends SubCommand { + + @Override public boolean onCommand(PlotPlayer player, String[] args) { + Plot plot = player.getCurrentPlot(); + if ((plot == null) || !plot.hasOwner()) { + return !sendMessage(player, C.NOT_IN_PLOT); + } + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_CONTINUE)) { + MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + return false; + } + if (!plot.hasFlag(Flags.DONE)) { + MainUtil.sendMessage(player, C.DONE_NOT_DONE); + return false; + } + int size = plot.getConnectedPlots().size(); + if (Settings.Done.COUNTS_TOWARDS_LIMIT && (player.getAllowedPlots() + < player.getPlotCount() + size)) { + MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_ADMIN_COMMAND_CONTINUE); + return false; + } + if (plot.getRunning() > 0) { + MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); + return false; + } + plot.removeFlag(Flags.DONE); + MainUtil.sendMessage(player, C.DONE_REMOVED); + return true; + } +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Copy.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Copy.java similarity index 54% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Copy.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Copy.java index 99849f926..ab9c7b8f8 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Copy.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Copy.java @@ -1,31 +1,25 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; -@CommandDeclaration( - command = "copy", - permission = "plots.copy", - aliases = {"copypaste"}, - category = CommandCategory.CLAIMING, - description = "Copy a plot", - usage = "/plot copy ", - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "copy", permission = "plots.copy", aliases = { + "copypaste"}, category = CommandCategory.CLAIMING, description = "Copy a plot", usage = "/plot copy ", requiredType = RequiredType.NONE) public class Copy extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { Location loc = player.getLocation(); Plot plot1 = loc.getPlotAbs(); if (plot1 == null) { return !MainUtil.sendMessage(player, C.NOT_IN_PLOT); } - if (!plot1.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN.s())) { + if (!plot1.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN.s())) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } @@ -47,8 +41,7 @@ public class Copy extends SubCommand { return false; } if (plot1.copy(plot2, new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(player, C.COPY_SUCCESS); } })) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/CreateRoadSchematic.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/CreateRoadSchematic.java new file mode 100644 index 000000000..779bf46c0 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/CreateRoadSchematic.java @@ -0,0 +1,30 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld; +import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; + +@CommandDeclaration(command = "createroadschematic", aliases = { + "crs"}, category = CommandCategory.ADMINISTRATION, requiredType = RequiredType.NONE, permission = "plots.createroadschematic", description = "Add a road schematic to your world using the roads around your current plot", usage = "/plot createroadschematic") +public class CreateRoadSchematic extends SubCommand { + + @Override public boolean onCommand(PlotPlayer player, String[] args) { + Location loc = player.getLocation(); + Plot plot = loc.getPlotAbs(); + if (plot == null) { + return sendMessage(player, C.NOT_IN_PLOT); + } + if (!(loc.getPlotArea() instanceof HybridPlotWorld)) { + return sendMessage(player, C.NOT_IN_PLOT_WORLD); + } + HybridUtils.manager.setupRoadSchematic(plot); + MainUtil.sendMessage(player, + "$1Saved new road schematic. To test the road, fly to a few other plots and use /plot debugroadregen"); + return true; + } +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Database.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Database.java similarity index 60% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Database.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Database.java index 5f9c14108..c89821f4c 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Database.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Database.java @@ -1,18 +1,19 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.database.MySQL; +import com.github.intellectualsites.plotsquared.plot.database.SQLManager; +import com.github.intellectualsites.plotsquared.plot.database.SQLite; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.database.MySQL; -import com.intellectualcrafters.plot.database.SQLManager; -import com.intellectualcrafters.plot.database.SQLite; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.worlds.SinglePlotArea; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.TaskManager; -import com.plotsquared.general.commands.CommandDeclaration; import java.io.File; import java.sql.SQLException; import java.util.ArrayList; @@ -21,20 +22,14 @@ import java.util.HashMap; import java.util.List; import java.util.Map.Entry; -@CommandDeclaration( - command = "database", - aliases = {"convert"}, - category = CommandCategory.ADMINISTRATION, - permission = "plots.database", - description = "Convert/Backup Storage", - requiredType = RequiredType.CONSOLE, - usage = "/plot database [area] ") +@CommandDeclaration(command = "database", aliases = { + "convert"}, category = CommandCategory.ADMINISTRATION, permission = "plots.database", description = "Convert/Backup Storage", requiredType = RequiredType.CONSOLE, usage = "/plot database [area] ") public class Database extends SubCommand { - public static void insertPlots(final SQLManager manager, final List plots, final PlotPlayer player) { + public static void insertPlots(final SQLManager manager, final List plots, + final PlotPlayer player) { TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { try { ArrayList ps = new ArrayList<>(); for (Plot p : plots) { @@ -42,33 +37,32 @@ public class Database extends SubCommand { } MainUtil.sendMessage(player, "&6Starting..."); manager.createPlotsAndData(ps, new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(player, "&6Database conversion finished!"); manager.close(); } }); } catch (Exception e) { - MainUtil.sendMessage(player, "Failed to insert plot objects, see stacktrace for info"); + MainUtil.sendMessage(player, + "Failed to insert plot objects, see stacktrace for info"); e.printStackTrace(); } } }); } - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length < 1) { MainUtil.sendMessage(player, "/plot database [area] "); return false; } List plots; - PlotArea area = PS.get().getPlotAreaByString(args[0]); + PlotArea area = PlotSquared.get().getPlotAreaByString(args[0]); if (area != null) { - plots = PS.get().sortPlotsByTemp(area.getPlots()); + plots = PlotSquared.get().sortPlotsByTemp(area.getPlots()); args = Arrays.copyOfRange(args, 1, args.length); } else { - plots = PS.get().sortPlotsByTemp(PS.get().getPlots()); + plots = PlotSquared.get().sortPlotsByTemp(PlotSquared.get().getPlots()); } if (args.length < 1) { MainUtil.sendMessage(player, "/plot database [world] "); @@ -76,27 +70,30 @@ public class Database extends SubCommand { return false; } try { - com.intellectualcrafters.plot.database.Database implementation; + com.github.intellectualsites.plotsquared.plot.database.Database implementation; String prefix = ""; switch (args[0].toLowerCase()) { case "import": if (args.length < 2) { - MainUtil.sendMessage(player, "/plot database import [prefix]"); + MainUtil + .sendMessage(player, "/plot database import [prefix]"); return false; } - File file = MainUtil.getFile(PS.get().IMP.getDirectory(), args[1].endsWith(".db") ? args[1] : args[1] + ".db"); + File file = MainUtil.getFile(PlotSquared.get().IMP.getDirectory(), + args[1].endsWith(".db") ? args[1] : args[1] + ".db"); if (!file.exists()) { MainUtil.sendMessage(player, "&6Database does not exist: " + file); return false; } MainUtil.sendMessage(player, "&6Starting..."); implementation = new SQLite(file); - SQLManager manager = new SQLManager(implementation, args.length == 3 ? args[2] : "", true); + SQLManager manager = + new SQLManager(implementation, args.length == 3 ? args[2] : "", true); HashMap> map = manager.getPlots(); plots = new ArrayList<>(); for (Entry> entry : map.entrySet()) { String areaname = entry.getKey(); - PlotArea pa = PS.get().getPlotAreaByString(areaname); + PlotArea pa = PlotSquared.get().getPlotAreaByString(areaname); if (pa != null) { for (Entry entry2 : entry.getValue().entrySet()) { Plot plot = entry2.getValue(); @@ -106,9 +103,13 @@ public class Database extends SubCommand { if (newPlot != null) { PlotId newId = newPlot.getId(); PlotId id = plot.getId(); - File worldFile = new File(PS.imp().getWorldContainer(), id.toCommaSeparatedString()); + File worldFile = + new File(PlotSquared.imp().getWorldContainer(), + id.toCommaSeparatedString()); if (worldFile.exists()) { - File newFile = new File(PS.imp().getWorldContainer(), newId.toCommaSeparatedString()); + File newFile = + new File(PlotSquared.imp().getWorldContainer(), + newId.toCommaSeparatedString()); worldFile.renameTo(newFile); } id.x = newId.x; @@ -119,31 +120,33 @@ public class Database extends SubCommand { continue; } } - MainUtil.sendMessage(player, "Skipping duplicate plot: " + plot + " | id=" + plot.temp); + MainUtil.sendMessage(player, + "Skipping duplicate plot: " + plot + " | id=" + plot.temp); continue; } plot.setArea(pa); plots.add(plot); } } else { - HashMap plotmap = PS.get().plots_tmp.get(areaname); + HashMap plotmap = + PlotSquared.get().plots_tmp.get(areaname); if (plotmap == null) { plotmap = new HashMap<>(); - PS.get().plots_tmp.put(areaname, plotmap); + PlotSquared.get().plots_tmp.put(areaname, plotmap); } plotmap.putAll(entry.getValue()); } } DBFunc.createPlotsAndData(plots, new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(player, "&6Database conversion finished!"); } }); return true; case "mysql": if (args.length < 6) { - return MainUtil.sendMessage(player, "/plot database mysql [host] [port] [username] [password] [database] {prefix}"); + return MainUtil.sendMessage(player, + "/plot database mysql [host] [port] [username] [password] [database] {prefix}"); } String host = args[1]; String port = args[2]; @@ -159,7 +162,8 @@ public class Database extends SubCommand { if (args.length < 2) { return MainUtil.sendMessage(player, "/plot database sqlite [file]"); } - File sqliteFile = MainUtil.getFile(PS.get().IMP.getDirectory(), args[1] + ".db"); + File sqliteFile = + MainUtil.getFile(PlotSquared.get().IMP.getDirectory(), args[1] + ".db"); implementation = new SQLite(sqliteFile); break; default: @@ -171,15 +175,18 @@ public class Database extends SubCommand { return true; } catch (ClassNotFoundException | SQLException e) { MainUtil.sendMessage(player, "$1Failed to save plots, read stacktrace for info"); - MainUtil.sendMessage(player, "&d==== Here is an ugly stacktrace, if you are interested in those things ==="); + MainUtil.sendMessage(player, + "&d==== Here is an ugly stacktrace, if you are interested in those things ==="); e.printStackTrace(); MainUtil.sendMessage(player, "&d==== End of stacktrace ===="); - MainUtil.sendMessage(player, "$1Please make sure you are using the correct arguments!"); + MainUtil + .sendMessage(player, "$1Please make sure you are using the correct arguments!"); return false; } } catch (ClassNotFoundException | SQLException e) { MainUtil.sendMessage(player, "$1Failed to open connection, read stacktrace for info"); - MainUtil.sendMessage(player, "&d==== Here is an ugly stacktrace, if you are interested in those things ==="); + MainUtil.sendMessage(player, + "&d==== Here is an ugly stacktrace, if you are interested in those things ==="); e.printStackTrace(); MainUtil.sendMessage(player, "&d==== End of stacktrace ===="); MainUtil.sendMessage(player, "$1Please make sure you are using the correct arguments!"); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Debug.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Debug.java similarity index 56% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Debug.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Debug.java index ccc4ad95b..5fcb921a0 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Debug.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Debug.java @@ -1,21 +1,16 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.StringMan; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; -@CommandDeclaration(command = "debug", - category = CommandCategory.DEBUG, - description = "Show debug information", - usage = "/plot debug [msg]", - permission = "plots.admin") +@CommandDeclaration(command = "debug", category = CommandCategory.DEBUG, description = "Show debug information", usage = "/plot debug [msg]", permission = "plots.admin") public class Debug extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) { StringBuilder msg = new StringBuilder(); for (C caption : C.values()) { @@ -30,8 +25,9 @@ public class Debug extends SubCommand { String section = C.DEBUG_SECTION.s(); information.append(header); information.append(getSection(section, "PlotArea")); - information.append(getLine(line, "Plot Worlds", StringMan.join(PS.get().getPlotAreas(), ", "))); - information.append(getLine(line, "Owned Plots", PS.get().getPlots().size())); + information.append( + getLine(line, "Plot Worlds", StringMan.join(PlotSquared.get().getPlotAreas(), ", "))); + information.append(getLine(line, "Owned Plots", PlotSquared.get().getPlots().size())); information.append(getSection(section, "Messages")); information.append(getLine(line, "Total Messages", C.values().length)); information.append(getLine(line, "View all captions", "/plot debug msg")); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugAllowUnsafe.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugAllowUnsafe.java new file mode 100644 index 000000000..2f558828a --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugAllowUnsafe.java @@ -0,0 +1,28 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +@CommandDeclaration(command = "debugallowunsafe", description = "Allow unsafe actions until toggled off", usage = "/plot debugallowunsafe", category = CommandCategory.DEBUG, requiredType = RequiredType.NONE, permission = "plots.debugallowunsafe") +public class DebugAllowUnsafe extends SubCommand { + + public static final List unsafeAllowed = new ArrayList<>(); + + @Override public boolean onCommand(PlotPlayer player, String[] args) { + + if (unsafeAllowed.contains(player.getUUID())) { + unsafeAllowed.remove(player.getUUID()); + sendMessage(player, C.DEBUGALLOWUNSAFE_OFF); + } else { + unsafeAllowed.add(player.getUUID()); + sendMessage(player, C.DEBUGALLOWUNSAFE_ON); + } + return true; + } + +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugClaimTest.java similarity index 51% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugClaimTest.java index 3e00d0be5..e57a543ef 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugClaimTest.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugClaimTest.java @@ -1,46 +1,32 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; import com.google.common.collect.BiMap; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.ChunkLoc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotManager; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.StringWrapper; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.WorldUtil; -import com.plotsquared.general.commands.CommandDeclaration; import java.util.ArrayList; import java.util.Map; import java.util.UUID; -@CommandDeclaration( - command = "debugclaimtest", - description = "If you accidentally delete your database, this command will attempt to restore all plots based on the data from plot signs. " - + "Execution time may vary", - category = CommandCategory.DEBUG, - requiredType = RequiredType.CONSOLE, - permission = "plots.debugclaimtest") +@CommandDeclaration(command = "debugclaimtest", description = + "If you accidentally delete your database, this command will attempt to restore all plots based on the data from plot signs. " + + "Execution time may vary", category = CommandCategory.DEBUG, requiredType = RequiredType.CONSOLE, permission = "plots.debugclaimtest") public class DebugClaimTest extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length < 3) { - return !MainUtil - .sendMessage( - null, - "If you accidentally delete your database, this command will attempt to restore all plots based on the data from the " - + "plot signs. \n\n&cMissing world arg /plot debugclaimtest {world} {PlotId min} {PlotId max}"); + return !MainUtil.sendMessage(null, + "If you accidentally delete your database, this command will attempt to restore all plots based on the data from the " + + "plot signs. \n\n&cMissing world arg /plot debugclaimtest {world} {PlotId min} {PlotId max}"); } - PlotArea area = PS.get().getPlotAreaByString(args[0]); + PlotArea area = PlotSquared.get().getPlotAreaByString(args[0]); if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) { C.NOT_VALID_PLOT_WORLD.send(player, args[0]); return false; @@ -53,11 +39,13 @@ public class DebugClaimTest extends SubCommand { max = PlotId.fromString(args[2]); } catch (Exception ignored) { return !MainUtil.sendMessage(player, - "&cInvalid min/max values. &7The values are to Plot IDs in the format &cX;Y &7where X;Y are the plot coords\nThe conversion " - + "will only check the plots in the selected area."); + "&cInvalid min/max values. &7The values are to Plot IDs in the format &cX;Y &7where X;Y are the plot coords\nThe conversion " + + "will only check the plots in the selected area."); } - MainUtil.sendMessage(player, "&3Sign Block&8->&3Plot&8: &7Beginning sign to plot conversion. This may take a while..."); - MainUtil.sendMessage(player, "&3Sign Block&8->&3Plot&8: Found an excess of 250,000 chunks. Limiting search radius... (~3.8 min)"); + MainUtil.sendMessage(player, + "&3Sign Block&8->&3Plot&8: &7Beginning sign to plot conversion. This may take a while..."); + MainUtil.sendMessage(player, + "&3Sign Block&8->&3Plot&8: Found an excess of 250,000 chunks. Limiting search radius... (~3.8 min)"); PlotManager manager = area.getPlotManager(); ArrayList plots = new ArrayList<>(); for (PlotId id : MainUtil.getPlotSelectionIds(min, max)) { @@ -80,8 +68,10 @@ public class DebugClaimTest extends SubCommand { BiMap map = UUIDHandler.getUuidMap(); UUID uuid = map.get(new StringWrapper(line)); if (uuid == null) { - for (Map.Entry stringWrapperUUIDEntry : map.entrySet()) { - if (stringWrapperUUIDEntry.getKey().value.toLowerCase().startsWith(line.toLowerCase())) { + for (Map.Entry stringWrapperUUIDEntry : map + .entrySet()) { + if (stringWrapperUUIDEntry.getKey().value.toLowerCase() + .startsWith(line.toLowerCase())) { uuid = stringWrapperUUIDEntry.getValue(); break; } @@ -91,20 +81,22 @@ public class DebugClaimTest extends SubCommand { uuid = UUIDHandler.getUUID(line, null); } if (uuid != null) { - MainUtil.sendMessage(player, " - &aFound plot: " + plot.getId() + " : " + line); + MainUtil + .sendMessage(player, " - &aFound plot: " + plot.getId() + " : " + line); plot.setOwner(uuid); plots.add(plot); } else { - MainUtil.sendMessage(player, " - &cInvalid PlayerName: " + plot.getId() + " : " + line); + MainUtil.sendMessage(player, + " - &cInvalid PlayerName: " + plot.getId() + " : " + line); } } } } if (!plots.isEmpty()) { - MainUtil.sendMessage(player, "&3Sign Block&8->&3Plot&8: &7Updating '" + plots.size() + "' plots!"); + MainUtil.sendMessage(player, + "&3Sign Block&8->&3Plot&8: &7Updating '" + plots.size() + "' plots!"); DBFunc.createPlotsAndData(plots, new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(player, "&6Database update finished!"); } }); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugExec.java similarity index 63% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugExec.java index 2219c08e4..ca5ba76d3 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugExec.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugExec.java @@ -1,78 +1,45 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.flag.Flag; +import com.github.intellectualsites.plotsquared.plot.flag.FlagManager; +import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; +import com.github.intellectualsites.plotsquared.plot.listener.WEManager; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; +import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; +import com.github.intellectualsites.plotsquared.plot.util.expiry.PlotAnalysis; import com.google.common.io.Files; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.flag.Flag; -import com.intellectualcrafters.plot.flag.FlagManager; -import com.intellectualcrafters.plot.generator.HybridUtils; -import com.intellectualcrafters.plot.object.ConsolePlayer; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.OfflinePlotPlayer; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotBlock; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotMessage; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.RunnableVal2; -import com.intellectualcrafters.plot.object.RunnableVal3; -import com.intellectualcrafters.plot.util.AbstractTitle; -import com.intellectualcrafters.plot.util.ChunkManager; -import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.SetupUtils; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.WorldUtil; -import com.intellectualcrafters.plot.util.block.GlobalBlockQueue; -import com.intellectualcrafters.plot.util.expiry.ExpireManager; -import com.intellectualcrafters.plot.util.expiry.PlotAnalysis; -import com.plotsquared.general.commands.Command; -import com.plotsquared.general.commands.CommandDeclaration; -import com.plotsquared.listener.WEManager; + +import javax.script.*; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.sql.Timestamp; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.UUID; -import javax.script.Bindings; -import javax.script.ScriptContext; -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import javax.script.ScriptException; -import javax.script.SimpleScriptContext; +import java.util.*; -@CommandDeclaration(command = "debugexec", - permission = "plots.admin", - description = "Mutli-purpose debug command", - aliases = {"exec", "$"}, - category = CommandCategory.DEBUG) -public class DebugExec extends SubCommand { +@CommandDeclaration(command = "debugexec", permission = "plots.admin", description = "Mutli-purpose debug command", aliases = { + "exec", "$"}, category = CommandCategory.DEBUG) public class DebugExec extends SubCommand { private ScriptEngine engine; private Bindings scope; public DebugExec() { try { - if (PS.get() != null) { - File file = new File(PS.get().IMP.getDirectory(), Settings.Paths.SCRIPTS + File.separator + "start.js"); + if (PlotSquared.get() != null) { + File file = new File(PlotSquared.get().IMP.getDirectory(), + Settings.Paths.SCRIPTS + File.separator + "start.js"); if (file.exists()) { init(); - String script = StringMan.join(Files - .readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + Settings.Paths.SCRIPTS), "start.js"), - StandardCharsets.UTF_8), - System.getProperty("line.separator")); + String script = StringMan.join(Files.readLines(new File(new File( + PlotSquared.get().IMP.getDirectory() + File.separator + + Settings.Paths.SCRIPTS), "start.js"), StandardCharsets.UTF_8), + System.getProperty("line.separator")); this.scope.put("THIS", this); this.scope.put("PlotPlayer", ConsolePlayer.getConsole()); this.engine.eval(script, this.scope); @@ -121,10 +88,10 @@ public class DebugExec extends SubCommand { this.scope.put("RunnableVal", RunnableVal.class); // Instances - this.scope.put("PS", PS.get()); + this.scope.put("PS", PlotSquared.get()); this.scope.put("GlobalBlockQueue", GlobalBlockQueue.IMP); this.scope.put("ExpireManager", ExpireManager.IMP); - if (PS.get().worldedit != null) { + if (PlotSquared.get().worldedit != null) { this.scope.put("WEManager", new WEManager()); } this.scope.put("TaskManager", TaskManager.IMP); @@ -139,7 +106,7 @@ public class DebugExec extends SubCommand { this.scope.put("UUIDHandler", UUIDHandler.implementation); this.scope.put("DBFunc", DBFunc.dbManager); this.scope.put("HybridUtils", HybridUtils.manager); - this.scope.put("IMP", PS.get().IMP); + this.scope.put("IMP", PlotSquared.get().IMP); this.scope.put("MainCommand", MainCommand.getInstance()); // enums @@ -148,10 +115,11 @@ public class DebugExec extends SubCommand { } } - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { - List allowed_params = - Arrays.asList("analyze", "calibrate-analysis", "remove-flag", "stop-expire", "start-expire", "seen", "list-scripts", "start-rgar", "stop-rgar", "help", "addcmd", "runasync", "run", "allcmd", "all"); + @Override public boolean onCommand(final PlotPlayer player, String[] args) { + List allowed_params = Arrays + .asList("analyze", "calibrate-analysis", "remove-flag", "stop-expire", "start-expire", + "seen", "list-scripts", "start-rgar", "stop-rgar", "help", "addcmd", "runasync", + "run", "allcmd", "all"); if (args.length > 0) { String arg = args[0].toLowerCase(); String script; @@ -170,19 +138,20 @@ public class DebugExec extends SubCommand { } MainUtil.sendMessage(player, "$1Starting task..."); HybridUtils.manager.analyzePlot(plot, new RunnableVal() { - @Override - public void run(PlotAnalysis value) { - MainUtil.sendMessage(player, "$1Done: $2Use $3/plot debugexec analyze$2 for more information"); + @Override public void run(PlotAnalysis value) { + MainUtil.sendMessage(player, + "$1Done: $2Use $3/plot debugexec analyze$2 for more information"); } }); return true; } case "calibrate-analysis": if (args.length != 2) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec analyze "); + MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + "/plot debugexec analyze "); MainUtil.sendMessage(player, - "$1 $2= $1The percentage of plots you want to clear (100 clears 100% of plots so no point calibrating " - + "it)"); + "$1 $2= $1The percentage of plots you want to clear (100 clears 100% of plots so no point calibrating " + + "it)"); return false; } double threshold; @@ -190,12 +159,12 @@ public class DebugExec extends SubCommand { threshold = Integer.parseInt(args[1]) / 100d; } catch (NumberFormatException ignored) { MainUtil.sendMessage(player, "$2Invalid threshold: " + args[1]); - MainUtil.sendMessage(player, "$1 $2= $1The percentage of plots you want to clear as a number between 0 - 100"); + MainUtil.sendMessage(player, + "$1 $2= $1The percentage of plots you want to clear as a number between 0 - 100"); return false; } PlotAnalysis.calcOptimalModifiers(new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(player, "$1Thank you for calibrating plot expiry"); } }, threshold); @@ -207,11 +176,12 @@ public class DebugExec extends SubCommand { return MainUtil.sendMessage(player, "Cancelled task."); case "remove-flag": if (args.length != 2) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec remove-flag "); + MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + "/plot debugexec remove-flag "); return false; } String flag = args[1]; - for (Plot plot : PS.get().getBasePlots()) { + for (Plot plot : PlotSquared.get().getBasePlots()) { Flag flag1 = FlagManager.getFlag(flag); if (plot.getFlag(flag1).isPresent()) { plot.removeFlag(flag1); @@ -220,22 +190,25 @@ public class DebugExec extends SubCommand { return MainUtil.sendMessage(player, "Cleared flag: " + flag); case "start-rgar": { if (args.length != 2) { - MainUtil.sendMessage(player, "&cInvalid syntax: /plot debugexec start-rgar "); + MainUtil.sendMessage(player, + "&cInvalid syntax: /plot debugexec start-rgar "); return false; } - PlotArea area = PS.get().getPlotAreaByString(args[1]); + PlotArea area = PlotSquared.get().getPlotAreaByString(args[1]); if (area == null) { MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD, args[1]); return false; } boolean result; if (HybridUtils.regions != null) { - result = HybridUtils.manager.scheduleRoadUpdate(area, HybridUtils.regions, 0); + result = + HybridUtils.manager.scheduleRoadUpdate(area, HybridUtils.regions, 0); } else { result = HybridUtils.manager.scheduleRoadUpdate(area, 0); } if (!result) { - MainUtil.sendMessage(player, "&cCannot schedule mass schematic update! (Is one already in progress?)"); + MainUtil.sendMessage(player, + "&cCannot schedule mass schematic update! (Is one already in progress?)"); return false; } return true; @@ -267,7 +240,8 @@ public class DebugExec extends SubCommand { } OfflinePlotPlayer op = UUIDHandler.getUUIDWrapper().getOfflinePlayer(uuid); if (op == null || op.getLastPlayed() == 0) { - return MainUtil.sendMessage(player, "Player hasn't connected before: " + args[1]); + return MainUtil + .sendMessage(player, "Player hasn't connected before: " + args[1]); } Timestamp stamp = new Timestamp(op.getLastPlayed()); Date date = new Date(stamp.getTime()); @@ -281,18 +255,21 @@ public class DebugExec extends SubCommand { case "he": case "?": case "help": - MainUtil.sendMessage(player, "Possible sub commands: /plot debugexec <" + StringMan.join(allowed_params, "|") + ">"); + MainUtil.sendMessage(player, + "Possible sub commands: /plot debugexec <" + StringMan + .join(allowed_params, "|") + ">"); return false; case "addcmd": try { - final String cmd = StringMan.join(Files - .readLines(MainUtil.getFile(new File(PS.get().IMP.getDirectory() + File.separator + Settings.Paths.SCRIPTS), - args[1]), - StandardCharsets.UTF_8), - System.getProperty("line.separator")); - new Command(MainCommand.getInstance(), true, args[1].split("\\.")[0], null, RequiredType.NONE, CommandCategory.DEBUG) { - @Override - public void execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { + final String cmd = StringMan.join(Files.readLines(MainUtil.getFile(new File( + PlotSquared.get().IMP.getDirectory() + File.separator + + Settings.Paths.SCRIPTS), args[1]), StandardCharsets.UTF_8), + System.getProperty("line.separator")); + new Command(MainCommand.getInstance(), true, args[1].split("\\.")[0], null, + RequiredType.NONE, CommandCategory.DEBUG) { + @Override public void execute(PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) { try { DebugExec.this.scope.put("PlotPlayer", player); DebugExec.this.scope.put("args", args); @@ -306,18 +283,18 @@ public class DebugExec extends SubCommand { return true; } catch (IOException e) { e.printStackTrace(); - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec addcmd "); + MainUtil + .sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec addcmd "); return false; } case "runasync": async = true; case "run": try { - script = StringMan.join(Files - .readLines(MainUtil.getFile(new File(PS.get().IMP.getDirectory() + File.separator + Settings.Paths.SCRIPTS), - args[1]), - StandardCharsets.UTF_8), - System.getProperty("line.separator")); + script = StringMan.join(Files.readLines(MainUtil.getFile(new File( + PlotSquared.get().IMP.getDirectory() + File.separator + + Settings.Paths.SCRIPTS), args[1]), StandardCharsets.UTF_8), + System.getProperty("line.separator")); if (args.length > 2) { HashMap replacements = new HashMap<>(); for (int i = 2; i < args.length; i++) { @@ -331,7 +308,8 @@ public class DebugExec extends SubCommand { } break; case "list-scripts": - String path = PS.get().IMP.getDirectory() + File.separator + Settings.Paths.SCRIPTS; + String path = PlotSquared.get().IMP.getDirectory() + File.separator + + Settings.Paths.SCRIPTS; File folder = new File(path); File[] filesArray = folder.listFiles(); @@ -351,40 +329,42 @@ public class DebugExec extends SubCommand { } List allFiles = Arrays.asList(filesArray); - paginate(player, allFiles, 8, page, new RunnableVal3() { + paginate(player, allFiles, 8, page, + new RunnableVal3() { - @Override - public void run(Integer i, File file, PlotMessage message) { - String name = file.getName(); - message.text("[").color("$3").text(String.valueOf(i)).color("$1").text("]").color("$3").text(' ' + name).color("$1"); - } - }, "/plot debugexec list-scripts", "List of scripts"); + @Override public void run(Integer i, File file, PlotMessage message) { + String name = file.getName(); + message.text("[").color("$3").text(String.valueOf(i)).color("$1") + .text("]").color("$3").text(' ' + name).color("$1"); + } + }, "/plot debugexec list-scripts", "List of scripts"); return true; case "allcmd": if (args.length < 3) { - C.COMMAND_SYNTAX.send(player, "/plot debugexec allcmd "); + C.COMMAND_SYNTAX + .send(player, "/plot debugexec allcmd "); return false; } long start = System.currentTimeMillis(); Command cmd = MainCommand.getInstance().getCommand(args[3]); String[] params = Arrays.copyOfRange(args, 4, args.length); if ("true".equals(args[1])) { - Location loc = player.getMeta("location"); - Plot plot = player.getMeta("lastplot"); - for (Plot current : PS.get().getBasePlots()) { - player.setMeta("location", current.getBottomAbs()); - player.setMeta("lastplot", current); + Location loc = player.getMeta(PlotPlayer.META_LOCATION); + Plot plot = player.getMeta(PlotPlayer.META_LAST_PLOT); + for (Plot current : PlotSquared.get().getBasePlots()) { + player.setMeta(PlotPlayer.META_LOCATION, current.getBottomAbs()); + player.setMeta(PlotPlayer.META_LAST_PLOT, current); cmd.execute(player, params, null, null); } if (loc == null) { - player.deleteMeta("location"); + player.deleteMeta(PlotPlayer.META_LOCATION); } else { - player.setMeta("location", loc); + player.setMeta(PlotPlayer.META_LOCATION, loc); } if (plot == null) { - player.deleteMeta("lastplot"); + player.deleteMeta(PlotPlayer.META_LAST_PLOT); } else { - player.setMeta("lastplot", plot); + player.setMeta(PlotPlayer.META_LAST_PLOT, plot); } player.sendMessage("&c> " + (System.currentTimeMillis() - start)); return true; @@ -392,7 +372,9 @@ public class DebugExec extends SubCommand { init(); this.scope.put("_2", params); this.scope.put("_3", cmd); - script = "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" + args[1] + script = + "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" + + args[1] + "){PlotPlayer.setMeta(\"location\",plot.getBottomAbs());PlotPlayer.setMeta(\"lastplot\",plot);_3.onCommand" + "(PlotPlayer,_2)}}"; @@ -402,9 +384,10 @@ public class DebugExec extends SubCommand { C.COMMAND_SYNTAX.send(player, "/plot debugexec all "); return false; } - script = "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" + args[1] + "){" + StringMan - .join(Arrays.copyOfRange(args, 2, args.length), " ") - + "}}"; + script = + "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" + + args[1] + "){" + StringMan + .join(Arrays.copyOfRange(args, 2, args.length), " ") + "}}"; break; default: @@ -416,13 +399,12 @@ public class DebugExec extends SubCommand { } init(); this.scope.put("PlotPlayer", player); - PS.debug("> " + script); + PlotSquared.debug("> " + script); try { if (async) { final String toExec = script; TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { long start = System.currentTimeMillis(); Object result = null; try { @@ -430,13 +412,15 @@ public class DebugExec extends SubCommand { } catch (ScriptException e) { e.printStackTrace(); } - PS.log("> " + (System.currentTimeMillis() - start) + "ms -> " + result); + PlotSquared.log( + "> " + (System.currentTimeMillis() - start) + "ms -> " + result); } }); } else { long start = System.currentTimeMillis(); Object result = this.engine.eval(script, this.scope); - PS.log("> " + (System.currentTimeMillis() - start) + "ms -> " + result); + PlotSquared + .log("> " + (System.currentTimeMillis() - start) + "ms -> " + result); } return true; } catch (ScriptException e) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugFixFlags.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugFixFlags.java new file mode 100644 index 000000000..eaea2ad82 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugFixFlags.java @@ -0,0 +1,50 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.Argument; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.flag.Flag; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; + +@CommandDeclaration(command = "debugfixflags", usage = "/plot debugfixflags ", permission = "plots.debugfixflags", description = "Attempt to fix all flags for a world", requiredType = RequiredType.CONSOLE, category = CommandCategory.DEBUG) +public class DebugFixFlags extends SubCommand { + + public DebugFixFlags() { + super(Argument.String); + } + + @Override public boolean onCommand(PlotPlayer player, String[] args) { + PlotArea area = PlotSquared.get().getPlotAreaByString(args[0]); + if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) { + MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD, args[0]); + return false; + } + MainUtil.sendMessage(player, "&8--- &6Starting task &8 ---"); + for (Plot plot : area.getPlots()) { + HashMap, Object> flags = plot.getFlags(); + Iterator, Object>> i = flags.entrySet().iterator(); + boolean changed = false; + while (i.hasNext()) { + if (i.next().getKey() == null) { + changed = true; + i.remove(); + } + } + if (changed) { + DBFunc.setFlags(plot, plot.getFlags()); + } + } + MainUtil.sendMessage(player, "&aDone!"); + return true; + } +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugImportWorlds.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugImportWorlds.java new file mode 100644 index 000000000..7a8d92744 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugImportWorlds.java @@ -0,0 +1,57 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; +import com.github.intellectualsites.plotsquared.plot.object.worlds.PlotAreaManager; +import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotArea; +import com.github.intellectualsites.plotsquared.plot.object.worlds.SinglePlotAreaManager; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; +import com.google.common.base.Charsets; + +import java.io.File; +import java.util.UUID; + +@CommandDeclaration(command = "debugimportworlds", permission = "plots.admin", description = "Import worlds by player name", requiredType = RequiredType.CONSOLE, category = CommandCategory.TELEPORT) +public class DebugImportWorlds extends Command { + public DebugImportWorlds() { + super(MainCommand.getInstance(), true); + } + + @Override public void execute(PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) throws CommandException { + // UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)) + PlotAreaManager pam = PlotSquared.get().getPlotAreaManager(); + if (!(pam instanceof SinglePlotAreaManager)) { + player.sendMessage("Must be a single plot area!"); + return; + } + SinglePlotArea area = ((SinglePlotAreaManager) pam).getArea(); + PlotId id = new PlotId(0, 0); + File container = PlotSquared.imp().getWorldContainer(); + for (File folder : container.listFiles()) { + String name = folder.getName(); + if (!WorldUtil.IMP.isWorld(name) && PlotId.fromString(name) == null) { + UUID uuid = UUIDHandler.getUUID(name, null); + if (uuid == null) { + uuid = + UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); + } + while (new File(container, id.toCommaSeparatedString()).exists()) { + id = Auto.getNextPlotId(id, 1); + } + File newDir = new File(container, id.toCommaSeparatedString()); + if (folder.renameTo(newDir)) { + area.getPlot(id).setOwner(uuid); + } + } + } + player.sendMessage("Done!"); + } +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugLoadTest.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugLoadTest.java new file mode 100644 index 000000000..bbc972438 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugLoadTest.java @@ -0,0 +1,15 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; + +@CommandDeclaration(command = "debugloadtest", permission = "plots.debugloadtest", description = "This debug command will force the reload of all plots in the DB", usage = "/plot debugloadtest", category = CommandCategory.DEBUG, requiredType = RequiredType.CONSOLE) +public class DebugLoadTest extends SubCommand { + + @Override public boolean onCommand(PlotPlayer player, String[] args) { + PlotSquared.get().plots_tmp = DBFunc.getPlots(); + return true; + } +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugPaste.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugPaste.java new file mode 100644 index 000000000..1e29809ff --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugPaste.java @@ -0,0 +1,87 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.HastebinUtility; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; + +import java.io.File; +import java.io.IOException; + +@CommandDeclaration(command = "debugpaste", aliases = "dp", usage = "/plot debugpaste", description = "Upload settings.yml, worlds.yml, commands.yml and latest.log to www.hastebin.com", permission = "plots.debugpaste", category = CommandCategory.DEBUG) +public class DebugPaste extends SubCommand { + + @Override public boolean onCommand(final PlotPlayer player, String[] args) { + TaskManager.runTaskAsync(new Runnable() { + @Override public void run() { + try { + String settingsYML = HastebinUtility.upload(PlotSquared.get().configFile); + String worldsYML = HastebinUtility.upload(PlotSquared.get().worldsFile); + String commandsYML = HastebinUtility.upload(PlotSquared.get().commandsFile); + String latestLOG; + try { + latestLOG = HastebinUtility.upload( + new File(PlotSquared.get().IMP.getDirectory(), + "../../logs/latest.log")); + } catch (IOException ignored) { + MainUtil.sendMessage(player, + "&clatest.log is too big to be pasted, will ignore"); + latestLOG = "too big :("; + } + StringBuilder b = new StringBuilder(); + b.append( + "# Welcome to this paste\n# It is meant to provide us at IntellectualSites with better information about your " + + "problem\n\n# We will start with some informational files\n"); + b.append("links.settings_yml: ").append(settingsYML).append('\n'); + b.append("links.worlds_yml: ").append(worldsYML).append('\n'); + b.append("links.commands_yml: ").append(commandsYML).append('\n'); + b.append("links.latest_log: ").append(latestLOG).append('\n'); + b.append("\n# Server Information\n"); + int[] sVersion = PlotSquared.get().IMP.getServerVersion(); + b.append("version.server: ").append(sVersion[0]).append('.').append(sVersion[1]) + .append('.').append(sVersion[2]).append('\n'); + b.append("online_mode: ").append(UUIDHandler.getUUIDWrapper()).append(';') + .append(!Settings.UUID.OFFLINE).append('\n'); + b.append("plugins:"); + for (String id : PlotSquared.get().IMP.getPluginIds()) { + String[] split = id.split(":"); + String[] split2 = split[0].split(";"); + String enabled = split.length == 2 ? split[1] : "unknown"; + String name = split2[0]; + String version = split2.length == 2 ? split2[1] : "unknown"; + b.append("\n ").append(name).append(":\n ").append("version: '") + .append(version).append('\'').append("\n enabled: ").append(enabled); + } + b.append("\n\n# YAY! Now, let's see what we can find in your JVM\n"); + Runtime runtime = Runtime.getRuntime(); + b.append("memory.free: ").append(runtime.freeMemory()).append('\n'); + b.append("memory.max: ").append(runtime.maxMemory()).append('\n'); + b.append("java.specification.version: '") + .append(System.getProperty("java.specification.version")).append("'\n"); + b.append("java.vendor: '").append(System.getProperty("java.vendor")) + .append("'\n"); + b.append("java.version: '").append(System.getProperty("java.version")) + .append("'\n"); + b.append("os.arch: '").append(System.getProperty("os.arch")).append("'\n"); + b.append("os.name: '").append(System.getProperty("os.name")).append("'\n"); + b.append("os.version: '").append(System.getProperty("os.version")) + .append("'\n\n"); + b.append("# Okay :D Great. You are now ready to create your bug report!"); + b.append( + "\n# You can do so at https://github.com/IntellectualSites/PlotSquared/issues"); + + String link = HastebinUtility.upload(b.toString()); + player.sendMessage(C.DEBUG_REPORT_CREATED.s().replace("%url%", link)); + } catch (IOException e) { + e.printStackTrace(); + } + } + }); + return true; + } +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugRoadRegen.java similarity index 54% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugRoadRegen.java index 914eab1d3..7b070e20f 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/DebugRoadRegen.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugRoadRegen.java @@ -1,29 +1,18 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.generator.HybridPlotManager; -import com.intellectualcrafters.plot.generator.HybridPlotWorld; -import com.intellectualcrafters.plot.generator.HybridUtils; -import com.intellectualcrafters.plot.object.ChunkLoc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotManager; +import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld; +import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; -@CommandDeclaration( - command = "debugroadregen", - usage = "/plot debugroadregen", - requiredType = RequiredType.NONE, - description = "Regenerate all roads based on the road schematic", - category = CommandCategory.DEBUG, - permission = "plots.debugroadregen") +@CommandDeclaration(command = "debugroadregen", usage = "/plot debugroadregen", requiredType = RequiredType.NONE, description = "Regenerate all roads based on the road schematic", category = CommandCategory.DEBUG, permission = "plots.debugroadregen") public class DebugRoadRegen extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { Location loc = player.getLocation(); PlotArea plotArea = loc.getPlotArea(); if (!(plotArea instanceof HybridPlotWorld)) { @@ -45,14 +34,17 @@ public class DebugRoadRegen extends SubCommand { } boolean result = HybridUtils.manager.regenerateRoad(plotArea, chunk, extend); MainUtil.sendMessage(player, - "&6Regenerating chunk: " + chunk.x + ',' + chunk.z + "\n&6 - Result: " + (result ? "&aSuccess" : "&cFailed")); + "&6Regenerating chunk: " + chunk.x + ',' + chunk.z + "\n&6 - Result: " + (result ? + "&aSuccess" : + "&cFailed")); MainUtil.sendMessage(player, "&cTo regenerate all roads: /plot regenallroads"); } else { HybridPlotManager manager = (HybridPlotManager) plotArea.getPlotManager(); manager.createRoadEast(plotArea, plot); manager.createRoadSouth(plotArea, plot); manager.createRoadSouthEast(plotArea, plot); - MainUtil.sendMessage(player, "&6Regenerating plot south/east roads: " + plot.getId() + "\n&6 - Result: &aSuccess"); + MainUtil.sendMessage(player, "&6Regenerating plot south/east roads: " + plot.getId() + + "\n&6 - Result: &aSuccess"); MainUtil.sendMessage(player, "&cTo regenerate all roads: /plot regenallroads"); } return true; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugSaveTest.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugSaveTest.java new file mode 100644 index 000000000..f90a5b1d6 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugSaveTest.java @@ -0,0 +1,26 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; + +import java.util.ArrayList; + +@CommandDeclaration(command = "debugsavetest", permission = "plots.debugsavetest", category = CommandCategory.DEBUG, requiredType = RequiredType.CONSOLE, usage = "/plot debugsavetest", description = "This command will force the recreation of all plots in the DB") +public class DebugSaveTest extends SubCommand { + + @Override public boolean onCommand(final PlotPlayer player, String[] args) { + ArrayList plots = new ArrayList(); + plots.addAll(PlotSquared.get().getPlots()); + MainUtil.sendMessage(player, "&6Starting `DEBUGSAVETEST`"); + DBFunc.createPlotsAndData(plots, new Runnable() { + @Override public void run() { + MainUtil.sendMessage(player, "&6Database sync finished!"); + } + }); + return true; + } +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Delete.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Delete.java similarity index 57% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Delete.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Delete.java index b84b50a1d..39637e83b 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Delete.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Delete.java @@ -1,35 +1,21 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.object.Expression; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.CmdConfirm; -import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.TaskManager; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.*; -@CommandDeclaration( - command = "delete", - permission = "plots.delete", - description = "Delete the plot you stand on", - usage = "/plot delete", - aliases = {"dispose", "del"}, - category = CommandCategory.CLAIMING, - requiredType = RequiredType.NONE, - confirmation = true) + +@CommandDeclaration(command = "delete", permission = "plots.delete", description = "Delete the plot you stand on", usage = "/plot delete", aliases = { + "dispose", + "del"}, category = CommandCategory.CLAIMING, requiredType = RequiredType.NONE, confirmation = true) public class Delete extends SubCommand { // Note: To delete a specific plot use /plot delete // The syntax also works with any command: /plot - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { Location loc = player.getLocation(); final Plot plot = loc.getPlotAbs(); @@ -39,23 +25,23 @@ public class Delete extends SubCommand { if (!plot.hasOwner()) { return !sendMessage(player, C.PLOT_UNOWNED); } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DELETE)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DELETE)) { return !sendMessage(player, C.NO_PLOT_PERMS); } final PlotArea plotArea = plot.getArea(); final java.util.Set plots = plot.getConnectedPlots(); - final int currentPlots = Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(loc.getWorld()); + final int currentPlots = + Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(loc.getWorld()); Runnable run = new Runnable() { - @Override - public void run() { + @Override public void run() { if (plot.getRunning() > 0) { MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); return; } final long start = System.currentTimeMillis(); boolean result = plot.deletePlot(new Runnable() { - @Override - public void run() { + @Override public void run() { plot.removeRunning(); if ((EconHandler.manager != null) && plotArea.USE_ECONOMY) { Expression valueExr = plotArea.PRICES.get("sell"); @@ -65,7 +51,8 @@ public class Delete extends SubCommand { sendMessage(player, C.ADDED_BALANCE, String.valueOf(value)); } } - MainUtil.sendMessage(player, C.DELETING_DONE, System.currentTimeMillis() - start); + MainUtil.sendMessage(player, C.DELETING_DONE, + System.currentTimeMillis() - start); } }); if (result) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Deny.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Deny.java similarity index 64% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Deny.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Deny.java index 4a88676dd..723a47cfb 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Deny.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Deny.java @@ -1,38 +1,28 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.PlotGameMode; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.WorldUtil; -import com.plotsquared.general.commands.Argument; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.Argument; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.*; import java.util.Iterator; import java.util.Set; import java.util.UUID; -@CommandDeclaration(command = "deny", - aliases = {"d", "ban"}, - description = "Deny a user from a plot", - usage = "/plot deny ", - category = CommandCategory.SETTINGS, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "deny", aliases = {"d", + "ban"}, description = "Deny a user from a plot", usage = "/plot deny ", category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE) public class Deny extends SubCommand { public Deny() { super(Argument.PlayerName); } - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { Location location = player.getLocation(); Plot plot = location.getPlotAbs(); @@ -43,7 +33,8 @@ public class Deny extends SubCommand { MainUtil.sendMessage(player, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DENY)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DENY)) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return true; } @@ -55,7 +46,9 @@ public class Deny extends SubCommand { Iterator iter = uuids.iterator(); while (iter.hasNext()) { UUID uuid = iter.next(); - if (uuid == DBFunc.everyone && !(Permissions.hasPermission(player, C.PERMISSION_DENY_EVERYONE) || Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DENY))) { + if (uuid == DBFunc.EVERYONE && !( + Permissions.hasPermission(player, C.PERMISSION_DENY_EVERYONE) || Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DENY))) { MainUtil.sendMessage(player, C.INVALID_PLAYER, MainUtil.getName(uuid)); continue; } @@ -68,13 +61,13 @@ public class Deny extends SubCommand { MainUtil.sendMessage(player, C.ALREADY_ADDED, MainUtil.getName(uuid)); return false; } - if (uuid != DBFunc.everyone) { + if (uuid != DBFunc.EVERYONE) { plot.removeMember(uuid); plot.removeTrusted(uuid); } plot.addDenied(uuid); EventUtil.manager.callDenied(player, plot, uuid, true); - if (!uuid.equals(DBFunc.everyone)) { + if (!uuid.equals(DBFunc.EVERYONE)) { handleKick(UUIDHandler.getPlayer(uuid), plot); } else { for (PlotPlayer plotPlayer : plot.getPlayersInPlot()) { @@ -105,7 +98,8 @@ public class Deny extends SubCommand { Location spawn = WorldUtil.IMP.getSpawn(loc.getWorld()); MainUtil.sendMessage(player, C.YOU_GOT_DENIED); if (plot.equals(spawn.getPlot())) { - Location newSpawn = WorldUtil.IMP.getSpawn(PS.get().getPlotAreaManager().getAllWorlds()[0]); + Location newSpawn = + WorldUtil.IMP.getSpawn(PlotSquared.get().getPlotAreaManager().getAllWorlds()[0]); if (plot.equals(newSpawn.getPlot())) { // Kick from server if you can't be teleported to spawn player.kick(C.YOU_GOT_DENIED.s()); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Desc.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Desc.java new file mode 100644 index 000000000..83d0636bf --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Desc.java @@ -0,0 +1,30 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.flag.FlagManager; +import com.github.intellectualsites.plotsquared.plot.flag.Flags; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; + +@CommandDeclaration(command = "setdescription", permission = "plots.set.desc", description = "Set the plot description", usage = "/plot desc ", aliases = { + "desc", "setdesc", "setd", + "description"}, category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE) +public class Desc extends SetCommand { + + @Override public boolean set(PlotPlayer player, Plot plot, String desc) { + if (desc.isEmpty()) { + plot.removeFlag(Flags.DESCRIPTION); + MainUtil.sendMessage(player, C.DESC_UNSET); + return true; + } + boolean result = FlagManager.addPlotFlag(plot, Flags.DESCRIPTION, desc); + if (!result) { + MainUtil.sendMessage(player, C.FLAG_NOT_ADDED); + return false; + } + MainUtil.sendMessage(player, C.DESC_SET); + return true; + } +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Done.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Done.java new file mode 100644 index 000000000..f3661be2d --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Done.java @@ -0,0 +1,68 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.flag.Flags; +import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; +import com.github.intellectualsites.plotsquared.plot.util.expiry.PlotAnalysis; + +@CommandDeclaration(command = "done", aliases = { + "submit"}, description = "Mark a plot as done", permission = "plots.done", category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE) +public class Done extends SubCommand { + + @Override public boolean onCommand(final PlotPlayer player, String[] args) { + Location loc = player.getLocation(); + final Plot plot = loc.getPlotAbs(); + if ((plot == null) || !plot.hasOwner()) { + return !sendMessage(player, C.NOT_IN_PLOT); + } + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DONE)) { + MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + return false; + } + if (plot.hasFlag(Flags.DONE)) { + MainUtil.sendMessage(player, C.DONE_ALREADY_DONE); + return false; + } + if (plot.getRunning() > 0) { + MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); + return false; + } + plot.addRunning(); + MainUtil.sendMessage(player, C.GENERATING_LINK); + final Settings.Auto_Clear doneRequirements = Settings.AUTO_CLEAR.get("done"); + if (ExpireManager.IMP == null || doneRequirements == null) { + finish(plot, player, true); + plot.removeRunning(); + } else { + HybridUtils.manager.analyzePlot(plot, new RunnableVal() { + @Override public void run(PlotAnalysis value) { + plot.removeRunning(); + boolean result = + value.getComplexity(doneRequirements) <= doneRequirements.THRESHOLD; + finish(plot, player, result); + } + }); + } + return true; + } + + private void finish(Plot plot, PlotPlayer pp, boolean success) { + if (success) { + long flagValue = System.currentTimeMillis() / 1000; + plot.setFlag(Flags.DONE, flagValue); + MainUtil.sendMessage(pp, C.DONE_SUCCESS); + } else { + MainUtil.sendMessage(pp, C.DONE_INSUFFICIENT_COMPLEXITY); + } + } +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Download.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Download.java new file mode 100644 index 000000000..11e338720 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Download.java @@ -0,0 +1,94 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.flag.Flags; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.util.*; +import com.sk89q.jnbt.CompoundTag; + +import java.net.URL; + +@CommandDeclaration(usage = "/plot download [schematic|bo3|world]", command = "download", aliases = { + "dl"}, category = CommandCategory.SCHEMATIC, requiredType = RequiredType.NONE, description = "Download your plot", permission = "plots.download") +public class Download extends SubCommand { + + @Override public boolean onCommand(final PlotPlayer player, String[] args) { + String world = player.getLocation().getWorld(); + if (!PlotSquared.get().hasPlotArea(world)) { + return !sendMessage(player, C.NOT_IN_PLOT_WORLD); + } + final Plot plot = player.getCurrentPlot(); + if (plot == null) { + return !sendMessage(player, C.NOT_IN_PLOT); + } + if (!plot.hasOwner()) { + MainUtil.sendMessage(player, C.PLOT_UNOWNED); + return false; + } + if ((Settings.Done.REQUIRED_FOR_DOWNLOAD && (!plot.getFlag(Flags.DONE).isPresent())) + && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DOWNLOAD)) { + MainUtil.sendMessage(player, C.DONE_NOT_DONE); + return false; + } + if ((!plot.isOwner(player.getUUID())) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN.s())) { + MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + return false; + } + if (plot.getRunning() > 0) { + MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); + return false; + } + if (args.length == 0 || (args.length == 1 && StringMan + .isEqualIgnoreCaseToAny(args[0], "sch", "schem", "schematic"))) { + if (plot.getVolume() > Integer.MAX_VALUE) { + C.SCHEMATIC_TOO_LARGE.send(player); + return false; + } + plot.addRunning(); + SchematicHandler.manager.getCompoundTag(plot, new RunnableVal() { + @Override public void run(CompoundTag value) { + plot.removeRunning(); + SchematicHandler.manager.upload(value, null, null, new RunnableVal() { + @Override public void run(URL url) { + if (url == null) { + MainUtil.sendMessage(player, C.GENERATING_LINK_FAILED); + return; + } + MainUtil.sendMessage(player, url.toString()); + } + }); + } + }); + } else if (args.length == 1 && StringMan + .isEqualIgnoreCaseToAny(args[0], "mcr", "world", "mca")) { + if (!Permissions.hasPermission(player, C.PERMISSION_DOWNLOAD_WORLD)) { + C.NO_PERMISSION.send(player, C.PERMISSION_DOWNLOAD_WORLD); + return false; + } + MainUtil.sendMessage(player, "&cNote: The `.mca` files are 512x512"); + plot.addRunning(); + WorldUtil.IMP.saveWorld(world); + WorldUtil.IMP.upload(plot, null, null, new RunnableVal() { + @Override public void run(URL url) { + plot.removeRunning(); + if (url == null) { + MainUtil.sendMessage(player, C.GENERATING_LINK_FAILED); + return; + } + MainUtil.sendMessage(player, url.toString()); + } + }); + } else { + C.COMMAND_SYNTAX.send(player, getUsage()); + return false; + } + MainUtil.sendMessage(player, C.GENERATING_LINK); + return true; + } +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/FlagCmd.java similarity index 78% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/FlagCmd.java index 7afd81474..35ccf7a4e 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/FlagCmd.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/FlagCmd.java @@ -1,27 +1,21 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.flag.*; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.*; import com.google.common.base.Optional; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.flag.*; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.*; -import com.plotsquared.general.commands.CommandDeclaration; import java.util.*; -@CommandDeclaration( - command = "setflag", - aliases = {"f", "flag", "setf", "setflag"}, - usage = "/plot flag ", - description = "Set plot flags", - category = CommandCategory.SETTINGS, - requiredType = RequiredType.NONE, - permission = "plots.flag") +@CommandDeclaration(command = "setflag", aliases = {"f", "flag", "setf", + "setflag"}, usage = "/plot flag ", description = "Set plot flags", category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE, permission = "plots.flag") public class FlagCmd extends SubCommand { private boolean checkPermValue(PlotPlayer player, Flag flag, String key, String value) { @@ -33,17 +27,19 @@ public class FlagCmd extends SubCommand { int numeric = Integer.parseInt(value); perm = perm.substring(0, perm.length() - value.length() - 1); if (numeric > 0) { - int checkRange = PS.get().getPlatform().equalsIgnoreCase("bukkit") ? numeric : Settings.Limit.MAX_PLOTS; + int checkRange = PlotSquared.get().getPlatform().equalsIgnoreCase("bukkit") ? + numeric : + Settings.Limit.MAX_PLOTS; return player.hasPermissionRange(perm, checkRange) >= numeric; } - } catch (NumberFormatException ignore) {} + } catch (NumberFormatException ignore) { + } } return Permissions.hasPermission(player, perm); } - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { /* * plot flag set fly true @@ -66,7 +62,8 @@ public class FlagCmd extends SubCommand { sendMessage(player, C.PLOT_NOT_CLAIMED); return false; } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_SET_FLAG_OTHER)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_SET_FLAG_OTHER)) { MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG_OTHER); return false; } @@ -76,7 +73,8 @@ public class FlagCmd extends SubCommand { if (flag == null || flag.isReserved()) { boolean suggested = false; try { - StringComparison> stringComparison = new StringComparison<>(args[1], Flags.getFlags()); + StringComparison> stringComparison = + new StringComparison<>(args[1], Flags.getFlags()); String best = stringComparison.getBestMatch(); if (best != null) { MainUtil.sendMessage(player, C.NOT_VALID_FLAG_SUGGESTED, best); @@ -118,7 +116,8 @@ public class FlagCmd extends SubCommand { } String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " "); if (!checkPermValue(player, flag, args[1], value)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG_KEY_VALUE.f(args[1].toLowerCase(), value.toLowerCase())); + MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG_KEY_VALUE + .f(args[1].toLowerCase(), value.toLowerCase())); return false; } Object parsed = flag.parseValue(value); @@ -140,24 +139,29 @@ public class FlagCmd extends SubCommand { return false; } if (args.length != 2 && args.length != 3) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag remove [values]"); + MainUtil + .sendMessage(player, C.COMMAND_SYNTAX, "/plot flag remove [values]"); return false; } - if (!Permissions.hasPermission(player, C.PERMISSION_SET_FLAG_KEY.f(args[1].toLowerCase()))) { + if (!Permissions + .hasPermission(player, C.PERMISSION_SET_FLAG_KEY.f(args[1].toLowerCase()))) { if (args.length != 3) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG_KEY.f(args[1].toLowerCase())); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_SET_FLAG_KEY.f(args[1].toLowerCase())); return false; } for (String entry : args[2].split(",")) { if (!checkPermValue(player, flag, args[1], entry)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG_KEY_VALUE.f(args[1].toLowerCase(), entry)); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_SET_FLAG_KEY_VALUE.f(args[1].toLowerCase(), entry)); return false; } } } if (args.length == 3 && flag instanceof ListFlag) { String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " "); - Optional flag1 = plot.getFlag((Flag>) flag); + Optional flag1 = + plot.getFlag((Flag>) flag); if (flag1.isPresent()) { boolean o = flag1.get().removeAll((Collection) flag.parseValue(value)); if (o) { @@ -176,9 +180,9 @@ public class FlagCmd extends SubCommand { return false; } } - if(flag == Flags.TIME) { + if (flag == Flags.TIME) { player.setTime(Long.MAX_VALUE); - } else if(flag == Flags.WEATHER) { + } else if (flag == Flags.WEATHER) { player.setWeather(PlotWeather.RESET); } MainUtil.sendMessage(player, C.FLAG_REMOVED); @@ -190,12 +194,14 @@ public class FlagCmd extends SubCommand { return false; } if (args.length < 3) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag add "); + MainUtil + .sendMessage(player, C.COMMAND_SYNTAX, "/plot flag add "); return false; } for (String entry : args[2].split(",")) { if (!checkPermValue(player, flag, args[1], entry)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG_KEY_VALUE.f(args[1].toLowerCase(), entry)); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_SET_FLAG_KEY_VALUE.f(args[1].toLowerCase(), entry)); return false; } } @@ -207,7 +213,8 @@ public class FlagCmd extends SubCommand { } Object val = parsed; if (flag instanceof ListFlag) { - Optional flag1 = plot.getFlag((Flag>) flag); + Optional flag1 = + plot.getFlag((Flag>) flag); if (flag1.isPresent()) { boolean o = flag1.get().addAll((Collection) parsed); if (o) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/GenerateDocs.java similarity index 87% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/GenerateDocs.java index 468e63252..5a69479b5 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/GenerateDocs.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/GenerateDocs.java @@ -1,8 +1,8 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.util.StringMan; -import com.plotsquared.general.commands.Command; +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; import java.io.File; import java.io.IOException; @@ -22,16 +22,17 @@ public class GenerateDocs { List commands = MainCommand.getInstance().getCommands(); GenerateDocs.log("### Want to document some commands?"); GenerateDocs.log(" - This page is automatically generated"); - GenerateDocs.log(" - Fork the project and add a javadoc comment to one of the command classes"); + GenerateDocs + .log(" - Fork the project and add a javadoc comment to one of the command classes"); GenerateDocs.log(" - Then do a pull request and it will be added to this page"); GenerateDocs.log(""); GenerateDocs.log("# Contents"); for (CommandCategory category : CommandCategory.values()) { GenerateDocs.log("###### " + category.name()); for (Command command : MainCommand.getInstance().getCommands(category, null)) { - GenerateDocs - .log(" - [/plot " + command.getId() + "](https://github.com/IntellectualSites/PlotSquared/wiki/Commands#" + command.getId() - + ") "); + GenerateDocs.log(" - [/plot " + command.getId() + + "](https://github.com/IntellectualSites/PlotSquared/wiki/Commands#" + command + .getId() + ") "); } GenerateDocs.log(""); } @@ -48,11 +49,12 @@ public class GenerateDocs { // Header String source = - "https://github.com/IntellectualSites/PlotSquared/tree/master/Core/src/main/java/com/intellectualcrafters/plot/commands/" + clazz - + ".java"; + "https://github.com/IntellectualSites/PlotSquared/tree/master/Core/src/main/java/com/intellectualcrafters/plot/commands/" + + clazz + ".java"; GenerateDocs.log("## [" + name.toUpperCase() + "](" + source + ") "); - File file = new File("Core/src/main/java/com/intellectualcrafters/plot/commands/" + clazz + ".java"); + File file = new File( + "Core/src/main/java/com/intellectualcrafters/plot/commands/" + clazz + ".java"); List lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); List perms = GenerateDocs.getPerms(name, lines); List usages = GenerateDocs.getUsage(name, lines); @@ -123,7 +125,8 @@ public class GenerateDocs { prefix = " "; } if (usage.length() != 0) { - usages.add(usage.toString().trim().replaceAll(" ", " ").replaceAll("\\{label\\}", "plot")); + usages.add(usage.toString().trim().replaceAll(" ", " ") + .replaceAll("\\{label\\}", "plot")); } } } @@ -203,7 +206,9 @@ public class GenerateDocs { for (String line : lines) { line = line.trim(); if (line.startsWith("/** ") || line.startsWith("*/ ") || line.startsWith("* ")) { - line = line.replaceAll("/[*][*] ", "").replaceAll("[*]/ ", "").replaceAll("[*] ", "").trim(); + line = + line.replaceAll("/[*][*] ", "").replaceAll("[*]/ ", "").replaceAll("[*] ", "") + .trim(); result.append(line + '\n'); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Grant.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Grant.java new file mode 100644 index 000000000..81c7f3039 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Grant.java @@ -0,0 +1,70 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; +import com.github.intellectualsites.plotsquared.plot.util.ByteArrayUtilities; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; + +import java.util.UUID; + +@CommandDeclaration(command = "grant", category = CommandCategory.CLAIMING, usage = "/plot grant [player]", permission = "plots.grant", requiredType = RequiredType.NONE) +public class Grant extends Command { + + public Grant() { + super(MainCommand.getInstance(), true); + } + + @Override public void execute(final PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) throws CommandException { + checkTrue(args.length >= 1 && args.length <= 2, C.COMMAND_SYNTAX, getUsage()); + final String arg0 = args[0].toLowerCase(); + switch (arg0) { + case "add": + case "check": + if (!Permissions.hasPermission(player, C.PERMISSION_GRANT.f(arg0))) { + C.NO_PERMISSION.send(player, C.PERMISSION_GRANT.f(arg0)); + return; + } + if (args.length > 2) { + break; + } + final UUID uuid = + args.length == 2 ? UUIDHandler.getUUIDFromString(args[1]) : player.getUUID(); + if (uuid == null) { + C.INVALID_PLAYER.send(player, args[1]); + return; + } + MainUtil.getPersistentMeta(uuid, "grantedPlots", new RunnableVal() { + @Override public void run(byte[] array) { + if (arg0.equals("check")) { // check + int granted = + array == null ? 0 : ByteArrayUtilities.bytesToInteger(array); + C.GRANTED_PLOTS.send(player, granted); + } else { // add + int amount = + 1 + (array == null ? 0 : ByteArrayUtilities.bytesToInteger(array)); + boolean replace = array != null; + String key = "grantedPlots"; + byte[] rawData = ByteArrayUtilities.integerToBytes(amount); + PlotPlayer online = UUIDHandler.getPlayer(uuid); + if (online != null) { + online.setPersistentMeta(key, rawData); + } else { + DBFunc.addPersistentMeta(uuid, key, rawData, replace); + } + } + } + }); + } + C.COMMAND_SYNTAX.send(player, getUsage()); + } +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Help.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Help.java similarity index 59% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Help.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Help.java index de77178d7..36053b9f1 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Help.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Help.java @@ -1,34 +1,30 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal2; -import com.intellectualcrafters.plot.object.RunnableVal3; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.helpmenu.HelpMenu; -import com.plotsquared.general.commands.Command; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.helpmenu.HelpMenu; -@CommandDeclaration(command = "help", - description = "Get this help menu", - aliases = {"he", "?"}, - category = CommandCategory.INFO, - usage="help [category|#]", - permission="plots.use") +@CommandDeclaration(command = "help", description = "Get this help menu", aliases = {"he", + "?"}, category = CommandCategory.INFO, usage = "help [category|#]", permission = "plots.use") public class Help extends Command { public Help(Command parent) { super(parent, true); } - @Override - public boolean canExecute(PlotPlayer player, boolean message) { + @Override public boolean canExecute(PlotPlayer player, boolean message) { return true; } - @Override - public void execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { + @Override public void execute(PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) { switch (args.length) { case 0: displayHelp(player, null, 0); @@ -80,15 +76,18 @@ public class Help extends Command { StringBuilder builder = new StringBuilder(); builder.append(C.HELP_HEADER.s()); for (CommandCategory c : CommandCategory.values()) { - builder.append( - "\n" + StringMan.replaceAll(C.HELP_INFO_ITEM.s(), "%category%", c.toString().toLowerCase(), "%category_desc%", c.toString())); + builder.append("\n" + StringMan + .replaceAll(C.HELP_INFO_ITEM.s(), "%category%", c.toString().toLowerCase(), + "%category_desc%", c.toString())); } - builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", "all").replaceAll("%category_desc%", "Display all commands")); + builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", "all") + .replaceAll("%category_desc%", "Display all commands")); builder.append("\n" + C.HELP_FOOTER.s()); MainUtil.sendMessage(player, builder.toString(), false); return; } page--; - new HelpMenu(player).setCategory(catEnum).getCommands().generateMaxPages().generatePage(page, getParent().toString()).render(); + new HelpMenu(player).setCategory(catEnum).getCommands().generateMaxPages() + .generatePage(page, getParent().toString()).render(); } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Inbox.java similarity index 69% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Inbox.java index a23cb965c..eedc8945b 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Inbox.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Inbox.java @@ -1,27 +1,21 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.object.comment.CommentInbox; +import com.github.intellectualsites.plotsquared.plot.object.comment.PlotComment; +import com.github.intellectualsites.plotsquared.plot.util.CommentManager; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; import com.google.common.base.Optional; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.object.comment.CommentInbox; -import com.intellectualcrafters.plot.object.comment.PlotComment; -import com.intellectualcrafters.plot.util.CommentManager; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.StringMan; -import com.plotsquared.general.commands.CommandDeclaration; import java.util.ArrayList; import java.util.List; -@CommandDeclaration( - command = "inbox", - description = "Review the comments for a plot", - usage = "/plot inbox [inbox] [delete |clear|page]", - permission = "plots.inbox", - category = CommandCategory.CHAT, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "inbox", description = "Review the comments for a plot", usage = "/plot inbox [inbox] [delete |clear|page]", permission = "plots.inbox", category = CommandCategory.CHAT, requiredType = RequiredType.NONE) public class Inbox extends SubCommand { public void displayComments(PlotPlayer player, List oldComments, int page) { @@ -46,8 +40,8 @@ public class Inbox extends SubCommand { } StringBuilder string = new StringBuilder(); string.append(StringMan - .replaceAll(C.COMMENT_LIST_HEADER_PAGED.s(), "%amount%", comments.length, "%cur", page + 1, "%max", totalPages + 1, "%word", "all") - + '\n'); + .replaceAll(C.COMMENT_LIST_HEADER_PAGED.s(), "%amount%", comments.length, "%cur", + page + 1, "%max", totalPages + 1, "%word", "all") + '\n'); // This might work xD for (int x = page * 12; x < max; x++) { @@ -58,14 +52,14 @@ public class Inbox extends SubCommand { } else { color = "&7"; } - string.append("&8[&7#").append(x + 1).append("&8][&7").append(comment.world).append(';').append(comment.id).append("&8][&6") - .append(comment.senderName).append("&8]").append(color).append(comment.comment).append('\n'); + string.append("&8[&7#").append(x + 1).append("&8][&7").append(comment.world).append(';') + .append(comment.id).append("&8][&6").append(comment.senderName).append("&8]") + .append(color).append(comment.comment).append('\n'); } MainUtil.sendMessage(player, string.toString()); } - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { final Plot plot = player.getCurrentPlot(); if (plot == null) { sendMessage(player, C.NOT_IN_PLOT); @@ -76,18 +70,19 @@ public class Inbox extends SubCommand { return false; } if (args.length == 0) { - sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox [inbox] [delete |clear|page]"); + sendMessage(player, C.COMMAND_SYNTAX, + "/plot inbox [inbox] [delete |clear|page]"); for (final CommentInbox inbox : CommentManager.inboxes.values()) { if (inbox.canRead(plot, player)) { if (!inbox.getComments(plot, new RunnableVal>() { - @Override - public void run(List value) { + @Override public void run(List value) { if (value != null) { int total = 0; int unread = 0; for (PlotComment comment : value) { total++; - if (comment.timestamp > CommentManager.getTimestamp(player, inbox.toString())) { + if (comment.timestamp > CommentManager + .getTimestamp(player, inbox.toString())) { unread++; } } @@ -98,7 +93,9 @@ public class Inbox extends SubCommand { } else { color = ""; } - sendMessage(player, C.INBOX_ITEM, color + inbox.toString() + " (" + total + '/' + unread + ')'); + sendMessage(player, C.INBOX_ITEM, + color + inbox.toString() + " (" + total + '/' + unread + + ')'); return; } } @@ -113,7 +110,8 @@ public class Inbox extends SubCommand { } final CommentInbox inbox = CommentManager.inboxes.get(args[0].toLowerCase()); if (inbox == null) { - sendMessage(player, C.INVALID_INBOX, StringMan.join(CommentManager.inboxes.keySet(), ", ")); + sendMessage(player, C.INVALID_INBOX, + StringMan.join(CommentManager.inboxes.keySet(), ", ")); return false; } player.setMeta("inbox:" + inbox.toString(), System.currentTimeMillis()); @@ -126,7 +124,8 @@ public class Inbox extends SubCommand { return false; } if (args.length != 3) { - sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox " + inbox.toString() + " delete "); + sendMessage(player, C.COMMAND_SYNTAX, + "/plot inbox " + inbox.toString() + " delete "); } final int index; try { @@ -136,13 +135,13 @@ public class Inbox extends SubCommand { return false; } } catch (NumberFormatException ignored) { - sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox " + inbox.toString() + " delete "); + sendMessage(player, C.COMMAND_SYNTAX, + "/plot inbox " + inbox.toString() + " delete "); return false; } if (!inbox.getComments(plot, new RunnableVal>() { - @Override - public void run(List value) { + @Override public void run(List value) { if (index > value.size()) { sendMessage(player, C.NOT_VALID_INBOX_INDEX, index + ""); return; @@ -162,7 +161,8 @@ public class Inbox extends SubCommand { sendMessage(player, C.NO_PERM_INBOX_MODIFY); } inbox.clearInbox(plot); - Optional> comments = plot.getSettings().getComments(inbox.toString()); + Optional> comments = + plot.getSettings().getComments(inbox.toString()); if (comments.isPresent()) { plot.getSettings().removeComments(comments.get()); } @@ -172,7 +172,8 @@ public class Inbox extends SubCommand { try { page = Integer.parseInt(args[1]); } catch (NumberFormatException ignored) { - sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox [inbox] [delete |clear|page]"); + sendMessage(player, C.COMMAND_SYNTAX, + "/plot inbox [inbox] [delete |clear|page]"); return false; } } @@ -184,8 +185,7 @@ public class Inbox extends SubCommand { return false; } if (!inbox.getComments(plot, new RunnableVal>() { - @Override - public void run(List value) { + @Override public void run(List value) { displayComments(player, value, page); } })) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Info.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Info.java similarity index 61% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Info.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Info.java index 2ab3ecbe1..c8971c71c 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Info.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Info.java @@ -1,27 +1,18 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotInventory; -import com.intellectualcrafters.plot.object.PlotItemStack; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.expiry.ExpireManager; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; import java.util.UUID; -@CommandDeclaration(command = "info", - aliases = "i", - description = "Display plot info", - usage = "/plot info ", - category = CommandCategory.INFO) +@CommandDeclaration(command = "info", aliases = "i", description = "Display plot info", usage = "/plot info ", category = CommandCategory.INFO) public class Info extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { Plot plot; String arg; if (args.length > 0) { @@ -65,13 +56,12 @@ public class Info extends SubCommand { if (args.length == 1) { args = new String[0]; } else { - args = new String[]{args[1]}; + args = new String[] {args[1]}; } } if (args.length == 1 && args[0].equalsIgnoreCase("inv")) { PlotInventory inv = new PlotInventory(player) { - @Override - public boolean onClick(int index) { + @Override public boolean onClick(int index) { // TODO InfoInventory not implemented yet!!!!!!!! // See plot rating or musicsubcommand on examples return false; @@ -79,31 +69,35 @@ public class Info extends SubCommand { }; UUID uuid = player.getUUID(); String name = MainUtil.getName(plot.owner); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cPlot Info", "&cID: &6" + plot.getId().toString(), - "&cOwner: &6" + name, - "&cAlias: &6" + plot.getAlias(), - "&cBiome: &6" + plot.getBiome().replaceAll("_", "").toLowerCase(), - "&cCan Build: &6" + plot.isAdded(uuid), - "&cSeen: &6" + MainUtil.secToTime((int) (ExpireManager.IMP.getAge(plot) / 1000)), - "&cIs Denied: &6" + plot.isDenied(uuid))); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cTrusted", "&cAmount: &6" + plot.getTrusted().size(), - "&8Click to view a list of the trusted users")); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cMembers", "&cAmount: &6" + plot.getMembers().size(), - "&8Click to view a list of plot members")); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cDenied", "&cDenied", "&cAmount: &6" + plot.getDenied().size(), - "&8Click to view a list of denied players")); - inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cFlags", "&cFlags", "&cAmount: &6" + plot.getFlags().size(), - "&8Click to view a list of plot flags")); + inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cPlot Info", + "&cID: &6" + plot.getId().toString(), "&cOwner: &6" + name, + "&cAlias: &6" + plot.getAlias(), + "&cBiome: &6" + plot.getBiome().replaceAll("_", "").toLowerCase(), + "&cCan Build: &6" + plot.isAdded(uuid), + "&cSeen: &6" + MainUtil.secToTime((int) (ExpireManager.IMP.getAge(plot) / 1000)), + "&cIs Denied: &6" + plot.isDenied(uuid))); + inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cTrusted", + "&cAmount: &6" + plot.getTrusted().size(), + "&8Click to view a list of the trusted users")); + inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cMembers", + "&cAmount: &6" + plot.getMembers().size(), + "&8Click to view a list of plot members")); + inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cDenied", "&cDenied", + "&cAmount: &6" + plot.getDenied().size(), + "&8Click to view a list of denied players")); + inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cFlags", "&cFlags", + "&cAmount: &6" + plot.getFlags().size(), "&8Click to view a list of plot flags")); inv.openInventory(); return true; } boolean hasOwner = plot.hasOwner(); // Wildcard player {added} - boolean containsEveryone = plot.getTrusted().contains(DBFunc.everyone); - boolean trustedEveryone = plot.getMembers().contains(DBFunc.everyone); + boolean containsEveryone = plot.getTrusted().contains(DBFunc.EVERYONE); + boolean trustedEveryone = plot.getMembers().contains(DBFunc.EVERYONE); // Unclaimed? if (!hasOwner && !containsEveryone && !trustedEveryone) { - MainUtil.sendMessage(player, C.PLOT_INFO_UNCLAIMED, plot.getId().x + ";" + plot.getId().y); + MainUtil + .sendMessage(player, C.PLOT_INFO_UNCLAIMED, plot.getId().x + ";" + plot.getId().y); return true; } String info = C.PLOT_INFO.s(); @@ -112,8 +106,8 @@ public class Info extends SubCommand { info = getCaption(arg); if (info == null) { MainUtil.sendMessage(player, - "&6Categories&7: &amembers&7, &aalias&7, &abiome&7, &aseen&7, &adenied&7, &aflags&7, &aid&7, &asize&7, &atrusted&7, " - + "&aowner&7, &arating"); + "&6Categories&7: &amembers&7, &aalias&7, &abiome&7, &aseen&7, &adenied&7, &aflags&7, &aid&7, &asize&7, &atrusted&7, " + + "&aowner&7, &arating"); return false; } full = true; @@ -121,9 +115,9 @@ public class Info extends SubCommand { full = false; } MainUtil.format(info, plot, player, full, new RunnableVal() { - @Override - public void run(String value) { - MainUtil.sendMessage(player, C.PLOT_INFO_HEADER.s() + '\n' + value + '\n' + C.PLOT_INFO_FOOTER.s(), false); + @Override public void run(String value) { + MainUtil.sendMessage(player, + C.PLOT_INFO_HEADER.s() + '\n' + value + '\n' + C.PLOT_INFO_FOOTER.s(), false); } }); return true; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Kick.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Kick.java similarity index 59% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Kick.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Kick.java index f637c83b7..f35423781 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Kick.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Kick.java @@ -1,43 +1,38 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.intellectualcrafters.plot.util.WorldUtil; -import com.plotsquared.general.commands.Argument; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.Argument; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; import java.util.HashSet; import java.util.Set; import java.util.UUID; -@CommandDeclaration(command = "kick", - aliases = {"k"}, - description = "Kick a player from your plot", - permission = "plots.kick", - usage = "/plot kick ", - category = CommandCategory.TELEPORT, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "kick", aliases = { + "k"}, description = "Kick a player from your plot", permission = "plots.kick", usage = "/plot kick ", category = CommandCategory.TELEPORT, requiredType = RequiredType.NONE) public class Kick extends SubCommand { public Kick() { super(Argument.PlayerName); } - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { Location location = player.getLocation(); Plot plot = location.getPlot(); if (plot == null) { return !sendMessage(player, C.NOT_IN_PLOT); } - if ((!plot.hasOwner() || !plot.isOwner(player.getUUID())) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_KICK)) { + if ((!plot.hasOwner() || !plot.isOwner(player.getUUID())) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_KICK)) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } @@ -48,9 +43,10 @@ public class Kick extends SubCommand { } Set players = new HashSet<>(); for (UUID uuid : uuids) { - if (uuid == DBFunc.everyone) { + if (uuid == DBFunc.EVERYONE) { for (PlotPlayer pp : plot.getPlayersInPlot()) { - if (pp == player || Permissions.hasPermission(pp, C.PERMISSION_ADMIN_ENTRY_DENIED)) { + if (pp == player || Permissions + .hasPermission(pp, C.PERMISSION_ADMIN_ENTRY_DENIED)) { continue; } players.add(pp); @@ -79,7 +75,8 @@ public class Kick extends SubCommand { Location spawn = WorldUtil.IMP.getSpawn(location.getWorld()); C.YOU_GOT_KICKED.send(player2); if (plot.equals(spawn.getPlot())) { - Location newSpawn = WorldUtil.IMP.getSpawn(PS.get().getPlotAreaManager().getAllWorlds()[0]); + Location newSpawn = WorldUtil.IMP + .getSpawn(PlotSquared.get().getPlotAreaManager().getAllWorlds()[0]); if (plot.equals(newSpawn.getPlot())) { // Kick from server if you can't be teleported to spawn player2.kick(C.YOU_GOT_KICKED.s()); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Leave.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Leave.java similarity index 50% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Leave.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Leave.java index 7df2372f7..ae4043af8 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Leave.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Leave.java @@ -1,28 +1,26 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; +import com.github.intellectualsites.plotsquared.plot.util.EventUtil; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal2; -import com.intellectualcrafters.plot.object.RunnableVal3; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.MainUtil; -import com.plotsquared.general.commands.Command; -import com.plotsquared.general.commands.CommandDeclaration; import java.util.UUID; -@CommandDeclaration(command = "leave", - description = "Leave a plot", - permission = "plots.leave", - category = CommandCategory.CLAIMING, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "leave", description = "Leave a plot", permission = "plots.leave", category = CommandCategory.CLAIMING, requiredType = RequiredType.NONE) public class Leave extends Command { public Leave() { super(MainCommand.getInstance(), true); } - @Override - public void execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { + @Override public void execute(PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) throws CommandException { final Plot plot = check(player.getCurrentPlot(), C.NOT_IN_PLOT); checkTrue(plot.hasOwner(), C.PLOT_UNOWNED); checkTrue(plot.isAdded(player.getUUID()), C.NO_PLOT_PERMS); @@ -45,4 +43,4 @@ public class Leave extends Command { } } } -} \ No newline at end of file +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/ListCmd.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/ListCmd.java similarity index 66% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/ListCmd.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/ListCmd.java index 1465476a9..29a1defb2 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/ListCmd.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/ListCmd.java @@ -1,47 +1,26 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.PlotSquared.SortType; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.flag.Flags; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; import com.google.common.base.Optional; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.PS.SortType; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotMessage; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.Rating; -import com.intellectualcrafters.plot.object.RunnableVal3; -import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.expiry.ExpireManager; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.StringComparison; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.plotsquared.general.commands.CommandDeclaration; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; +import java.util.*; import java.util.Map.Entry; -import java.util.UUID; -@CommandDeclaration( - command = "list", - aliases = {"l", "find", "search"}, - description = "List plots", - permission = "plots.list", - category = CommandCategory.INFO, - usage = "/plot list > [#]") +@CommandDeclaration(command = "list", aliases = {"l", "find", + "search"}, description = "List plots", permission = "plots.list", category = CommandCategory.INFO, usage = "/plot list > [#]") public class ListCmd extends SubCommand { private String[] getArgumentList(PlotPlayer player) { List args = new ArrayList<>(); - if (EconHandler.manager != null && Permissions.hasPermission(player, C.PERMISSION_LIST_FORSALE)) { + if (EconHandler.manager != null && Permissions + .hasPermission(player, C.PERMISSION_LIST_FORSALE)) { args.add("forsale"); } if (Permissions.hasPermission(player, C.PERMISSION_LIST_MINE)) { @@ -84,11 +63,11 @@ public class ListCmd extends SubCommand { } public void noArgs(PlotPlayer player) { - MainUtil.sendMessage(player, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + Arrays.toString(getArgumentList(player))); + MainUtil.sendMessage(player, + C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + Arrays.toString(getArgumentList(player))); } - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { if (args.length < 1) { noArgs(player); return false; @@ -119,7 +98,7 @@ public class ListCmd extends SubCommand { return false; } sort = false; - plots = PS.get().sortPlotsByTemp(PS.get().getBasePlots(player)); + plots = PlotSquared.get().sortPlotsByTemp(PlotSquared.get().getBasePlots(player)); break; case "shared": if (!Permissions.hasPermission(player, C.PERMISSION_LIST_SHARED)) { @@ -127,8 +106,9 @@ public class ListCmd extends SubCommand { return false; } plots = new ArrayList<>(); - for (Plot plot : PS.get().getPlots()) { - if (plot.getTrusted().contains(player.getUUID()) || plot.getMembers().contains(player.getUUID())) { + for (Plot plot : PlotSquared.get().getPlots()) { + if (plot.getTrusted().contains(player.getUUID()) || plot.getMembers() + .contains(player.getUUID())) { plots.add(plot); } } @@ -139,17 +119,20 @@ public class ListCmd extends SubCommand { return false; } if (!Permissions.hasPermission(player, C.PERMISSION_LIST_WORLD_NAME.f(world))) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_WORLD_NAME.f(world)); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_LIST_WORLD_NAME.f(world)); return false; } - plots = new ArrayList<>(PS.get().getPlots(world)); + plots = new ArrayList<>(PlotSquared.get().getPlots(world)); break; case "expired": if (!Permissions.hasPermission(player, C.PERMISSION_LIST_EXPIRED)) { MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_EXPIRED); return false; } - plots = ExpireManager.IMP == null ? new ArrayList() : new ArrayList<>(ExpireManager.IMP.getPendingExpired()); + plots = ExpireManager.IMP == null ? + new ArrayList() : + new ArrayList<>(ExpireManager.IMP.getPendingExpired()); break; case "area": if (!Permissions.hasPermission(player, C.PERMISSION_LIST_AREA)) { @@ -157,7 +140,8 @@ public class ListCmd extends SubCommand { return false; } if (!Permissions.hasPermission(player, C.PERMISSION_LIST_WORLD_NAME.f(world))) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_WORLD_NAME.f(world)); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_LIST_WORLD_NAME.f(world)); return false; } plots = area == null ? new ArrayList() : new ArrayList<>(area.getPlots()); @@ -167,7 +151,7 @@ public class ListCmd extends SubCommand { MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_ALL); return false; } - plots = new ArrayList<>(PS.get().getPlots()); + plots = new ArrayList<>(PlotSquared.get().getPlots()); break; case "done": if (!Permissions.hasPermission(player, C.PERMISSION_LIST_DONE)) { @@ -175,7 +159,7 @@ public class ListCmd extends SubCommand { return false; } plots = new ArrayList<>(); - for (Plot plot : PS.get().getPlots()) { + for (Plot plot : PlotSquared.get().getPlots()) { Optional flag = plot.getFlag(Flags.DONE); if (!flag.isPresent()) { continue; @@ -183,8 +167,7 @@ public class ListCmd extends SubCommand { plots.add(plot); } Collections.sort(plots, new Comparator() { - @Override - public int compare(Plot a, Plot b) { + @Override public int compare(Plot a, Plot b) { String va = "" + a.getFlags().get(Flags.DONE); String vb = "" + b.getFlags().get(Flags.DONE); if (MathMan.isInteger(va)) { @@ -203,10 +186,9 @@ public class ListCmd extends SubCommand { MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_TOP); return false; } - plots = new ArrayList<>(PS.get().getPlots()); + plots = new ArrayList<>(PlotSquared.get().getPlots()); Collections.sort(plots, new Comparator() { - @Override - public int compare(Plot p1, Plot p2) { + @Override public int compare(Plot p1, Plot p2) { double v1 = 0; int p1s = p1.getSettings().getRatings().size(); int p2s = p2.getRatings().size(); @@ -244,7 +226,7 @@ public class ListCmd extends SubCommand { break; } plots = new ArrayList<>(); - for (Plot plot : PS.get().getPlots()) { + for (Plot plot : PlotSquared.get().getPlots()) { Optional price = plot.getFlag(Flags.PRICE); if (price.isPresent()) { plots.add(plot); @@ -257,7 +239,7 @@ public class ListCmd extends SubCommand { return false; } plots = new ArrayList<>(); - for (Plot plot : PS.get().getPlots()) { + for (Plot plot : PlotSquared.get().getPlots()) { if (plot.owner == null) { plots.add(plot); } @@ -269,7 +251,7 @@ public class ListCmd extends SubCommand { return false; } plots = new ArrayList<>(); - for (Plot plot : PS.get().getPlots()) { + for (Plot plot : PlotSquared.get().getPlots()) { if (plot.owner == null) { continue; } @@ -297,23 +279,26 @@ public class ListCmd extends SubCommand { sort = false; break; default: - if (PS.get().hasPlotArea(args[0])) { + if (PlotSquared.get().hasPlotArea(args[0])) { if (!Permissions.hasPermission(player, C.PERMISSION_LIST_WORLD)) { MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_WORLD); return false; } - if (!Permissions.hasPermission(player, C.PERMISSION_LIST_WORLD_NAME.f(args[0]))) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_WORLD_NAME.f(args[0])); + if (!Permissions + .hasPermission(player, C.PERMISSION_LIST_WORLD_NAME.f(args[0]))) { + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_LIST_WORLD_NAME.f(args[0])); return false; } - plots = new ArrayList<>(PS.get().getPlots(args[0])); + plots = new ArrayList<>(PlotSquared.get().getPlots(args[0])); break; } UUID uuid = UUIDHandler.getUUID(args[0], null); if (uuid == null) { try { uuid = UUID.fromString(args[0]); - } catch (Exception ignored) {} + } catch (Exception ignored) { + } } if (uuid != null) { if (!Permissions.hasPermission(player, C.PERMISSION_LIST_PLAYER)) { @@ -321,13 +306,15 @@ public class ListCmd extends SubCommand { return false; } sort = false; - plots = PS.get().sortPlotsByTemp(PS.get().getPlots(uuid)); + plots = PlotSquared.get().sortPlotsByTemp(PlotSquared.get().getPlots(uuid)); break; } } if (plots == null) { - sendMessage(player, C.DID_YOU_MEAN, new StringComparison<>(args[0], new String[]{"mine", "shared", "world", "all"}).getBestMatch()); + sendMessage(player, C.DID_YOU_MEAN, + new StringComparison<>(args[0], new String[] {"mine", "shared", "world", "all"}) + .getBestMatch()); return false; } @@ -339,8 +326,8 @@ public class ListCmd extends SubCommand { return true; } - public void displayPlots(final PlotPlayer player, List plots, int pageSize, int page, PlotArea area, - String[] args, boolean sort) { + public void displayPlots(final PlotPlayer player, List plots, int pageSize, int page, + PlotArea area, String[] args, boolean sort) { // Header Iterator iterator = plots.iterator(); while (iterator.hasNext()) { @@ -349,56 +336,63 @@ public class ListCmd extends SubCommand { } } if (sort) { - plots = PS.get().sortPlots(plots, SortType.CREATION_DATE, area); + plots = PlotSquared.get().sortPlots(plots, SortType.CREATION_DATE, area); } - this.paginate(player, plots, pageSize, page, new RunnableVal3() { - @Override - public void run(Integer i, Plot plot, PlotMessage message) { - String color; - if (plot.owner == null) { - color = "$3"; - } else if (plot.isOwner(player.getUUID())) { - color = "$1"; - } else if (plot.isAdded(player.getUUID())) { - color = "$4"; - } else if (plot.isDenied(player.getUUID())) { - color = "$2"; - } else { - color = "$1"; - } - PlotMessage trusted = - new PlotMessage().text(C.color(C.PLOT_INFO_TRUSTED.s().replaceAll("%trusted%", MainUtil.getPlayerList(plot.getTrusted())))) - .color("$1"); - PlotMessage members = - new PlotMessage().text(C.color(C.PLOT_INFO_MEMBERS.s().replaceAll("%members%", MainUtil.getPlayerList(plot.getMembers())))) - .color("$1"); - String strFlags = StringMan.join(plot.getFlags().values(), ","); - if (strFlags.isEmpty()) { - strFlags = C.NONE.s(); - } - PlotMessage flags = new PlotMessage().text(C.color(C.PLOT_INFO_FLAGS.s().replaceAll("%flags%", strFlags))).color("$1"); - message.text("[").color("$3").text(i + "").command("/plot visit " + plot.getArea() + ";" + plot.getId()) - .tooltip("/plot visit " + plot.getArea() + ";" + plot.getId()).color("$1") - .text("]") - .color("$3").text(" " + plot.toString()).tooltip(trusted, members, flags) - .command("/plot info " + plot.getArea() + ";" + plot.getId()).color(color).text(" - ").color("$2"); - String prefix = ""; - for (UUID uuid : plot.getOwners()) { - String name = UUIDHandler.getName(uuid); - if (name == null) { - message = message.text(prefix).color("$4").text("unknown").color("$2").tooltip(uuid.toString()).suggest(uuid.toString()); + this.paginate(player, plots, pageSize, page, + new RunnableVal3() { + @Override public void run(Integer i, Plot plot, PlotMessage message) { + String color; + if (plot.owner == null) { + color = "$3"; + } else if (plot.isOwner(player.getUUID())) { + color = "$1"; + } else if (plot.isAdded(player.getUUID())) { + color = "$4"; + } else if (plot.isDenied(player.getUUID())) { + color = "$2"; } else { - PlotPlayer pp = UUIDHandler.getPlayer(uuid); - if (pp != null) { - message = message.text(prefix).color("$4").text(name).color("$1").tooltip(new PlotMessage("Online").color("$4")); - } else { - message = message.text(prefix).color("$4").text(name).color("$1").tooltip(new PlotMessage("Offline").color("$3")); - } + color = "$1"; + } + PlotMessage trusted = new PlotMessage().text(C.color(C.PLOT_INFO_TRUSTED.s() + .replaceAll("%trusted%", MainUtil.getPlayerList(plot.getTrusted())))) + .color("$1"); + PlotMessage members = new PlotMessage().text(C.color(C.PLOT_INFO_MEMBERS.s() + .replaceAll("%members%", MainUtil.getPlayerList(plot.getMembers())))) + .color("$1"); + String strFlags = StringMan.join(plot.getFlags().values(), ","); + if (strFlags.isEmpty()) { + strFlags = C.NONE.s(); + } + PlotMessage flags = new PlotMessage() + .text(C.color(C.PLOT_INFO_FLAGS.s().replaceAll("%flags%", strFlags))) + .color("$1"); + message.text("[").color("$3").text(i + "") + .command("/plot visit " + plot.getArea() + ";" + plot.getId()) + .tooltip("/plot visit " + plot.getArea() + ";" + plot.getId()).color("$1") + .text("]").color("$3").text(" " + plot.toString()) + .tooltip(trusted, members, flags) + .command("/plot info " + plot.getArea() + ";" + plot.getId()).color(color) + .text(" - ").color("$2"); + String prefix = ""; + for (UUID uuid : plot.getOwners()) { + String name = UUIDHandler.getName(uuid); + if (name == null) { + message = message.text(prefix).color("$4").text("unknown").color("$2") + .tooltip(uuid.toString()).suggest(uuid.toString()); + } else { + PlotPlayer pp = UUIDHandler.getPlayer(uuid); + if (pp != null) { + message = message.text(prefix).color("$4").text(name).color("$1") + .tooltip(new PlotMessage("Online").color("$4")); + } else { + message = message.text(prefix).color("$4").text(name).color("$1") + .tooltip(new PlotMessage("Offline").color("$3")); + } + } + prefix = ", "; } - prefix = ", "; } - } - }, "/plot list " + args[0], C.PLOT_LIST_HEADER_PAGED.s()); + }, "/plot list " + args[0], C.PLOT_LIST_HEADER_PAGED.s()); } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Load.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Load.java similarity index 66% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Load.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Load.java index 238c3631f..34353c77f 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Load.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Load.java @@ -1,37 +1,27 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.schematic.Schematic; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.SchematicHandler.Schematic; -import com.intellectualcrafters.plot.util.TaskManager; -import com.plotsquared.general.commands.CommandDeclaration; import java.net.MalformedURLException; import java.net.URL; import java.util.List; -@CommandDeclaration( - command = "load", - aliases = {"restore"}, - category = CommandCategory.SCHEMATIC, - requiredType = RequiredType.NONE, - description = "Load your plot", - permission = "plots.load", - usage = "/plot load") +@CommandDeclaration(command = "load", aliases = { + "restore"}, category = CommandCategory.SCHEMATIC, requiredType = RequiredType.NONE, description = "Load your plot", permission = "plots.load", usage = "/plot load") public class Load extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { String world = player.getLocation().getWorld(); - if (!PS.get().hasPlotArea(world)) { + if (!PlotSquared.get().hasPlotArea(world)) { return !sendMessage(player, C.NOT_IN_PLOT_WORLD); } final Plot plot = player.getCurrentPlot(); @@ -42,7 +32,8 @@ public class Load extends SubCommand { MainUtil.sendMessage(player, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_LOAD)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_LOAD)) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } @@ -64,7 +55,8 @@ public class Load extends SubCommand { schematic = schematics.get(Integer.parseInt(args[0]) - 1); } catch (Exception ignored) { // use /plot load - MainUtil.sendMessage(player, C.NOT_VALID_NUMBER, "(1, " + schematics.size() + ')'); + MainUtil + .sendMessage(player, C.NOT_VALID_NUMBER, "(1, " + schematics.size() + ')'); return false; } final URL url; @@ -78,26 +70,27 @@ public class Load extends SubCommand { plot.addRunning(); MainUtil.sendMessage(player, C.GENERATING_COMPONENT); TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { Schematic schematic = SchematicHandler.manager.getSchematic(url); if (schematic == null) { plot.removeRunning(); - sendMessage(player, C.SCHEMATIC_INVALID, "non-existent or not in gzip format"); + sendMessage(player, C.SCHEMATIC_INVALID, + "non-existent or not in gzip format"); return; } PlotArea area = plot.getArea(); - SchematicHandler.manager.paste(schematic, plot, 0, area.MIN_BUILD_HEIGHT, 0, false, new RunnableVal() { - @Override - public void run(Boolean value) { - plot.removeRunning(); - if (value) { - sendMessage(player, C.SCHEMATIC_PASTE_SUCCESS); - } else { - sendMessage(player, C.SCHEMATIC_PASTE_FAILED); - } - } - }); + SchematicHandler.manager + .paste(schematic, plot, 0, area.MIN_BUILD_HEIGHT, 0, false, + new RunnableVal() { + @Override public void run(Boolean value) { + plot.removeRunning(); + if (value) { + sendMessage(player, C.SCHEMATIC_PASTE_SUCCESS); + } else { + sendMessage(player, C.SCHEMATIC_PASTE_FAILED); + } + } + }); } }); return true; @@ -113,8 +106,7 @@ public class Load extends SubCommand { if (schematics == null) { plot.addRunning(); TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { List schematics = SchematicHandler.manager.getSaves(player.getUUID()); plot.removeRunning(); if ((schematics == null) || schematics.isEmpty()) { @@ -140,13 +132,15 @@ public class Load extends SubCommand { if (split.length < 5) { continue; } - String time = secToTime((System.currentTimeMillis() / 1000) - Long.parseLong(split[0])); + String time = + secToTime((System.currentTimeMillis() / 1000) - Long.parseLong(split[0])); String world = split[1]; PlotId id = PlotId.fromString(split[2] + ';' + split[3]); String size = split[4]; String color = "$4"; MainUtil.sendMessage(player, - "$3[$2" + (i + 1) + "$3] " + color + time + "$3 | " + color + world + ';' + id + "$3 | " + color + size + 'x' + size); + "$3[$2" + (i + 1) + "$3] " + color + time + "$3 | " + color + world + ';' + id + + "$3 | " + color + size + 'x' + size); } catch (Exception e) { e.printStackTrace(); } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/MainCommand.java similarity index 75% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/MainCommand.java index b1c14dc51..cc74d3c6a 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/MainCommand.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/MainCommand.java @@ -1,31 +1,22 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.ConsolePlayer; -import com.intellectualcrafters.plot.object.Expression; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal2; -import com.intellectualcrafters.plot.object.RunnableVal3; -import com.intellectualcrafters.plot.util.CmdConfirm; -import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.Permissions; -import com.plotsquared.general.commands.Command; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.CmdConfirm; +import com.github.intellectualsites.plotsquared.plot.util.EconHandler; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; import java.util.Arrays; /** * PlotSquared command class. */ -@CommandDeclaration( - command = "plot", - aliases = {"plots", "p", "plotsquared", "plot2", "p2", "ps", "2", "plotme", "plotz", "ap"}) -public class MainCommand extends Command { - +@CommandDeclaration(command = "plot", aliases = {"plots", "p", "plotsquared", "plot2", "p2", "ps", + "2", "plotme", "plotz", "ap"}) public class MainCommand extends Command { + private static MainCommand instance; public Help help; public Toggle toggle; @@ -97,7 +88,6 @@ public class MainCommand extends Command { new Trim(); new Done(); new Continue(); - new BO3(); new Middle(); new Grant(); // Set commands @@ -137,14 +127,16 @@ public class MainCommand extends Command { public void run(final Command cmd, final Runnable success, final Runnable failure) { if (cmd.hasConfirmation(player)) { CmdConfirm.addPending(player, cmd.getUsage(), new Runnable() { - @Override - public void run() { + @Override public void run() { if (EconHandler.manager != null) { PlotArea area = player.getApplicablePlotArea(); if (area != null) { - Expression priceEval = area.PRICES.get(cmd.getFullId()); - Double price = priceEval != null ? priceEval.evaluate(0d) : 0d; - if (price != null && EconHandler.manager.getMoney(player) < price) { + Expression priceEval = + area.PRICES.get(cmd.getFullId()); + Double price = + priceEval != null ? priceEval.evaluate(0d) : 0d; + if (price != null + && EconHandler.manager.getMoney(player) < price) { if (failure != null) { failure.run(); } @@ -177,8 +169,7 @@ public class MainCommand extends Command { } } }, new RunnableVal2() { - @Override - public void run(Command cmd, CommandResult result) { + @Override public void run(Command cmd, CommandResult result) { // Post command stuff!? } }); @@ -192,13 +183,13 @@ public class MainCommand extends Command { @Deprecated /** * @Deprecated legacy - */ - public void addCommand(SubCommand command) { - PS.debug("Command registration is now done during instantiation"); + */ public void addCommand(SubCommand command) { + PlotSquared.debug("Command registration is now done during instantiation"); } - @Override - public void execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { + @Override public void execute(final PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) { // Clear perm caching // player.deleteMeta("perm"); // Optional command scope // @@ -208,16 +199,18 @@ public class MainCommand extends Command { if (args.length >= 2) { PlotArea area = player.getApplicablePlotArea(); Plot newPlot = Plot.fromString(area, args[0]); - if (newPlot != null && (player instanceof ConsolePlayer || newPlot.getArea().equals(area) || Permissions.hasPermission(player, C.PERMISSION_ADMIN)) && !newPlot.isDenied(player.getUUID())) { + if (newPlot != null && (player instanceof ConsolePlayer || newPlot.getArea() + .equals(area) || Permissions.hasPermission(player, C.PERMISSION_ADMIN)) && !newPlot + .isDenied(player.getUUID())) { Location newLoc = newPlot.getCenter(); if (player.canTeleport(newLoc)) { // Save meta - loc = player.getMeta("location"); - plot = player.getMeta("lastplot"); + loc = player.getMeta(PlotPlayer.META_LOCATION); + plot = player.getMeta(PlotPlayer.META_LAST_PLOT); tp = true; // Set loc - player.setMeta("location", newLoc); - player.setMeta("lastplot", newPlot); + player.setMeta(PlotPlayer.META_LOCATION, newLoc); + player.setMeta(PlotPlayer.META_LAST_PLOT, newPlot); } else { C.BORDER.send(player); } @@ -233,9 +226,12 @@ public class MainCommand extends Command { if (EconHandler.manager != null) { PlotArea area = player.getApplicablePlotArea(); if (area != null) { - Expression priceEval = area.PRICES.get(cmd.getFullId()); - Double price = priceEval != null ? priceEval.evaluate(0d) : 0d; - if (price != 0d && EconHandler.manager.getMoney(player) < price) { + Expression priceEval = + area.PRICES.get(cmd.getFullId()); + Double price = + priceEval != null ? priceEval.evaluate(0d) : 0d; + if (price != 0d + && EconHandler.manager.getMoney(player) < price) { if (failure != null) { failure.run(); } @@ -272,20 +268,19 @@ public class MainCommand extends Command { // Reset command scope // if (tp && !(player instanceof ConsolePlayer)) { if (loc == null) { - player.deleteMeta("location"); + player.deleteMeta(PlotPlayer.META_LOCATION); } else { - player.setMeta("location", loc); + player.setMeta(PlotPlayer.META_LOCATION, loc); } if (plot == null) { - player.deleteMeta("lastplot"); + player.deleteMeta(PlotPlayer.META_LAST_PLOT); } else { - player.setMeta("lastplot", plot); + player.setMeta(PlotPlayer.META_LAST_PLOT, plot); } } } - @Override - public boolean canExecute(PlotPlayer player, boolean message) { + @Override public boolean canExecute(PlotPlayer player, boolean message) { return true; } } diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Merge.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Merge.java similarity index 73% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Merge.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Merge.java index b620fe468..e9527e3bd 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Merge.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Merge.java @@ -1,33 +1,18 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.object.Expression; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.CmdConfirm; -import com.intellectualcrafters.plot.util.EconHandler; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.*; import java.util.UUID; -@CommandDeclaration(command = "merge", - aliases = "m", - description = "Merge the plot you are standing on, with another plot", - permission = "plots.merge", usage = "/plot merge [removeroads]", - category = CommandCategory.SETTINGS, - requiredType = RequiredType.NONE, - confirmation = true) +@CommandDeclaration(command = "merge", aliases = "m", description = "Merge the plot you are standing on, with another plot", permission = "plots.merge", usage = "/plot merge [removeroads]", category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE, confirmation = true) public class Merge extends SubCommand { - public static final String[] values = new String[]{"north", "east", "south", "west", "auto"}; - public static final String[] aliases = new String[]{"n", "e", "s", "w", "all"}; + public static final String[] values = new String[] {"north", "east", "south", "west", "auto"}; + public static final String[] aliases = new String[] {"n", "e", "s", "w", "all"}; public static String direction(float yaw) { yaw = yaw / 90; @@ -51,8 +36,7 @@ public class Merge extends SubCommand { } } - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { Location loc = player.getLocationFull(); final Plot plot = loc.getPlotAbs(); if (plot == null) { @@ -72,14 +56,17 @@ public class Merge extends SubCommand { } } final PlotArea plotArea = plot.getArea(); - Expression priceExr = plotArea.PRICES.containsKey("merge") ? plotArea.PRICES.get("merge") : null; + Expression priceExr = + plotArea.PRICES.containsKey("merge") ? plotArea.PRICES.get("merge") : null; final int size = plot.getConnectedPlots().size(); final double price = priceExr == null ? 0d : priceExr.evaluate((double) size); - if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d && EconHandler.manager.getMoney(player) < price) { + if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d + && EconHandler.manager.getMoney(player) < price) { sendMessage(player, C.CANNOT_AFFORD_MERGE, String.valueOf(price)); return false; } - final int maxSize = Permissions.hasPermissionRange(player, "plots.merge", Settings.Limit.MAX_PLOTS); + final int maxSize = + Permissions.hasPermissionRange(player, "plots.merge", Settings.Limit.MAX_PLOTS); if (size - 1 > maxSize) { MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.merge." + (size + 1)); return false; @@ -126,8 +113,10 @@ public class Merge extends SubCommand { } } if (direction == -1) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot merge <" + StringMan.join(values, "|") + "> [removeroads]"); - MainUtil.sendMessage(player, C.DIRECTION.s().replaceAll("%dir%", direction(loc.getYaw()))); + MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + "/plot merge <" + StringMan.join(values, "|") + "> [removeroads]"); + MainUtil + .sendMessage(player, C.DIRECTION.s().replaceAll("%dir%", direction(loc.getYaw()))); return false; } final boolean terrain; @@ -145,7 +134,8 @@ public class Merge extends SubCommand { return true; } Plot adjacent = plot.getRelative(direction); - if (adjacent == null || !adjacent.hasOwner() || adjacent.getMerged((direction + 2) % 4) || adjacent.isOwner(uuid)) { + if (adjacent == null || !adjacent.hasOwner() || adjacent.getMerged((direction + 2) % 4) + || adjacent.isOwner(uuid)) { MainUtil.sendMessage(player, C.NO_AVAILABLE_AUTOMERGE); return false; } @@ -163,8 +153,7 @@ public class Merge extends SubCommand { isOnline = true; final int dir = direction; Runnable run = new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(accepter, C.MERGE_ACCEPTED); plot.autoMerge(dir, maxSize - size, owner, terrain); PlotPlayer plotPlayer = UUIDHandler.getPlayer(player.getUUID()); @@ -184,7 +173,8 @@ public class Merge extends SubCommand { } }; if (hasConfirmation(player)) { - CmdConfirm.addPending(accepter, C.MERGE_REQUEST_CONFIRM.s().replaceAll("%s", player.getName()), run); + CmdConfirm.addPending(accepter, + C.MERGE_REQUEST_CONFIRM.s().replaceAll("%s", player.getName()), run); } else { run.run(); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Middle.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Middle.java new file mode 100644 index 000000000..0105dc8bf --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Middle.java @@ -0,0 +1,28 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; + +/** + * @author manuelgu, altered by Citymonstret + */ +@CommandDeclaration(command = "middle", aliases = {"center", + "centre"}, description = "Teleports you to the center of the plot", usage = "/plot middle", category = CommandCategory.TELEPORT, requiredType = RequiredType.NONE) +public class Middle extends SubCommand { + + @Override public boolean onCommand(PlotPlayer player, String[] arguments) { + Location location = player.getLocation(); + Plot plot = location.getPlot(); + if (plot == null) { + return sendMessage(player, C.NOT_IN_PLOT); + } + if (!plot.hasOwner()) { + return sendMessage(player, C.PLOT_UNOWNED); + } + player.teleport(plot.getCenter()); + return true; + } +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Move.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Move.java similarity index 52% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Move.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Move.java index 8a3a52180..725ce3a25 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Move.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Move.java @@ -1,46 +1,40 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; -@CommandDeclaration( - usage = "/plot move ", - command = "move", - description = "Move a plot", - aliases = {"debugmove"}, - permission = "plots.move", - category = CommandCategory.CLAIMING, - requiredType = RequiredType.NONE) +@CommandDeclaration(usage = "/plot move ", command = "move", description = "Move a plot", aliases = { + "debugmove"}, permission = "plots.move", category = CommandCategory.CLAIMING, requiredType = RequiredType.NONE) public class Move extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { Location loc = player.getLocation(); Plot plot1 = loc.getPlotAbs(); if (plot1 == null) { return !MainUtil.sendMessage(player, C.NOT_IN_PLOT); } - if (!plot1.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN.s())) { + if (!plot1.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN.s())) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } boolean override = false; if (args.length == 2 && args[1].equalsIgnoreCase("-f")) { - args = new String[]{ args[0] }; + args = new String[] {args[0]}; override = true; } if (args.length != 1) { C.COMMAND_SYNTAX.send(player, getUsage()); return false; } - PlotArea area = PS.get().getPlotAreaByString(args[0]); + PlotArea area = PlotSquared.get().getPlotAreaByString(args[0]); Plot plot2; if (area == null) { plot2 = MainUtil.getPlotFromString(player, args[0], true); @@ -55,13 +49,13 @@ public class Move extends SubCommand { MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot copy "); return false; } - if (!plot1.getArea().isCompatible(plot2.getArea()) && (!override || !Permissions.hasPermission(player, C.PERMISSION_ADMIN.s()))) { + if (!plot1.getArea().isCompatible(plot2.getArea()) && (!override || !Permissions + .hasPermission(player, C.PERMISSION_ADMIN.s()))) { C.PLOTWORLD_INCOMPATIBLE.send(player); return false; } if (plot1.move(plot2, new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(player, C.MOVE_SUCCESS); } }, false)) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Music.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Music.java similarity index 50% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Music.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Music.java index 47f47fb48..c889ba334 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Music.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Music.java @@ -1,27 +1,15 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotBlock; -import com.intellectualcrafters.plot.object.PlotInventory; -import com.intellectualcrafters.plot.object.PlotItemStack; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.WorldUtil; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.flag.Flags; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; -@CommandDeclaration( - command = "music", - permission = "plots.music", - description = "Play music in your plot", - usage = "/plot music", - category = CommandCategory.APPEARANCE, - requiredType = RequiredType.PLAYER) +@CommandDeclaration(command = "music", permission = "plots.music", description = "Play music in your plot", usage = "/plot music", category = CommandCategory.APPEARANCE, requiredType = RequiredType.PLAYER) public class Music extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { Location loc = player.getLocation(); final Plot plot = loc.getPlotAbs(); if (plot == null) { @@ -32,24 +20,23 @@ public class Music extends SubCommand { return true; } PlotInventory inv = new PlotInventory(player, 2, "Plot Jukebox") { - @Override - public boolean onClick(int index) { + @Override public boolean onClick(int index) { PlotItemStack item = getItem(index); if (item == null) { return true; } - int id = item.id == 7 ? 0 : item.id; - if (id == 0) { + if (item.getPlotBlock().equalsAny(7, "bedrock")) { plot.removeFlag(Flags.MUSIC); } else { - plot.setFlag(Flags.MUSIC, id); + plot.setFlag(Flags.MUSIC, item.getPlotBlock().getRawId()); } return false; } }; int index = 0; for (int i = 2256; i < 2268; i++) { - String name = "&r&6" + WorldUtil.IMP.getClosestMatchingName(PlotBlock.get((short) i, (byte) 0)); + String name = + "&r&6" + WorldUtil.IMP.getClosestMatchingName(PlotBlock.get((short) i, (byte) 0)); String[] lore = {"&r&aClick to play!"}; PlotItemStack item = new PlotItemStack(i, (byte) 0, 1, name, lore); inv.setItem(index, item); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Near.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Near.java new file mode 100644 index 000000000..b9929e51e --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Near.java @@ -0,0 +1,24 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; + +@CommandDeclaration(command = "near", aliases = "n", description = "Display nearby players", usage = "/plot near", category = CommandCategory.INFO) +public class Near extends Command { + public Near() { + super(MainCommand.getInstance(), true); + } + + @Override public void execute(PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) throws CommandException { + final Plot plot = check(player.getCurrentPlot(), C.NOT_IN_PLOT); + C.PLOT_NEAR.send(player, StringMan.join(plot.getPlayersInPlot(), ", ")); + } +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Owner.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Owner.java similarity index 63% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Owner.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Owner.java index 26a4e413f..964cbf212 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Owner.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Owner.java @@ -1,28 +1,21 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.*; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.*; import java.util.Set; import java.util.UUID; -@CommandDeclaration( - command = "setowner", - permission = "plots.set.owner", - description = "Set the plot owner", - usage = "/plot setowner ", - aliases = {"owner", "so", "seto"}, - category = CommandCategory.CLAIMING, - requiredType = RequiredType.NONE, - confirmation = true) +@CommandDeclaration(command = "setowner", permission = "plots.set.owner", description = "Set the plot owner", usage = "/plot setowner ", aliases = { + "owner", "so", + "seto"}, category = CommandCategory.CLAIMING, requiredType = RequiredType.NONE, confirmation = true) public class Owner extends SetCommand { - @Override - public boolean set(final PlotPlayer player, final Plot plot, String value) { + @Override public boolean set(final PlotPlayer player, final Plot plot, String value) { Set plots = plot.getConnectedPlots(); UUID uuid = null; String name = null; @@ -38,8 +31,10 @@ public class Owner extends SetCommand { name = name == null ? value : name; } if (uuid == null || value.equalsIgnoreCase("-")) { - if (value.equalsIgnoreCase("none") || value.equalsIgnoreCase("null") || value.equalsIgnoreCase("-")) { - if (!Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SETOWNER.s(), true)) { + if (value.equalsIgnoreCase("none") || value.equalsIgnoreCase("null") || value + .equalsIgnoreCase("-")) { + if (!Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SETOWNER.s(), true)) { return false; } Set connected = plot.getConnectedPlots(); @@ -65,7 +60,9 @@ public class Owner extends SetCommand { return false; } int size = plots.size(); - int currentPlots = (Settings.Limit.GLOBAL ? other.getPlotCount() : other.getPlotCount(plot.getWorldName())) + size; + int currentPlots = (Settings.Limit.GLOBAL ? + other.getPlotCount() : + other.getPlotCount(plot.getWorldName())) + size; if (currentPlots > other.getAllowedPlots()) { sendMessage(player, C.CANT_TRANSFER_MORE_PLOTS); return false; @@ -75,14 +72,15 @@ public class Owner extends SetCommand { final UUID finalUUID = uuid; final boolean removeDenied = plot.isDenied(finalUUID); Runnable run = new Runnable() { - @Override - public void run() { + @Override public void run() { if (plot.setOwner(finalUUID, player)) { - if (removeDenied) plot.removeDenied(finalUUID); + if (removeDenied) + plot.removeDenied(finalUUID); plot.setSign(finalName); MainUtil.sendMessage(player, C.SET_OWNER); if (other != null) { - MainUtil.sendMessage(other, C.NOW_OWNER, plot.getArea() + ";" + plot.getId()); + MainUtil + .sendMessage(other, C.NOW_OWNER, plot.getArea() + ";" + plot.getId()); } } else MainUtil.sendMessage(player, C.SET_OWNER_CANCELLED); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/PluginCmd.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/PluginCmd.java new file mode 100644 index 000000000..37cf5ad60 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/PluginCmd.java @@ -0,0 +1,37 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.json.JSONObject; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.HttpUtil; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; + +@CommandDeclaration(command = "plugin", permission = "plots.use", description = "Show plugin information", usage = "/plot plugin", aliases = "version", category = CommandCategory.INFO) +public class PluginCmd extends SubCommand { + + @Override public boolean onCommand(final PlotPlayer player, String[] args) { + TaskManager.IMP.taskAsync(new Runnable() { + @Override public void run() { + MainUtil.sendMessage(player, String.format( + "$2>> $1&l" + PlotSquared.imp().getPluginName() + " $2($1Version$2: $1%s$2)", + PlotSquared.get().getVersion())); + MainUtil.sendMessage(player, + "$2>> $1&lAuthors$2: $1Citymonstret $2& $1Empire92 $2& $1MattBDev"); + MainUtil.sendMessage(player, + "$2>> $1&lWiki$2: $1https://github.com/IntellectualCrafters/PlotSquared/wiki"); + MainUtil.sendMessage(player, + "$2>> $1&lNewest Version$2: $1" + getNewestVersionString()); + } + }); + return true; + } + + public String getNewestVersionString() { + String str = HttpUtil + .readUrl("https://api.github.com/repos/IntellectualSites/PlotSquared/releases/latest"); + JSONObject release = new JSONObject(str); + return release.getString("name"); + } +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Purge.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Purge.java similarity index 72% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Purge.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Purge.java index 95eccb11c..57e0fe2e9 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Purge.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Purge.java @@ -1,35 +1,27 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.CmdConfirm; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.plotsquared.general.commands.CommandDeclaration; -import com.plotsquared.listener.PlotListener; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.listener.PlotListener; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.CmdConfirm; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.UUID; -@CommandDeclaration( - usage = "/plot purge world: area: id: owner: shared: unknown:[true|false]", - command = "purge", - permission = "plots.admin", - description = "Purge all plots for a world", - category = CommandCategory.ADMINISTRATION, - requiredType = RequiredType.CONSOLE, - confirmation = true) +@CommandDeclaration(usage = "/plot purge world: area: id: owner: shared: unknown:[true|false]", command = "purge", permission = "plots.admin", description = "Purge all plots for a world", category = CommandCategory.ADMINISTRATION, requiredType = RequiredType.CONSOLE, confirmation = true) public class Purge extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length == 0) { return false; } @@ -53,7 +45,7 @@ public class Purge extends SubCommand { break; case "area": case "a": - area = PS.get().getPlotAreaByString(split[1]); + area = PlotSquared.get().getPlotAreaByString(split[1]); if (area == null) { C.NOT_VALID_PLOT_WORLD.send(player, split[1]); return false; @@ -94,7 +86,7 @@ public class Purge extends SubCommand { } } final HashSet toDelete = new HashSet<>(); - for (Plot plot : PS.get().getBasePlots()) { + for (Plot plot : PlotSquared.get().getBasePlots()) { if (world != null && !plot.getWorldName().equalsIgnoreCase(world)) { continue; } @@ -117,8 +109,9 @@ public class Purge extends SubCommand { toDelete.add(current); } } - if (PS.get().plots_tmp != null) { - for (Entry> entry : PS.get().plots_tmp.entrySet()) { + if (PlotSquared.get().plots_tmp != null) { + for (Entry> entry : PlotSquared.get().plots_tmp + .entrySet()) { String worldName = entry.getKey(); if (world != null && !world.equalsIgnoreCase(worldName)) { continue; @@ -145,11 +138,11 @@ public class Purge extends SubCommand { C.FOUND_NO_PLOTS.send(player); return false; } - String cmd = "/plot purge " + StringMan.join(args, " ") + " (" + toDelete.size() + " plots)"; + String cmd = + "/plot purge " + StringMan.join(args, " ") + " (" + toDelete.size() + " plots)"; Runnable run = new Runnable() { - @Override - public void run() { - PS.debug("Calculating plots to purge, please wait..."); + @Override public void run() { + PlotSquared.debug("Calculating plots to purge, please wait..."); HashSet ids = new HashSet<>(); for (Plot plot : toDelete) { if (plot.temp != Integer.MAX_VALUE) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Rate.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Rate.java similarity index 76% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Rate.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Rate.java index 2c9090e68..9b31124c8 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Rate.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Rate.java @@ -1,48 +1,28 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.flag.Flags; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotInventory; -import com.intellectualcrafters.plot.object.PlotItemStack; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.Rating; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.MathMan; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.TaskManager; -import com.plotsquared.general.commands.Command; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.flag.Flags; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.*; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; +import java.util.*; import java.util.Map.Entry; -import java.util.UUID; -@CommandDeclaration(command = "rate", - permission = "plots.rate", - description = "Rate the plot", - usage = "/plot rate [#|next|purge]", - aliases = "rt", - category = CommandCategory.INFO, - requiredType = RequiredType.NONE) +@CommandDeclaration(command = "rate", permission = "plots.rate", description = "Rate the plot", usage = "/plot rate [#|next|purge]", aliases = "rt", category = CommandCategory.INFO, requiredType = RequiredType.NONE) public class Rate extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length == 1) { switch (args[0].toLowerCase()) { case "next": { - ArrayList plots = new ArrayList<>(PS.get().getBasePlots()); + ArrayList plots = new ArrayList<>(PlotSquared.get().getBasePlots()); Collections.sort(plots, new Comparator() { - @Override - public int compare(Plot p1, Plot p2) { + @Override public int compare(Plot p1, Plot p2) { double v1 = 0; if (!p1.getRatings().isEmpty()) { for (Entry entry : p1.getRatings().entrySet()) { @@ -63,8 +43,9 @@ public class Rate extends SubCommand { }); UUID uuid = player.getUUID(); for (Plot p : plots) { - if ((!Settings.Done.REQUIRED_FOR_RATINGS || p.hasFlag(Flags.DONE)) && p.isBasePlot() && (!p.getRatings() - .containsKey(uuid)) && !p.isAdded(uuid)) { + if ((!Settings.Done.REQUIRED_FOR_RATINGS || p.hasFlag(Flags.DONE)) && p + .isBasePlot() && (!p.getRatings().containsKey(uuid)) && !p + .isAdded(uuid)) { p.teleportPlayer(player); MainUtil.sendMessage(player, C.RATE_THIS); return true; @@ -105,8 +86,7 @@ public class Rate extends SubCommand { } if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES.isEmpty()) { final Runnable run = new Runnable() { - @Override - public void run() { + @Override public void run() { if (plot.getRatings().containsKey(player.getUUID())) { sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString()); return; @@ -115,18 +95,21 @@ public class Rate extends SubCommand { final MutableInt rating = new MutableInt(0); String title = Settings.Ratings.CATEGORIES.get(0); PlotInventory inventory = new PlotInventory(player, 1, title) { - @Override - public boolean onClick(int i) { + @Override public boolean onClick(int i) { rating.add((i + 1) * Math.pow(10, index.getValue())); index.increment(); if (index.getValue() >= Settings.Ratings.CATEGORIES.size()) { int rV = rating.getValue(); - Rating result = EventUtil.manager.callRating(this.player, plot, new Rating(rV)); + Rating result = + EventUtil.manager.callRating(this.player, plot, new Rating(rV)); if (result != null) { plot.addRating(this.player.getUUID(), result); - sendMessage(this.player, C.RATING_APPLIED, plot.getId().toString()); - if (Permissions.hasPermission(this.player, C.PERMISSION_COMMENT)) { - Command command = MainCommand.getInstance().getCommand(Comment.class); + sendMessage(this.player, C.RATING_APPLIED, + plot.getId().toString()); + if (Permissions + .hasPermission(this.player, C.PERMISSION_COMMENT)) { + Command command = + MainCommand.getInstance().getCommand(Comment.class); if (command != null) { MainUtil.sendMessage(this.player, C.COMMENT_THIS, command.getUsage()); @@ -154,8 +137,7 @@ public class Rate extends SubCommand { if (plot.getSettings().ratings == null) { if (!Settings.Enabled_Components.RATING_CACHE) { TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { plot.getSettings().ratings = DBFunc.getRatings(plot); run.run(); } @@ -185,8 +167,7 @@ public class Rate extends SubCommand { } final UUID uuid = player.getUUID(); final Runnable run = new Runnable() { - @Override - public void run() { + @Override public void run() { if (plot.getRatings().containsKey(uuid)) { sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString()); return; @@ -201,8 +182,7 @@ public class Rate extends SubCommand { if (plot.getSettings().ratings == null) { if (!Settings.Enabled_Components.RATING_CACHE) { TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { plot.getSettings().ratings = DBFunc.getRatings(plot); run.run(); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/RegenAllRoads.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/RegenAllRoads.java new file mode 100644 index 000000000..e149a077f --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/RegenAllRoads.java @@ -0,0 +1,62 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotManager; +import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; +import com.github.intellectualsites.plotsquared.plot.object.ChunkLoc; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotManager; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; + +import java.util.Set; + +@CommandDeclaration(command = "regenallroads", description = "Regenerate all roads in the map using the set road schematic", aliases = { + "rgar"}, usage = "/plot regenallroads [height]", category = CommandCategory.ADMINISTRATION, requiredType = RequiredType.CONSOLE, permission = "plots.regenallroads") +public class RegenAllRoads extends SubCommand { + + @Override public boolean onCommand(PlotPlayer player, String[] args) { + int height = 0; + if (args.length == 2) { + try { + height = Integer.parseInt(args[1]); + } catch (NumberFormatException ignored) { + MainUtil.sendMessage(player, C.NOT_VALID_NUMBER, "(0, 256)"); + MainUtil + .sendMessage(player, C.COMMAND_SYNTAX, "/plot regenallroads [height]"); + return false; + } + } else if (args.length != 1) { + MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot regenallroads [height]"); + return false; + } + PlotArea area = PlotSquared.get().getPlotAreaByString(args[0]); + if (area == null) { + C.NOT_VALID_PLOT_WORLD.send(player, args[0]); + return false; + } + String name = args[0]; + PlotManager manager = area.getPlotManager(); + if (!(manager instanceof HybridPlotManager)) { + MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD); + return false; + } + Set chunks = ChunkManager.manager.getChunkChunks(name); + MainUtil + .sendMessage(player, "&cIf no schematic is set, the following will not do anything"); + MainUtil.sendMessage(player, + "&7 - To set a schematic, stand in a plot and use &c/plot createroadschematic"); + MainUtil.sendMessage(player, "&6Potential chunks to update: &7" + (chunks.size() * 1024)); + MainUtil.sendMessage(player, "&6Estimated time: &7" + chunks.size() + " seconds"); + boolean result = HybridUtils.manager.scheduleRoadUpdate(area, height); + if (!result) { + MainUtil.sendMessage(player, + "&cCannot schedule mass schematic update! (Is one already in progress?)"); + return false; + } + return true; + } +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Relight.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Relight.java new file mode 100644 index 000000000..7b3b52fe0 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Relight.java @@ -0,0 +1,39 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; +import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; + +import java.util.HashSet; + +@CommandDeclaration(command = "relight", description = "Relight your plot", usage = "/plot relight", category = CommandCategory.DEBUG) +public class Relight extends Command { + public Relight() { + super(MainCommand.getInstance(), true); + } + + @Override public void execute(final PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) { + final Plot plot = player.getCurrentPlot(); + if (plot == null) { + C.NOT_IN_PLOT.send(player); + return; + } + HashSet regions = plot.getRegions(); + final LocalBlockQueue queue = plot.getArea().getQueue(false); + ChunkManager.chunkTask(plot, new RunnableVal() { + @Override public void run(int[] value) { + queue.fixChunkLighting(value[0], value[1]); + } + }, new Runnable() { + @Override public void run() { + plot.refreshChunks(); + C.SET_BLOCK_ACTION_FINISHED.send(player); + } + }, 5); + } +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Reload.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Reload.java similarity index 60% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Reload.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Reload.java index 58d447337..d24b54ff8 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Reload.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Reload.java @@ -1,37 +1,32 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection; +import com.github.intellectualsites.plotsquared.configuration.MemorySection; +import com.github.intellectualsites.plotsquared.configuration.file.YamlConfiguration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; -import com.intellectualcrafters.configuration.ConfigurationSection; -import com.intellectualcrafters.configuration.MemorySection; -import com.intellectualcrafters.configuration.file.YamlConfiguration; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.MainUtil; -import com.plotsquared.general.commands.CommandDeclaration; import java.io.IOException; import java.util.Objects; -@CommandDeclaration(command = "reload", - aliases = "rl", - permission = "plots.admin.command.reload", - description = "Reload translations and world settings", - usage = "/plot reload", - category = CommandCategory.ADMINISTRATION) +@CommandDeclaration(command = "reload", aliases = "rl", permission = "plots.admin.command.reload", description = "Reload translations and world settings", usage = "/plot reload", category = CommandCategory.ADMINISTRATION) public class Reload extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { try { // The following won't affect world generation, as that has to be // loaded during startup unfortunately. - PS.get().setupConfigs(); - C.load(PS.get().translationFile); - PS.get().foreachPlotArea(new RunnableVal() { - @Override - public void run(PlotArea area) { - ConfigurationSection worldSection = PS.get().worlds.getConfigurationSection("worlds." + area.worldname); + PlotSquared.get().setupConfigs(); + C.load(PlotSquared.get().translationFile); + PlotSquared.get().foreachPlotArea(new RunnableVal() { + @Override public void run(PlotArea area) { + ConfigurationSection worldSection = PlotSquared.get().worlds + .getConfigurationSection("worlds." + area.worldname); if (worldSection == null) { return; } @@ -39,8 +34,8 @@ public class Reload extends SubCommand { area.saveConfiguration(worldSection); area.loadDefaultConfiguration(worldSection); } else { - ConfigurationSection areaSection = - worldSection.getConfigurationSection("areas." + area.id + "-" + area.getMin() + "-" + area.getMax()); + ConfigurationSection areaSection = worldSection.getConfigurationSection( + "areas." + area.id + "-" + area.getMin() + "-" + area.getMax()); YamlConfiguration clone = new YamlConfiguration(); for (String key : areaSection.getKeys(true)) { if (areaSection.get(key) instanceof MemorySection) { @@ -77,7 +72,7 @@ public class Reload extends SubCommand { } } }); - PS.get().worlds.save(PS.get().worldsFile); + PlotSquared.get().worlds.save(PlotSquared.get().worldsFile); MainUtil.sendMessage(player, C.RELOADED_CONFIGS); } catch (IOException e) { e.printStackTrace(); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Remove.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Remove.java similarity index 65% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Remove.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Remove.java index 207223384..666192e58 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Remove.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Remove.java @@ -1,38 +1,31 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.database.DBFunc; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.EventUtil; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.UUIDHandler; -import com.plotsquared.general.commands.Argument; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.Argument; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.EventUtil; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import java.util.UUID; -@CommandDeclaration( - command = "remove", - aliases = {"r","untrust", "ut", "undeny", "unban", "ud"}, - description = "Remove a player from a plot", - usage = "/plot remove ", - category = CommandCategory.SETTINGS, - requiredType = RequiredType.NONE, - permission = "plots.remove") +@CommandDeclaration(command = "remove", aliases = {"r", "untrust", "ut", "undeny", "unban", + "ud"}, description = "Remove a player from a plot", usage = "/plot remove ", category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE, permission = "plots.remove") public class Remove extends SubCommand { public Remove() { super(Argument.PlayerName); } - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { Location location = player.getLocation(); Plot plot = location.getPlotAbs(); if (plot == null) { @@ -42,7 +35,8 @@ public class Remove extends SubCommand { MainUtil.sendMessage(player, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_REMOVE)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_REMOVE)) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return true; } @@ -71,19 +65,18 @@ public class Remove extends SubCommand { Set uuids = MainUtil.getUUIDsFromString(args[0]); if (!uuids.isEmpty()) { for (UUID uuid : uuids) { - if (uuid == DBFunc.everyone) { - if (plot.removeTrusted(uuid)){ + if (uuid == DBFunc.EVERYONE) { + if (plot.removeTrusted(uuid)) { EventUtil.manager.callTrusted(player, plot, uuid, false); count++; - }else if (plot.removeMember(uuid)) { + } else if (plot.removeMember(uuid)) { EventUtil.manager.callMember(player, plot, uuid, false); count++; - }else if (plot.removeDenied(uuid)) { + } else if (plot.removeDenied(uuid)) { EventUtil.manager.callDenied(player, plot, uuid, false); count++; } - } - else if (plot.getTrusted().contains(uuid)) { + } else if (plot.getTrusted().contains(uuid)) { if (plot.removeTrusted(uuid)) { EventUtil.manager.callTrusted(player, plot, uuid, false); count++; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/RequiredType.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/RequiredType.java similarity index 67% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/RequiredType.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/RequiredType.java index 9ea99c407..3f13368de 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/RequiredType.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/RequiredType.java @@ -1,6 +1,6 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.plotsquared.general.commands.CommandCaller; +import com.github.intellectualsites.plotsquared.commands.CommandCaller; public enum RequiredType { CONSOLE, PLAYER, NONE; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Save.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Save.java similarity index 58% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Save.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Save.java index bdf706faa..b4722772e 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Save.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Save.java @@ -1,34 +1,26 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.SchematicHandler; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.sk89q.jnbt.CompoundTag; -import com.intellectualcrafters.jnbt.CompoundTag; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.TaskManager; -import com.plotsquared.general.commands.CommandDeclaration; import java.net.URL; import java.util.List; import java.util.UUID; -@CommandDeclaration(command = "save", - aliases = {"backup"}, - description = "Save your plot", - category = CommandCategory.SCHEMATIC, - requiredType = RequiredType.NONE, - permission = "plots.save") +@CommandDeclaration(command = "save", aliases = { + "backup"}, description = "Save your plot", category = CommandCategory.SCHEMATIC, requiredType = RequiredType.NONE, permission = "plots.save") public class Save extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { String world = player.getLocation().getWorld(); - if (!PS.get().hasPlotArea(world)) { + if (!PlotSquared.get().hasPlotArea(world)) { return !sendMessage(player, C.NOT_IN_PLOT_WORLD); } final Plot plot = player.getCurrentPlot(); @@ -39,7 +31,8 @@ public class Save extends SubCommand { MainUtil.sendMessage(player, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SAVE)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SAVE)) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } @@ -49,23 +42,22 @@ public class Save extends SubCommand { } plot.addRunning(); SchematicHandler.manager.getCompoundTag(plot, new RunnableVal() { - @Override - public void run(final CompoundTag value) { + @Override public void run(final CompoundTag value) { TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { + @Override public void run() { String time = (System.currentTimeMillis() / 1000) + ""; Location[] corners = plot.getCorners(); corners[0].setY(0); corners[1].setY(255); int size = (corners[1].getX() - corners[0].getX()) + 1; PlotId id = plot.getId(); - String world = plot.getArea().toString().replaceAll(";", "-").replaceAll("[^A-Za-z0-9]", ""); - final String file = time + '_' + world + '_' + id.x + '_' + id.y + '_' + size; + String world = plot.getArea().toString().replaceAll(";", "-") + .replaceAll("[^A-Za-z0-9]", ""); + final String file = + time + '_' + world + '_' + id.x + '_' + id.y + '_' + size; UUID uuid = player.getUUID(); SchematicHandler.manager.upload(value, uuid, file, new RunnableVal() { - @Override - public void run(URL url) { + @Override public void run(URL url) { plot.removeRunning(); if (url == null) { MainUtil.sendMessage(player, C.SAVE_FAILED); diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SchematicCmd.java similarity index 64% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SchematicCmd.java index b190de880..6e2852ac6 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/SchematicCmd.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SchematicCmd.java @@ -1,39 +1,25 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.object.ConsolePlayer; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.RunnableVal; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.SchematicHandler; -import com.intellectualcrafters.plot.util.SchematicHandler.Schematic; -import com.intellectualcrafters.plot.util.TaskManager; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.schematic.Schematic; +import com.github.intellectualsites.plotsquared.plot.util.*; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.UUID; -@CommandDeclaration( - command = "schematic", - permission = "plots.schematic", - description = "Schematic command", - aliases = {"sch", "schem"}, - category = CommandCategory.SCHEMATIC, - usage = "/plot schematic ") +@CommandDeclaration(command = "schematic", permission = "plots.schematic", description = "Schematic command", aliases = { + "sch", "schem"}, category = CommandCategory.SCHEMATIC, usage = "/plot schematic ") public class SchematicCmd extends SubCommand { private boolean running = false; - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length < 1) { sendMessage(player, C.SCHEMATIC_MISSING_ARG); return true; @@ -58,7 +44,8 @@ public class SchematicCmd extends SubCommand { MainUtil.sendMessage(player, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC_PASTE)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC_PASTE)) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } @@ -69,9 +56,8 @@ public class SchematicCmd extends SubCommand { final String location = args[1]; this.running = true; TaskManager.runTaskAsync(new Runnable() { - @Override - public void run() { - Schematic schematic; + @Override public void run() { + Schematic schematic = null; if (location.startsWith("url:")) { try { UUID uuid = UUID.fromString(location.substring(4)); @@ -80,29 +66,35 @@ public class SchematicCmd extends SubCommand { schematic = SchematicHandler.manager.getSchematic(url); } catch (Exception e) { e.printStackTrace(); - sendMessage(player, C.SCHEMATIC_INVALID, "non-existent url: " + location); + sendMessage(player, C.SCHEMATIC_INVALID, + "non-existent url: " + location); SchematicCmd.this.running = false; return; } } else { - schematic = SchematicHandler.manager.getSchematic(location); + try { + schematic = SchematicHandler.manager.getSchematic(location); + } catch (SchematicHandler.UnsupportedFormatException e) { + e.printStackTrace(); + } } if (schematic == null) { SchematicCmd.this.running = false; - sendMessage(player, C.SCHEMATIC_INVALID, "non-existent or not in gzip format"); + sendMessage(player, C.SCHEMATIC_INVALID, + "non-existent or not in gzip format"); return; } - SchematicHandler.manager.paste(schematic, plot, 0, 0, 0, true, new RunnableVal() { - @Override - public void run(Boolean value) { - SchematicCmd.this.running = false; - if (value) { - sendMessage(player, C.SCHEMATIC_PASTE_SUCCESS); - } else { - sendMessage(player, C.SCHEMATIC_PASTE_FAILED); + SchematicHandler.manager + .paste(schematic, plot, 0, 0, 0, true, new RunnableVal() { + @Override public void run(Boolean value) { + SchematicCmd.this.running = false; + if (value) { + sendMessage(player, C.SCHEMATIC_PASTE_SUCCESS); + } else { + sendMessage(player, C.SCHEMATIC_PASTE_FAILED); + } } - } - }); + }); } }); break; @@ -146,31 +138,35 @@ public class SchematicCmd extends SubCommand { return false; } if (args.length != 2) { - MainUtil.sendMessage(player, "&cNeed world argument. Use &7/plot sch exportall "); + MainUtil.sendMessage(player, + "&cNeed world argument. Use &7/plot sch exportall "); return false; } - PlotArea area = PS.get().getPlotAreaByString(args[1]); + PlotArea area = PlotSquared.get().getPlotAreaByString(args[1]); if (area == null) { C.NOT_VALID_PLOT_WORLD.send(player, args[1]); return false; } Collection plots = area.getPlots(); if (plots.isEmpty()) { - MainUtil.sendMessage(player, "&cInvalid world. Use &7/plot sch exportall "); + MainUtil + .sendMessage(player, "&cInvalid world. Use &7/plot sch exportall "); return false; } - boolean result = SchematicHandler.manager.exportAll(plots, null, null, new Runnable() { - @Override - public void run() { - MainUtil.sendMessage(player, "&aFinished mass export"); - } - }); + boolean result = + SchematicHandler.manager.exportAll(plots, null, null, new Runnable() { + @Override public void run() { + MainUtil.sendMessage(player, "&aFinished mass export"); + } + }); if (!result) { MainUtil.sendMessage(player, "&cTask is already running."); return false; } else { - MainUtil.sendMessage(player, "&3Plot&8->&3Schematic&8: &7Mass export has started. This may take a while."); - MainUtil.sendMessage(player, "&3Plot&8->&3Schematic&8: &7Found &c" + plots.size() + "&7 plots..."); + MainUtil.sendMessage(player, + "&3Plot&8->&3Schematic&8: &7Mass export has started. This may take a while."); + MainUtil.sendMessage(player, + "&3Plot&8->&3Schematic&8: &7Found &c" + plots.size() + "&7 plots..."); } break; } @@ -193,20 +189,21 @@ public class SchematicCmd extends SubCommand { MainUtil.sendMessage(player, C.PLOT_UNOWNED); return false; } - if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC_SAVE)) { + if (!plot.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC_SAVE)) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } location.getWorld(); Collection plots = new ArrayList<>(); plots.add(plot); - boolean result = SchematicHandler.manager.exportAll(plots, null, null, new Runnable() { - @Override - public void run() { - MainUtil.sendMessage(player, "&aFinished export"); - SchematicCmd.this.running = false; - } - }); + boolean result = + SchematicHandler.manager.exportAll(plots, null, null, new Runnable() { + @Override public void run() { + MainUtil.sendMessage(player, "&aFinished export"); + SchematicCmd.this.running = false; + } + }); if (!result) { MainUtil.sendMessage(player, "&cTask is already running."); return false; @@ -214,6 +211,16 @@ public class SchematicCmd extends SubCommand { MainUtil.sendMessage(player, "&7Starting export..."); } break; + case "list": { + if (!Permissions.hasPermission(player, C.PERMISSION_SCHEMATIC_LIST)) { + MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SCHEMATIC_LIST); + return false; + } + final String string = + StringMan.join(SchematicHandler.manager.getShematicNames(), "$2, $1"); + C.SCHEMATIC_LIST.send(player, string); + } + break; default: sendMessage(player, C.SCHEMATIC_MISSING_ARG); break; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Set.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Set.java new file mode 100644 index 000000000..8dd9ce8f1 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Set.java @@ -0,0 +1,166 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Configuration; +import com.github.intellectualsites.plotsquared.plot.config.Configuration.UnknownBlockException; +import com.github.intellectualsites.plotsquared.plot.flag.Flag; +import com.github.intellectualsites.plotsquared.plot.flag.FlagManager; +import com.github.intellectualsites.plotsquared.plot.flag.Flags; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; + +@CommandDeclaration(command = "set", description = "Set a plot value", aliases = { + "s"}, usage = "/plot set ", permission = "plots.set", category = CommandCategory.APPEARANCE, requiredType = RequiredType.NONE) +public class Set extends SubCommand { + + public static final String[] values = new String[] {"biome", "alias", "home", "flag"}; + public static final String[] aliases = new String[] {"b", "w", "wf", "f", "a", "h", "fl"}; + + private final SetCommand component; + + public Set() { + this.component = new SetCommand() { + + @Override public String getId() { + return "set.component"; + } + + @Override public boolean set(PlotPlayer player, final Plot plot, String value) { + PlotArea plotArea = player.getLocation().getPlotArea(); + PlotManager manager = player.getLocation().getPlotManager(); + String[] components = manager.getPlotComponents(plotArea, plot.getId()); + boolean allowUnsafe = DebugAllowUnsafe.unsafeAllowed.contains(player.getUUID()); + + String[] args = value.split(" "); + String material = + StringMan.join(Arrays.copyOfRange(args, 1, args.length), ",").trim(); + + for (String component : components) { + if (component.equalsIgnoreCase(args[0])) { + if (!Permissions + .hasPermission(player, C.PERMISSION_SET_COMPONENT.f(component))) { + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_SET_COMPONENT.f(component)); + return false; + } + // PlotBlock[] blocks; + BlockBucket bucket; + try { + if (args.length < 2) { + MainUtil.sendMessage(player, C.NEED_BLOCK); + return true; + } + String[] split = material.split(","); + // blocks = Configuration.BLOCKLIST.parseString(material); + + try { + bucket = Configuration.BLOCK_BUCKET.parseString(material); + } catch (final UnknownBlockException unknownBlockException) { + final String unknownBlock = unknownBlockException.getUnknownValue(); + C.NOT_VALID_BLOCK.send(player, unknownBlock); + StringComparison.ComparisonResult match = + WorldUtil.IMP.getClosestBlock(unknownBlock); + if (match != null) { + final String found = + WorldUtil.IMP.getClosestMatchingName(match.best); + if (found != null) { + MainUtil.sendMessage(player, C.DID_YOU_MEAN, + found.toLowerCase()); + } + } + return false; + } + + if (!allowUnsafe) { + for (final PlotBlock block : bucket.getBlocks()) { + if (!block.isAir() && !WorldUtil.IMP.isBlockSolid(block)) { + C.NOT_ALLOWED_BLOCK.send(player, block.toString()); + return false; + } + } + } + } catch (Exception ignored) { + MainUtil.sendMessage(player, C.NOT_VALID_BLOCK, material); + return false; + } + if (plot.getRunning() > 0) { + MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); + return false; + } + plot.addRunning(); + for (Plot current : plot.getConnectedPlots()) { + current.setComponent(component, bucket); + } + MainUtil.sendMessage(player, C.GENERATING_COMPONENT); + GlobalBlockQueue.IMP.addTask(new Runnable() { + @Override public void run() { + plot.removeRunning(); + } + }); + return true; + } + } + return false; + } + }; + } + + public boolean noArgs(PlotPlayer player) { + ArrayList newValues = new ArrayList<>(); + newValues.addAll(Arrays.asList("biome", "alias", "home", "flag")); + Plot plot = player.getCurrentPlot(); + if (plot != null) { + newValues.addAll( + Arrays.asList(plot.getManager().getPlotComponents(plot.getArea(), plot.getId()))); + } + MainUtil.sendMessage(player, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringMan + .join(newValues, C.BLOCK_LIST_SEPARATER.formatted())); + return false; + } + + @Override public boolean onCommand(PlotPlayer player, String[] args) { + if (args.length == 0) { + return noArgs(player); + } + Command cmd = MainCommand.getInstance().getCommand("set" + args[0]); + if (cmd != null) { + if (!Permissions.hasPermission(player, cmd.getPermission(), true)) { + return false; + } + cmd.execute(player, Arrays.copyOfRange(args, 1, args.length), null, null); + return true; + } + // Additional checks + Plot plot = player.getCurrentPlot(); + if (plot == null) { + MainUtil.sendMessage(player, C.NOT_IN_PLOT); + return false; + } + // components + HashSet components = new HashSet<>( + Arrays.asList(plot.getManager().getPlotComponents(plot.getArea(), plot.getId()))); + if (components.contains(args[0].toLowerCase())) { + return this.component.onCommand(player, Arrays.copyOfRange(args, 0, args.length)); + } + // flag + Flag flag = FlagManager.getFlag(args[0].toLowerCase()); + if (Flags.getFlags().contains(flag)) { + StringBuilder a = new StringBuilder(); + if (args.length > 1) { + for (int x = 1; x < args.length; x++) { + a.append(" ").append(args[x]); + } + } + MainCommand.onCommand(player, ("flag set " + args[0] + a.toString()).split(" ")); + return true; + } + return noArgs(player); + } +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/SetCommand.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SetCommand.java similarity index 52% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/SetCommand.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SetCommand.java index ced109a75..aaa1adfa2 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/SetCommand.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SetCommand.java @@ -1,17 +1,16 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.intellectualcrafters.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; public abstract class SetCommand extends SubCommand { - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { Location loc = player.getLocation(); Plot plot = loc.getPlotAbs(); if (plot == null) { @@ -19,14 +18,16 @@ public abstract class SetCommand extends SubCommand { } if (!plot.hasOwner()) { if (!Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND.f(getFullId()))) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_ADMIN_COMMAND.f(getFullId())); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_ADMIN_COMMAND.f(getFullId())); MainUtil.sendMessage(player, C.PLOT_NOT_CLAIMED); return false; } } if (!plot.isOwner(player.getUUID())) { if (!Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND.f(getFullId()))) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_ADMIN_COMMAND.f(getFullId())); + MainUtil.sendMessage(player, C.NO_PERMISSION, + C.PERMISSION_ADMIN_COMMAND.f(getFullId())); MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SetHome.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SetHome.java new file mode 100644 index 000000000..86f474cd0 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SetHome.java @@ -0,0 +1,39 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.BlockLoc; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; + +@CommandDeclaration(command = "sethome", permission = "plots.set.home", description = "Set the plot home to your current position", usage = "/plot sethome [none]", aliases = { + "sh", "seth"}, category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE) +public class SetHome extends SetCommand { + + @Override public boolean set(PlotPlayer player, Plot plot, String value) { + switch (value.toLowerCase()) { + case "unset": + case "reset": + case "remove": + case "none": { + Plot base = plot.getBasePlot(false); + base.setHome(null); + return MainUtil.sendMessage(player, C.POSITION_UNSET); + } + case "": + Plot base = plot.getBasePlot(false); + Location bot = base.getBottomAbs(); + Location loc = player.getLocationFull(); + BlockLoc rel = + new BlockLoc(loc.getX() - bot.getX(), loc.getY(), loc.getZ() - bot.getZ(), + loc.getYaw(), loc.getPitch()); + base.setHome(rel); + return MainUtil.sendMessage(player, C.POSITION_SET); + default: + MainUtil.sendMessage(player, C.HOME_ARGUMENT); + return false; + } + } +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Setup.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Setup.java similarity index 64% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Setup.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Setup.java index 6e2019ff6..2b79fd8af 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Setup.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Setup.java @@ -1,38 +1,32 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.ConfigurationNode; -import com.intellectualcrafters.plot.generator.GeneratorWrapper; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotId; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.SetupObject; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.SetupUtils; -import com.intellectualcrafters.plot.util.StringMan; -import com.intellectualcrafters.plot.util.WorldUtil; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.ConfigurationNode; +import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.SetupObject; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map.Entry; -@CommandDeclaration( - command = "setup", - permission = "plots.admin.command.setup", - description = "Setup wizard for plot worlds", - usage = "/plot setup", - aliases = {"create"}, - category = CommandCategory.ADMINISTRATION) -public class Setup extends SubCommand { +@CommandDeclaration(command = "setup", permission = "plots.admin.command.setup", description = "Setup wizard for plot worlds", usage = "/plot setup", aliases = { + "create"}, category = CommandCategory.ADMINISTRATION) public class Setup extends SubCommand { public void displayGenerators(PlotPlayer player) { StringBuilder message = new StringBuilder(); message.append("&6What generator do you want?"); for (Entry> entry : SetupUtils.generators.entrySet()) { - if (entry.getKey().equals(PS.imp().getPluginName())) { + if (entry.getKey().equals(PlotSquared.imp().getPluginName())) { message.append("\n&8 - &2").append(entry.getKey()).append(" (Default Generator)"); } else if (entry.getValue().isFull()) { message.append("\n&8 - &7").append(entry.getKey()).append(" (Plot Generator)"); @@ -43,8 +37,7 @@ public class Setup extends SubCommand { MainUtil.sendMessage(player, message.toString()); } - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { // going through setup SetupObject object = player.getMeta("setup"); if (object == null) { @@ -65,8 +58,8 @@ public class Setup extends SubCommand { if (object.setup_index > 0) { object.setup_index--; ConfigurationNode node = object.step[object.setup_index]; - sendMessage(player, C.SETUP_STEP, object.setup_index + 1, node.getDescription(), node.getType().getType(), - String.valueOf(node.getDefaultValue())); + sendMessage(player, C.SETUP_STEP, object.setup_index + 1, node.getDescription(), + node.getType().getType(), String.valueOf(node.getDefaultValue())); return false; } else if (object.current > 0) { object.current--; @@ -78,20 +71,25 @@ public class Setup extends SubCommand { case 0: // choose generator if (args.length != 1 || !SetupUtils.generators.containsKey(args[0])) { String prefix = "\n&8 - &7"; - MainUtil.sendMessage(player, "&cYou must choose a generator!" + prefix + StringMan.join(SetupUtils.generators.keySet(), prefix) - .replaceAll(PS.imp().getPluginName(), "&2" + PS.imp().getPluginName())); + MainUtil.sendMessage(player, + "&cYou must choose a generator!" + prefix + StringMan + .join(SetupUtils.generators.keySet(), prefix) + .replaceAll(PlotSquared.imp().getPluginName(), + "&2" + PlotSquared.imp().getPluginName())); sendMessage(player, C.SETUP_INIT); return false; } object.setupGenerator = args[0]; object.current++; String partial = "\n&8 - &7PARTIAL&8 - &7Vanilla with clusters of plots"; - MainUtil.sendMessage(player, "&6What world type do you want?\n&8 - &2DEFAULT&8 - &7Standard plot generation" + MainUtil.sendMessage(player, + "&6What world type do you want?\n&8 - &2DEFAULT&8 - &7Standard plot generation" + "\n&8 - &7AUGMENTED&8 - &7Plot generation with terrain" + partial); break; case 1: // choose world type List allTypes = Arrays.asList("default", "augmented", "partial"); - List allDesc = Arrays.asList("Standard plot generation", "Plot generation with vanilla terrain", + List allDesc = Arrays + .asList("Standard plot generation", "Plot generation with vanilla terrain", "Vanilla with clusters of plots"); ArrayList types = new ArrayList<>(); if (SetupUtils.generators.get(object.setupGenerator).isFull()) { @@ -104,9 +102,11 @@ public class Setup extends SubCommand { for (String type : types) { int i = allTypes.indexOf(type); if (type.equals("default")) { - MainUtil.sendMessage(player, "&8 - &2" + type + " &8-&7 " + allDesc.get(i)); + MainUtil + .sendMessage(player, "&8 - &2" + type + " &8-&7 " + allDesc.get(i)); } else { - MainUtil.sendMessage(player, "&8 - &7" + type + " &8-&7 " + allDesc.get(i)); + MainUtil + .sendMessage(player, "&8 - &7" + type + " &8-&7 " + allDesc.get(i)); } } return false; @@ -117,9 +117,12 @@ public class Setup extends SubCommand { object.current = 6; if (object.step == null) { object.plotManager = object.setupGenerator; - object.step = SetupUtils.generators.get(object.plotManager).getPlotGenerator() - .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null).getSettingNodes(); - SetupUtils.generators.get(object.plotManager).getPlotGenerator().processSetup(object); + object.step = + SetupUtils.generators.get(object.plotManager).getPlotGenerator() + .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null) + .getSettingNodes(); + SetupUtils.generators.get(object.plotManager).getPlotGenerator() + .processSetup(object); } if (object.step.length == 0) { MainUtil.sendMessage(player, "&6What do you want your world to be called?"); @@ -127,31 +130,38 @@ public class Setup extends SubCommand { return true; } ConfigurationNode step = object.step[object.setup_index]; - sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), step.getType().getType(), - String.valueOf(step.getDefaultValue())); + sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), + step.getType().getType(), String.valueOf(step.getDefaultValue())); } else { if (gen.isFull()) { object.plotManager = object.setupGenerator; object.setupGenerator = null; - object.step = SetupUtils.generators.get(object.plotManager).getPlotGenerator() - .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null).getSettingNodes(); - SetupUtils.generators.get(object.plotManager).getPlotGenerator().processSetup(object); + object.step = + SetupUtils.generators.get(object.plotManager).getPlotGenerator() + .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null) + .getSettingNodes(); + SetupUtils.generators.get(object.plotManager).getPlotGenerator() + .processSetup(object); } else { - object.plotManager = PS.imp().getPluginName(); - MainUtil.sendMessage(player, "&c[WARNING] The specified generator does not identify as BukkitPlotGenerator"); - MainUtil.sendMessage(player, "&7 - You may need to manually configure the other plugin"); - object.step = SetupUtils.generators.get(object.plotManager).getPlotGenerator() - .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null).getSettingNodes(); + object.plotManager = PlotSquared.imp().getPluginName(); + MainUtil.sendMessage(player, + "&c[WARNING] The specified generator does not identify as BukkitPlotGenerator"); + MainUtil.sendMessage(player, + "&7 - You may need to manually configure the other plugin"); + object.step = + SetupUtils.generators.get(object.plotManager).getPlotGenerator() + .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null) + .getSettingNodes(); } if (object.type == 2) { MainUtil.sendMessage(player, "What would you like this area called?"); object.current++; } else { MainUtil.sendMessage(player, "&6What terrain would you like in plots?" - + "\n&8 - &2NONE&8 - &7No terrain at all" - + "\n&8 - &7ORE&8 - &7Just some ore veins and trees" - + "\n&8 - &7ROAD&8 - &7Terrain separated by roads" - + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); + + "\n&8 - &2NONE&8 - &7No terrain at all" + + "\n&8 - &7ORE&8 - &7Just some ore veins and trees" + + "\n&8 - &7ROAD&8 - &7Terrain separated by roads" + + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); object.current = 5; } } @@ -161,9 +171,10 @@ public class Setup extends SubCommand { MainUtil.sendMessage(player, "&cThe area id must be alphanumerical!"); return false; } - for (PlotArea area : PS.get().getPlotAreas()) { + for (PlotArea area : PlotSquared.get().getPlotAreas()) { if (area.id != null && area.id.equalsIgnoreCase(args[0])) { - MainUtil.sendMessage(player, "&cYou must choose an area id that is not in use!"); + MainUtil.sendMessage(player, + "&cYou must choose an area id that is not in use!"); return false; } } @@ -188,22 +199,23 @@ public class Setup extends SubCommand { return false; } if (id.x <= object.min.x || id.y <= object.min.y) { - MainUtil.sendMessage(player, "&cThe max PlotId must be greater than the minimum!"); + MainUtil + .sendMessage(player, "&cThe max PlotId must be greater than the minimum!"); return false; } object.max = id; object.current++; MainUtil.sendMessage(player, "&6What terrain would you like in plots?" - + "\n&8 - &2NONE&8 - &7No terrain at all" - + "\n&8 - &7ORE&8 - &7Just some ore veins and trees" - + "\n&8 - &7ROAD&8 - &7Terrain separated by roads" - + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); + + "\n&8 - &2NONE&8 - &7No terrain at all" + + "\n&8 - &7ORE&8 - &7Just some ore veins and trees" + + "\n&8 - &7ROAD&8 - &7Terrain separated by roads" + + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); break; case 5: { // Choose terrain List terrain = Arrays.asList("none", "ore", "road", "all"); if (args.length != 1 || !terrain.contains(args[0].toLowerCase())) { - MainUtil.sendMessage(player, "&cYou must choose the terrain!" - + "\n&8 - &2NONE&8 - &7No terrain at all" + MainUtil.sendMessage(player, + "&cYou must choose the terrain!" + "\n&8 - &2NONE&8 - &7No terrain at all" + "\n&8 - &7ORE&8 - &7Just some ore veins and trees" + "\n&8 - &7ROAD&8 - &7Terrain separated by roads" + "\n&8 - &7ALL&8 - &7Entirely vanilla generation"); @@ -213,11 +225,12 @@ public class Setup extends SubCommand { object.current++; if (object.step == null) { object.step = SetupUtils.generators.get(object.plotManager).getPlotGenerator() - .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null).getSettingNodes(); + .getNewPlotArea("CheckingPlotSquaredGenerator", null, null, null) + .getSettingNodes(); } ConfigurationNode step = object.step[object.setup_index]; - sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), step.getType().getType(), - String.valueOf(step.getDefaultValue())); + sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), + step.getType().getType(), String.valueOf(step.getDefaultValue())); break; } case 6: // world setup @@ -229,8 +242,8 @@ public class Setup extends SubCommand { } ConfigurationNode step = object.step[object.setup_index]; if (args.length < 1) { - sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), step.getType().getType(), - String.valueOf(step.getDefaultValue())); + sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), + step.getType().getType(), String.valueOf(step.getDefaultValue())); return false; } boolean valid = step.isValid(args[0]); @@ -243,13 +256,13 @@ public class Setup extends SubCommand { return false; } step = object.step[object.setup_index]; - sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), step.getType().getType(), - String.valueOf(step.getDefaultValue())); + sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), + step.getType().getType(), String.valueOf(step.getDefaultValue())); return false; } else { sendMessage(player, C.SETUP_INVALID_ARG, args[0], step.getConstant()); - sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), step.getType().getType(), - String.valueOf(step.getDefaultValue())); + sendMessage(player, C.SETUP_STEP, object.setup_index + 1, step.getDescription(), + step.getType().getType(), String.valueOf(step.getDefaultValue())); return false; } case 7: @@ -258,13 +271,14 @@ public class Setup extends SubCommand { return false; } if (WorldUtil.IMP.isWorld(args[0])) { - if (PS.get().hasPlotArea(args[0])) { + if (PlotSquared.get().hasPlotArea(args[0])) { MainUtil.sendMessage(player, "&cThat world name is already taken!"); return false; } MainUtil.sendMessage(player, - "&cThe world you specified already exists. After restarting, new terrain will use " + PS.imp().getPluginName() + ", however you may need to " - + "reset the world for it to generate correctly!"); + "&cThe world you specified already exists. After restarting, new terrain will use " + + PlotSquared.imp().getPluginName() + ", however you may need to " + + "reset the world for it to generate correctly!"); } object.world = args[0]; player.deleteMeta("setup"); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SubCommand.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SubCommand.java new file mode 100644 index 000000000..396185e29 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SubCommand.java @@ -0,0 +1,39 @@ +package com.github.intellectualsites.plotsquared.plot.commands; + +import com.github.intellectualsites.plotsquared.commands.Argument; +import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; + +/** + * SubCommand class + * + * @Deprecated In favor of normal Command class + * @see Command(Command, boolean) + */ +public abstract class SubCommand extends Command { + public SubCommand() { + super(MainCommand.getInstance(), true); + } + + public SubCommand(Argument... arguments) { + this(); + setRequiredArguments(arguments); + } + + @Override public void execute(PlotPlayer player, String[] args, + RunnableVal3 confirm, + RunnableVal2 whenDone) { + onCommand(player, args); + } + + + public abstract boolean onCommand(PlotPlayer player, String[] args); + + public boolean sendMessage(PlotPlayer player, C message, Object... args) { + message.send(player, args); + return true; + } +} diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Swap.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Swap.java similarity index 55% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Swap.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Swap.java index d1871f6b3..4ee9f817c 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Swap.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Swap.java @@ -1,29 +1,25 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.Permissions; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; -@CommandDeclaration(usage = "/plot swap ", - command = "swap", - description = "Swap two plots", - aliases = {"switch"}, - category = CommandCategory.CLAIMING, - requiredType = RequiredType.NONE) +@CommandDeclaration(usage = "/plot swap ", command = "swap", description = "Swap two plots", aliases = { + "switch"}, category = CommandCategory.CLAIMING, requiredType = RequiredType.NONE) public class Swap extends SubCommand { - @Override - public boolean onCommand(final PlotPlayer player, String[] args) { + @Override public boolean onCommand(final PlotPlayer player, String[] args) { Location loc = player.getLocation(); Plot plot1 = loc.getPlotAbs(); if (plot1 == null) { return !MainUtil.sendMessage(player, C.NOT_IN_PLOT); } - if (!plot1.isOwner(player.getUUID()) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN.s())) { + if (!plot1.isOwner(player.getUUID()) && !Permissions + .hasPermission(player, C.PERMISSION_ADMIN.s())) { MainUtil.sendMessage(player, C.NO_PLOT_PERMS); return false; } @@ -45,8 +41,7 @@ public class Swap extends SubCommand { return false; } if (plot1.move(plot2, new Runnable() { - @Override - public void run() { + @Override public void run() { MainUtil.sendMessage(player, C.SWAP_SUCCESS); } }, true)) { diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Target.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Target.java similarity index 50% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Target.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Target.java index 6cfae47cc..b378f9be4 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Target.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Target.java @@ -1,30 +1,23 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.object.Location; -import com.intellectualcrafters.plot.object.Plot; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.StringMan; -import com.plotsquared.general.commands.Argument; -import com.plotsquared.general.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.commands.Argument; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; -@CommandDeclaration( - command = "target", - usage = "/plot target <|nearest>", - description = "Target a plot with your compass", - permission = "plots.target", - requiredType = RequiredType.PLAYER, - category = CommandCategory.INFO) +@CommandDeclaration(command = "target", usage = "/plot target <|nearest>", description = "Target a plot with your compass", permission = "plots.target", requiredType = RequiredType.PLAYER, category = CommandCategory.INFO) public class Target extends SubCommand { public Target() { super(Argument.PlotID); } - @Override - public boolean onCommand(PlotPlayer player, String[] args) { + @Override public boolean onCommand(PlotPlayer player, String[] args) { Location location = player.getLocation(); if (!location.isPlotArea()) { MainUtil.sendMessage(player, C.NOT_IN_PLOT_WORLD); @@ -33,7 +26,7 @@ public class Target extends SubCommand { Plot target = null; if (StringMan.isEqualIgnoreCaseToAny(args[0], "near", "nearest")) { int distance = Integer.MAX_VALUE; - for (Plot plot : PS.get().getPlots(location.getWorld())) { + for (Plot plot : PlotSquared.get().getPlots(location.getWorld())) { double current = plot.getCenter().getEuclideanDistanceSquared(location); if (current < distance) { distance = (int) current; diff --git a/Core/src/main/java/com/intellectualcrafters/plot/commands/Template.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Template.java similarity index 62% rename from Core/src/main/java/com/intellectualcrafters/plot/commands/Template.java rename to Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Template.java index 86102a444..5c7e2d100 100644 --- a/Core/src/main/java/com/intellectualcrafters/plot/commands/Template.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Template.java @@ -1,49 +1,38 @@ -package com.intellectualcrafters.plot.commands; +package com.github.intellectualsites.plotsquared.plot.commands; -import com.intellectualcrafters.configuration.ConfigurationSection; -import com.intellectualcrafters.configuration.InvalidConfigurationException; -import com.intellectualcrafters.configuration.file.YamlConfiguration; -import com.intellectualcrafters.plot.PS; -import com.intellectualcrafters.plot.config.C; -import com.intellectualcrafters.plot.config.ConfigurationNode; -import com.intellectualcrafters.plot.config.Settings; -import com.intellectualcrafters.plot.object.FileBytes; -import com.intellectualcrafters.plot.object.PlotArea; -import com.intellectualcrafters.plot.object.PlotManager; -import com.intellectualcrafters.plot.object.PlotPlayer; -import com.intellectualcrafters.plot.object.SetupObject; -import com.intellectualcrafters.plot.util.MainUtil; -import com.intellectualcrafters.plot.util.SetupUtils; -import com.intellectualcrafters.plot.util.TaskManager; -import com.intellectualcrafters.plot.util.WorldUtil; -import com.intellectualcrafters.plot.util.block.GlobalBlockQueue; -import com.plotsquared.general.commands.CommandDeclaration; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; +import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; +import com.github.intellectualsites.plotsquared.configuration.ConfigurationSection; +import com.github.intellectualsites.plotsquared.configuration.InvalidConfigurationException; +import com.github.intellectualsites.plotsquared.configuration.file.YamlConfiguration; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.ConfigurationNode; +import com.github.intellectualsites.plotsquared.plot.config.Settings; +import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.SetupUtils; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; +import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; + +import java.io.*; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; -@CommandDeclaration( - command = "template", - permission = "plots.admin", - description = "Create or use a world template", - usage = "/plot template [import|export]