diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 5b2fa30d2..91ba21cb9 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,22 +1,30 @@ +__*NOTICE: Bukkit/Spigot versions 1.7.10 to 1.12.2 are considered legacy and will receive limited support. Please consider upgrading to 1.13 for future support. Plugins exist for 1.13+ that bring back old behaviors found in 1.8*__ # Bug report template -**Debug paste link:** - +**[REQUIRED] PlotSquared Version Number:** -**Description of the problem:** +**[REQUIRED] Spigot/Paper Version Number:** +**[REQUIRED] Minecraft Version Number:** + +**Links to worlds.yml file and settings.yml file:** + + +**[REQUIRED] Description of the problem:** + +**Any relevant console output or screenshots:** + +**Plugins being used on the server:** + **How to replicate:** **Checklist**: -- [] I included a `/plot debugpaste` link +- [] I included all information required in the sections above - [] I made sure there are no duplicates of this report [(Use Search)](https://github.com/IntellectualSites/PlotSquared/issues?utf8=%E2%9C%93&q=is%3Aissue) - [] I made sure I am using an up-to-date version of PlotSquared -- [] I Made sure the bug/error is not caused by any other plugin - - - +- [] I made sure the bug/error is not caused by any other plugin diff --git a/.github/auto-comment.yml b/.github/auto-comment.yml index 4aef8cae8..f7584d42e 100644 --- a/.github/auto-comment.yml +++ b/.github/auto-comment.yml @@ -2,7 +2,7 @@ issueOpened: > Thank your for raising a issue. We will try and get back to you as soon as possible. - Please make sure that you followed the issue template, and provied all neccessary information. + Please make sure that you followed the issue template, and provided all neccessary information. Failure to do so will prevent us from resolving the issue in a timely manner. Please note that suggestions are now to be submitted to https://git.io/fN5B4 rather than this issue tracker! diff --git a/.gitignore b/.gitignore index f55b143d2..68823d640 100644 --- a/.gitignore +++ b/.gitignore @@ -139,4 +139,5 @@ checkstyle.xml classes/ p2error.txt *.bat -Nukkit/build/resources/main/plugin.yml \ No newline at end of file +Nukkit/build/resources/main/plugin.yml +docs/ diff --git a/Bukkit/build.gradle b/Bukkit/build.gradle index e6a9117bb..9d00d7b99 100644 --- a/Bukkit/build.gradle +++ b/Bukkit/build.gradle @@ -1,6 +1,6 @@ repositories { maven { url "https://hub.spigotmc.org/nexus/content/repositories/snapshots/" } - maven { url = "https://oss.sonatype.org/content/repositories/snapshots/" } + maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } maven { url "http://nexus.hc.to/content/repositories/pub_releases" } maven { url = "https://repo.codemc.org/repository/maven-public" } maven { @@ -11,16 +11,16 @@ repositories { } dependencies { + implementation project(':Core') compile project(':Core') - testCompile project(':Core') - compile 'org.spigotmc:spigot-api:1.13.2-R0.1-SNAPSHOT' - compile(group: 'com.sk89q.worldedit', name: 'worldedit-bukkit', version: '7.0.0-SNAPSHOT') - compile(group: 'org.bstats', name: 'bstats-bukkit', version: '1.4') + compile 'com.destroystokyo.paper:paper-api:1.14.3-R0.1-SNAPSHOT' + //implementation 'com.onarandombox.multiversecore:Multiverse-Core:3.0.0-SNAPSHOT' + implementation 'org.spigotmc:spigot-api:1.14.3-R0.1-SNAPSHOT' + compile(group: 'com.sk89q.worldedit', name: 'worldedit-bukkit', version: '7.0.0') compile "io.papermc:paperlib:1.0.1" compile("net.milkbowl.vault:VaultAPI:1.7") { exclude module: 'bukkit' } - compile 'org.spigotmc:spigot-api:1.13.2-R0.1-SNAPSHOT' } sourceCompatibility = 1.8 @@ -41,7 +41,12 @@ jar.enabled = false shadowJar { dependencies { include(dependency(':Core')) - include(dependency('org.bstats:bstats-bukkit:1.4')) + // update notification stuff + include(dependency('com.github.Sauilitired:Jenkins4J:2.0-SNAPSHOT')) + include(dependency('com.squareup.retrofit2:retrofit:2.4.0')) + include(dependency('com.squareup.okhttp3:okhttp:3.14.0')) + include(dependency('com.squareup.okio:okio:2.2.2')) + include(dependency('org.jetbrains.kotlin:kotlin-stdlib:1.3.30')) include(dependency("io.papermc:paperlib:1.0.1")) } relocate 'io.papermc.lib', 'com.github.intellectualsites.plotsquared.bukkit.paperlib' diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/BukkitMain.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/BukkitMain.java index bc8fb225e..89bd5678b 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/BukkitMain.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/BukkitMain.java @@ -9,7 +9,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.ConfigurationNode; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; @@ -42,8 +42,19 @@ import org.bukkit.generator.ChunkGenerator; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; +import org.jetbrains.annotations.NotNull; + +import javax.annotation.Nullable; +import java.io.File; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.UUID; + +import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass; import javax.annotation.Nullable; import java.io.File; @@ -57,25 +68,10 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain @Getter private static WorldEdit worldEdit; static { - // Disable AWE as otherwise both fail to load - PluginManager manager = Bukkit.getPluginManager(); try { Settings.load(new File("plugins/PlotSquared/config/settings.yml")); } catch (Throwable ignored) { } - // Force WorldEdit to load - try { - System.out.println("[P2] Force loading WorldEdit"); - if (!manager.isPluginEnabled("WorldEdit")) { - manager.enablePlugin(WorldEditPlugin.getPlugin(WorldEditPlugin.class)); - } - System.out.println("[P2] Testing platform capabilities"); - WorldEdit.getInstance().getPlatformManager().queryCapability(Capability.GAME_HOOKS); - } catch (final Throwable throwable) { - throw new IllegalStateException( - "Failed to force load WorldEdit." + " Road schematics will fail to generate", - throwable); - } } private final LegacyMappings legacyMappings = new BukkitLegacyMappings(); @@ -115,17 +111,54 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain @Override public void onEnable() { this.pluginName = getDescription().getName(); - getServer().getName(); - PlotPlayer.registerConverter(Player.class, BukkitUtil::getPlayer); PaperLib.suggestPaper(this); new PlotSquared(this, "Bukkit"); - if (Settings.Enabled_Components.METRICS) { - this.startMetrics(); - } else { - PlotSquared.log(C.CONSOLE_PLEASE_ENABLE_METRICS.f(getPluginName())); + + if (PlotSquared.get().IMP.getServerVersion()[1] < 13) { + System.out.println( + "You can't use this version of PlotSquared on a server less than Minecraft 1.13.2."); + System.out + .println("Please check the download page for the link to the legacy versions."); + System.out.println("The server will now be shutdown to prevent any corruption."); + Bukkit.shutdown(); + return; } + + // Check for updates + if (PlotSquared.get().getUpdateUtility() != null) { + final UpdateUtility updateUtility = PlotSquared.get().getUpdateUtility(); + updateUtility + .checkForUpdate(this.getPluginVersionString(), ((updateDescription, throwable) -> { + Bukkit.getScheduler().runTask(BukkitMain.this, () -> { + getLogger().info("-------- PlotSquared Update Check --------"); + if (throwable != null) { + getLogger().severe(String + .format("Could not check for update. Reason: %s", + throwable.getMessage())); + } else { + if (updateDescription == null) { + getLogger().info( + "You appear to be running the latest version of PlotSquared. Congratulations!"); + } else { + getLogger() + .info("There appears to be a PlotSquared update available!"); + getLogger().info(String.format("You are running version %s," + + " the newest available version is %s", + getPluginVersionString(), updateDescription.getVersion())); + getLogger().info( + String.format("Update URL: %s", updateDescription.getUrl())); + } + } + getLogger().info("-------- PlotSquared Update Check --------"); + }); + })); + } else { + getLogger().warning("Update checking disabled. Skipping."); + } + + this.startMetrics(); if (Settings.Enabled_Components.WORLDS) { TaskManager.IMP.taskRepeat(this::unload, 20); try { @@ -165,46 +198,49 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain continue; } - final PlotId id = PlotId.fromString(name); - if (id != null) { - final Plot plot = area.getOwnedPlot(id); - if (plot != null) { - if (PlotPlayer.wrap(plot.owner) == null) { - if (world.getKeepSpawnInMemory()) { - world.setKeepSpawnInMemory(false); - return; + PlotId id; + try { + id = PlotId.fromString(name); + } catch (IllegalArgumentException ignored) { + continue; + } + final Plot plot = area.getOwnedPlot(id); + if (plot != null) { + if (!MainUtil.isServerOwned(plot) || PlotPlayer.wrap(plot.getOwner()) == null) { + if (world.getKeepSpawnInMemory()) { + world.setKeepSpawnInMemory(false); + return; + } + final Chunk[] chunks = world.getLoadedChunks(); + if (chunks.length == 0) { + if (!Bukkit.unloadWorld(world, true)) { + PlotSquared.debug("Failed to unload " + world.getName()); } - final Chunk[] chunks = world.getLoadedChunks(); - if (chunks.length == 0) { - if (!Bukkit.unloadWorld(world, true)) { - PlotSquared.debug("Failed to unload " + world.getName()); - } - return; - } else { - int index = 0; - do { - final Chunk chunkI = chunks[index++]; - boolean result; - if (methodUnloadChunk0 != null) { - try { - 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); - } - if (!result) { + return; + } else { + int index = 0; + do { + final Chunk chunkI = chunks[index++]; + boolean result; + if (methodUnloadChunk0 != null) { + try { + result = (boolean) methodUnloadChunk0 + .invoke(world, chunkI.getX(), chunkI.getZ(), true); + } catch (Throwable e) { + methodUnloadChunk0 = null; + e.printStackTrace(); continue outer; } - } while (index < chunks.length - && System.currentTimeMillis() - start < 5); - return; - } + } else { + result = world.unloadChunk(chunkI.getX(), chunkI.getZ(), true); + } + if (!result) { + continue outer; + } + if (System.currentTimeMillis() - start > 5) { + return; + } + } while (index < chunks.length); } } } @@ -219,7 +255,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain @Override public void log(@NonNull String message) { try { - message = C.color(message); + message = Captions.color(message); if (!Settings.Chat.CONSOLE_COLOR) { message = ChatColor.stripColor(message); } @@ -233,10 +269,6 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain this.getServer().getPluginManager().disablePlugin(this); } - @Override public void disable() { - onDisable(); - } - @Override public int[] getPluginVersion() { String ver = getDescription().getVersion(); if (ver.contains("-")) { @@ -272,276 +304,266 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain } @Override @SuppressWarnings("deprecation") public void runEntityTask() { - PlotSquared.log(C.PREFIX + "KillAllEntities started."); - TaskManager - .runTaskRepeat(() -> PlotSquared.get().foreachPlotArea(new RunnableVal() { - @Override public void run(PlotArea plotArea) { - final World world = Bukkit.getWorld(plotArea.worldname); - try { - if (world == null) { - return; - } - List entities = world.getEntities(); - Iterator iterator = entities.iterator(); - while (iterator.hasNext()) { - Entity entity = iterator.next(); - switch (entity.getType()) { - case EGG: - case COMPLEX_PART: - case FISHING_HOOK: - case ENDER_SIGNAL: - case LINGERING_POTION: - case AREA_EFFECT_CLOUD: - case EXPERIENCE_ORB: - case LEASH_HITCH: - case FIREWORK: - case WEATHER: - case LIGHTNING: - case WITHER_SKULL: - case UNKNOWN: - case PLAYER: - // non moving / unmovable + PlotSquared.log(Captions.PREFIX + "KillAllEntities started."); + TaskManager.runTaskRepeat(() -> PlotSquared.get().forEachPlotArea(plotArea -> { + final World world = Bukkit.getWorld(plotArea.worldname); + try { + if (world == null) { + return; + } + List entities = world.getEntities(); + Iterator iterator = entities.iterator(); + while (iterator.hasNext()) { + Entity entity = iterator.next(); + switch (entity.getType()) { + case EGG: + case FISHING_HOOK: + case ENDER_SIGNAL: + case AREA_EFFECT_CLOUD: + case EXPERIENCE_ORB: + case LEASH_HITCH: + case FIREWORK: + case LIGHTNING: + case WITHER_SKULL: + case UNKNOWN: + case PLAYER: + // non moving / unmovable + continue; + case THROWN_EXP_BOTTLE: + case SPLASH_POTION: + case SNOWBALL: + case SHULKER_BULLET: + case SPECTRAL_ARROW: + case ENDER_PEARL: + case ARROW: + case LLAMA_SPIT: + case TRIDENT: + // managed elsewhere | projectile + continue; + case ITEM_FRAME: + case PAINTING: + // Not vehicles + continue; + case ARMOR_STAND: + // Temporarily classify as vehicle + case MINECART: + case MINECART_CHEST: + case MINECART_COMMAND: + case MINECART_FURNACE: + case MINECART_HOPPER: + case MINECART_MOB_SPAWNER: + case ENDER_CRYSTAL: + case MINECART_TNT: + case BOAT: + if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) { + 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(); + } continue; - case THROWN_EXP_BOTTLE: - case SPLASH_POTION: - case SNOWBALL: - case SHULKER_BULLET: - case SPECTRAL_ARROW: - case TIPPED_ARROW: - case ENDER_PEARL: - case ARROW: - case LLAMA_SPIT: - case TRIDENT: - // managed elsewhere | projectile + } + List meta = entity.getMetadata("plot"); + if (meta.isEmpty()) { continue; - case ITEM_FRAME: - case PAINTING: - // Not vehicles - continue; - case ARMOR_STAND: - // Temporarily classify as vehicle - case MINECART: - case MINECART_CHEST: - case MINECART_COMMAND: - case MINECART_FURNACE: - case MINECART_HOPPER: - case MINECART_MOB_SPAWNER: - case ENDER_CRYSTAL: - case MINECART_TNT: - case BOAT: - if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) { + } + Plot origin = (Plot) meta.get(0).value(); + if (!plot.equals(origin.getBasePlot(false))) { + if (entity.hasMetadata("ps-tmp-teleport")) { + continue; + } + iterator.remove(); + entity.remove(); + } + } + continue; + case SMALL_FIREBALL: + case FIREBALL: + case DRAGON_FIREBALL: + case DROPPED_ITEM: + if (Settings.Enabled_Components.KILL_ROAD_ITEMS && plotArea + .getOwnedPlotAbs(BukkitUtil.getLocation(entity.getLocation())) + == null) { + entity.remove(); + } + // dropped item + continue; + case PRIMED_TNT: + case FALLING_BLOCK: + // managed elsewhere + continue; + case SHULKER: + if (Settings.Enabled_Components.KILL_ROAD_MOBS) { + LivingEntity livingEntity = (LivingEntity) entity; + List meta = entity.getMetadata("shulkerPlot"); + if (!meta.isEmpty()) { + if (livingEntity.isLeashed()) { + continue; + } + List keep = entity.getMetadata("keep"); + if (!keep.isEmpty()) { + continue; + } + + PlotId originalPlotId = (PlotId) meta.get(0).value(); + if (originalPlotId != null) { com.github.intellectualsites.plotsquared.plot.object.Location - location = BukkitUtil.getLocation(entity.getLocation()); - Plot plot = location.getPlot(); - if (plot == null) { - if (location.isPlotArea()) { + 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)))) { if (entity.hasMetadata("ps-tmp-teleport")) { continue; } iterator.remove(); entity.remove(); } - continue; } - List meta = entity.getMetadata("plot"); - if (meta.isEmpty()) { - continue; + } + } else { + //This is to apply the metadata to already spawned shulkers (see EntitySpawnListener.java) + 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 (currentPlotId != null) { + entity.setMetadata("shulkerPlot", new FixedMetadataValue( + (Plugin) PlotSquared.get().IMP, currentPlotId)); } - Plot origin = (Plot) meta.get(0).value(); - if (!plot.equals(origin.getBasePlot(false))) { + } + } + } + continue; + case LLAMA: + case DONKEY: + case MULE: + case ZOMBIE_HORSE: + case SKELETON_HORSE: + case HUSK: + case ELDER_GUARDIAN: + case WITHER_SKELETON: + case STRAY: + case ZOMBIE_VILLAGER: + case EVOKER: + case EVOKER_FANGS: + case VEX: + case VINDICATOR: + case POLAR_BEAR: + case BAT: + case BLAZE: + case CAVE_SPIDER: + case CHICKEN: + case COW: + case CREEPER: + case ENDERMAN: + case ENDERMITE: + case ENDER_DRAGON: + case GHAST: + case GIANT: + case GUARDIAN: + case HORSE: + case IRON_GOLEM: + case MAGMA_CUBE: + case MUSHROOM_COW: + case OCELOT: + case PIG: + case PIG_ZOMBIE: + case RABBIT: + case SHEEP: + case SILVERFISH: + case SKELETON: + case SLIME: + case SNOWMAN: + case SPIDER: + case SQUID: + case VILLAGER: + case WITCH: + case WITHER: + case WOLF: + case ZOMBIE: + case PARROT: + case SALMON: + case DOLPHIN: + case TROPICAL_FISH: + case DROWNED: + case COD: + case TURTLE: + case PUFFERFISH: + case PHANTOM: + case ILLUSIONER: + default: { + if (Settings.Enabled_Components.KILL_ROAD_MOBS) { + Location location = entity.getLocation(); + if (BukkitUtil.getLocation(location).isPlotRoad()) { + if (entity instanceof LivingEntity) { + LivingEntity livingEntity = (LivingEntity) entity; + if (!livingEntity.isLeashed() || !entity + .hasMetadata("keep")) { + Entity passenger = entity.getPassenger(); + if (!(passenger instanceof Player) && entity + .getMetadata("keep").isEmpty()) { + if (entity.hasMetadata("ps-tmp-teleport")) { + continue; + } + iterator.remove(); + entity.remove(); + continue; + } + } + } else { + Entity passenger = entity.getPassenger(); + if (!(passenger instanceof Player) && entity + .getMetadata("keep").isEmpty()) { if (entity.hasMetadata("ps-tmp-teleport")) { continue; } iterator.remove(); entity.remove(); - } - continue; - } else { - continue; - } - case SMALL_FIREBALL: - case FIREBALL: - case DRAGON_FIREBALL: - case DROPPED_ITEM: - if (Settings.Enabled_Components.KILL_ROAD_ITEMS) { - entity.remove(); - } - // dropped item - continue; - case PRIMED_TNT: - case FALLING_BLOCK: - // managed elsewhere - continue; - case LLAMA: - case DONKEY: - case MULE: - case ZOMBIE_HORSE: - case SKELETON_HORSE: - case HUSK: - case ELDER_GUARDIAN: - case WITHER_SKELETON: - case STRAY: - case ZOMBIE_VILLAGER: - case EVOKER: - case EVOKER_FANGS: - case VEX: - case VINDICATOR: - case POLAR_BEAR: - case BAT: - case BLAZE: - case CAVE_SPIDER: - case CHICKEN: - case COW: - case CREEPER: - case ENDERMAN: - case ENDERMITE: - case ENDER_DRAGON: - case GHAST: - case GIANT: - case GUARDIAN: - case HORSE: - case IRON_GOLEM: - case MAGMA_CUBE: - case MUSHROOM_COW: - case OCELOT: - case PIG: - case PIG_ZOMBIE: - case RABBIT: - case SHEEP: - case SILVERFISH: - case SKELETON: - case SLIME: - case SNOWMAN: - case SPIDER: - case SQUID: - case VILLAGER: - case WITCH: - case WITHER: - case WOLF: - case ZOMBIE: - default: { - if (Settings.Enabled_Components.KILL_ROAD_MOBS) { - Location location = entity.getLocation(); - if (BukkitUtil.getLocation(location).isPlotRoad()) { - if (entity instanceof LivingEntity) { - LivingEntity livingEntity = (LivingEntity) entity; - if (!livingEntity.isLeashed() || !entity - .hasMetadata("keep")) { - Entity passenger = entity.getPassenger(); - if (!(passenger instanceof Player) && entity - .getMetadata("keep").isEmpty()) { - if (entity.hasMetadata("ps-tmp-teleport")) { - continue; - } - iterator.remove(); - entity.remove(); - continue; - } - } - } else { - Entity passenger = entity.getPassenger(); - if (!(passenger instanceof Player) && entity - .getMetadata("keep").isEmpty()) { - if (entity.hasMetadata("ps-tmp-teleport")) { - continue; - } - iterator.remove(); - entity.remove(); - continue; - } - } - } - } - continue; - } - case SHULKER: { - if (Settings.Enabled_Components.KILL_ROAD_MOBS) { - LivingEntity livingEntity = (LivingEntity) entity; - List meta = entity.getMetadata("plot"); - if (meta != null && !meta.isEmpty()) { - if (livingEntity.isLeashed()) - continue; - - List keep = entity.getMetadata("keep"); - if (keep != null && !keep.isEmpty()) - continue; - - PlotId originalPlotId = (PlotId) meta.get(0).value(); - if (originalPlotId != null) { - 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)))) { - if (entity.hasMetadata("ps-tmp-teleport")) { - continue; - } - iterator.remove(); - entity.remove(); - } - } - } - } else { - //This is to apply the metadata to already spawned shulkers (see EntitySpawnListener.java) - 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 (currentPlotId != null) { - entity.setMetadata("plot", - new FixedMetadataValue( - (Plugin) PlotSquared.get().IMP, - currentPlotId)); - } - } + continue; } } } } + continue; } - } catch (Throwable e) { - e.printStackTrace(); } } - }), 20); + } catch (Throwable e) { + e.printStackTrace(); + } + }), 20); } @Override @Nullable - public final ChunkGenerator getDefaultWorldGenerator(final String world, final String id) { + public final ChunkGenerator getDefaultWorldGenerator(@NotNull final String worldName, + final String id) { final IndependentPlotGenerator result; if (id != null && id.equalsIgnoreCase("single")) { result = new SingleWorldGenerator(); } else { result = PlotSquared.get().IMP.getDefaultGenerator(); - if (!PlotSquared.get().setupPlotWorld(world, id, result)) { + if (!PlotSquared.get().setupPlotWorld(worldName, id, result)) { return null; } } - return (ChunkGenerator) result.specify(world); + return (ChunkGenerator) result.specify(worldName); } @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 (final NoSuchMethodException | ClassNotFoundException ignored) { - PlotSquared.debug("Not running Spigot. Skipping EntitySpawnListener event."); - } - } - - @Override public void registerInventoryEvents() { - // Part of PlayerEvents - can be moved if necessary + getServer().getPluginManager().registerEvents(new EntitySpawnListener(), this); } @Override public void registerPlotPlusEvents() { @@ -613,55 +635,13 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return new BukkitSetupUtils(); } - @Override public UUIDHandlerImplementation initUUIDHandler() { - boolean checkVersion = false; - try { - OfflinePlayer.class.getDeclaredMethod("getUniqueId"); - checkVersion = true; - } catch (Throwable ignore) { - } - final UUIDWrapper wrapper; - if (Settings.UUID.OFFLINE) { - if (Settings.UUID.FORCE_LOWERCASE) { - wrapper = new LowerOfflineUUIDWrapper(); - } else { - wrapper = new OfflineUUIDWrapper(); - } - Settings.UUID.OFFLINE = true; - } else if (checkVersion) { - wrapper = new DefaultUUIDWrapper(); - Settings.UUID.OFFLINE = false; - } else { - if (Settings.UUID.FORCE_LOWERCASE) { - wrapper = new LowerOfflineUUIDWrapper(); - } else { - wrapper = new OfflineUUIDWrapper(); - } - Settings.UUID.OFFLINE = true; - } - if (!checkVersion) { - 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()) { - Settings.UUID.NATIVE_UUID_PROVIDER = true; - } - } - if (Settings.UUID.OFFLINE) { - 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 { - PlotSquared.log(C.PREFIX + " &6" + getPluginName() + " is using online UUIDs"); - } - if (Settings.UUID.USE_SQLUUIDHANDLER) { - return new SQLUUIDHandler(wrapper); - } else { - return new FileUUIDHandler(wrapper); + @Override public void startMetrics() { + if (this.metricsStarted) { + return; } + this.metricsStarted = true; + Metrics metrics = new Metrics(this);// bstats + PlotSquared.log(Captions.PREFIX + "&6Metrics enabled."); } @Override public ChunkManager initChunkManager() { @@ -684,7 +664,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain getServer().getPluginManager().registerEvents(new WorldEvents(), this); } - @Override public IndependentPlotGenerator getDefaultGenerator() { + @NotNull @Override public IndependentPlotGenerator getDefaultGenerator() { return new HybridGen(); } @@ -692,15 +672,37 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return new BukkitInventoryUtil(); } - @Override public void startMetrics() { - if (this.metricsStarted) { - return; + @Override public UUIDHandlerImplementation initUUIDHandler() { + final UUIDWrapper wrapper; + if (Settings.UUID.OFFLINE) { + if (Settings.UUID.FORCE_LOWERCASE) { + wrapper = new LowerOfflineUUIDWrapper(); + } else { + wrapper = new OfflineUUIDWrapper(); + } + Settings.UUID.OFFLINE = true; + } else { + wrapper = new DefaultUUIDWrapper(); + Settings.UUID.OFFLINE = false; + } + if (!Bukkit.getVersion().contains("git-Spigot")) { + if (wrapper instanceof DefaultUUIDWrapper + || wrapper.getClass() == OfflineUUIDWrapper.class && !Bukkit.getOnlineMode()) { + Settings.UUID.NATIVE_UUID_PROVIDER = true; + } + } + if (Settings.UUID.OFFLINE) { + PlotSquared.log(Captions.PREFIX + " &6" + getPluginName() + + " is using Offline Mode UUIDs either because of user preference, or because you are using an old version of " + + "Bukkit"); + } else { + PlotSquared.log(Captions.PREFIX + " &6" + getPluginName() + " is using online UUIDs"); + } + if (Settings.UUID.USE_SQLUUIDHANDLER) { + return new SQLUUIDHandler(wrapper); + } else { + return new FileUUIDHandler(wrapper); } - System.setProperty("bstats.relocatecheck", - "false"); // We do not want to relocate the package... - new org.bstats.bukkit.Metrics(this); // bstats - PlotSquared.log(C.PREFIX + "&6Metrics enabled."); - this.metricsStarted = true; } @Override public void setGenerator(@NonNull final String worldName) { @@ -730,6 +732,7 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return; } } + assert world != null; ChunkGenerator gen = world.getGenerator(); if (gen instanceof BukkitPlotGenerator) { PlotSquared.get().loadWorld(worldName, (BukkitPlotGenerator) gen); @@ -744,11 +747,6 @@ public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain return new BukkitSchematicHandler(); } - @Override public AbstractTitle initTitleManager() { - // Already initialized in UUID handler - return AbstractTitle.TITLE_CLASS; - } - @Override @Nullable public PlotPlayer wrapPlayer(final Object player) { if (player instanceof Player) { return BukkitUtil.getPlayer((Player) player); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/FancyMessage.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/FancyMessage.java index 41ec91e49..56635abb0 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/FancyMessage.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/FancyMessage.java @@ -5,7 +5,10 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.stream.JsonWriter; -import org.bukkit.*; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.Statistic; import org.bukkit.Statistic.Type; import org.bukkit.command.CommandSender; import org.bukkit.configuration.serialization.ConfigurationSerializable; @@ -320,34 +323,6 @@ public class FancyMessage return this; } - /** - * Set the behavior of the current editing component to display information about an achievement when the client hovers over the text. - *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

- * - * @param which The achievement to display. - * @return This builder instance. - */ - 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)); - } catch (IllegalAccessException e) { - Bukkit.getLogger().log(Level.WARNING, "Could not access method.", e); - return this; - } catch (IllegalArgumentException e) { - 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); - return this; - } - } - /** * Set the behavior of the current editing component to display information about a parameterless statistic when the client hovers over the text. *

Tooltips do not inherit display characteristics, such as color and styles, from the message component on which they are applied.

@@ -648,9 +623,7 @@ public class FancyMessage * @return This builder instance. */ public FancyMessage translationReplacements(final FancyMessage... replacements) { - for (FancyMessage str : replacements) { - latest().translationReplacements.add(str); - } + Collections.addAll(latest().translationReplacements, replacements); dirty = true; @@ -869,7 +842,6 @@ public class FancyMessage *
  • The core text of the message part.
  • * * The primary omissions are tooltips and clickable actions. Consequently, this method should be used only as a last resort. - *

    *

    * Color and formatting can be removed from the returned string by using {@link ChatColor#stripColor(String)}.

    * diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/MessagePart.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/MessagePart.java index 6c2e838d6..43cf15e08 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/MessagePart.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/MessagePart.java @@ -134,7 +134,7 @@ 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); + .log(Level.WARNING, "A problem occurred during writing of JSON string", e); } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/Reflection.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/Reflection.java index 79c445dcc..f3f004284 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/Reflection.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/chat/Reflection.java @@ -43,10 +43,6 @@ public final class Reflection { */ public synchronized static String getVersion() { if (_versionString == null) { - if (Bukkit.getServer() == null) { - // The server hasn't started, static initializer call? - return null; - } String name = Bukkit.getServer().getClass().getPackage().getName(); _versionString = name.substring(name.lastIndexOf('.') + 1) + "."; } @@ -180,15 +176,11 @@ public final class Reflection { * @return A method object with the specified name declared by the specified class. */ public synchronized static Method getMethod(Class clazz, String name, Class... args) { - if (!_loadedMethods.containsKey(clazz)) { - _loadedMethods.put(clazz, new HashMap>, Method>>()); - } + _loadedMethods.computeIfAbsent(clazz, k -> new HashMap<>()); Map>, Method>> loadedMethodNames = _loadedMethods.get(clazz); - if (!loadedMethodNames.containsKey(name)) { - loadedMethodNames.put(name, new HashMap>, Method>()); - } + loadedMethodNames.computeIfAbsent(name, k -> new HashMap<>()); Map>, Method> loadedSignatures = loadedMethodNames.get(name); ArrayWrapper> wrappedArg = new ArrayWrapper<>(args); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/commands/DebugUUID.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/commands/DebugUUID.java index 0dfcf1a18..fdee5edf6 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/commands/DebugUUID.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/commands/DebugUUID.java @@ -10,7 +10,7 @@ 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.config.Captions; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.Plot; @@ -55,14 +55,15 @@ import java.util.Map.Entry; Class clazz = Class.forName(args[0]); newWrapper = (UUIDWrapper) clazz.newInstance(); } catch (ClassNotFoundException | IllegalAccessException | InstantiationException ignored) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot uuidconvert "); return false; } } if (args.length != 2 || !"-o".equals(args[1])) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert " + args[0] + " - o"); + MainUtil.sendMessage(player, Captions.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"); @@ -109,7 +110,8 @@ import java.util.Map.Entry; UUID uuid = UUID.fromString(s); uuids.add(uuid); } catch (Exception ignored) { - MainUtil.sendMessage(player, C.PREFIX + "Invalid playerdata: " + current); + MainUtil.sendMessage(player, + Captions.PREFIX + "Invalid playerdata: " + current); } } } @@ -137,7 +139,7 @@ import java.util.Map.Entry; } } catch (Throwable ignored) { MainUtil.sendMessage(player, - C.PREFIX + "&6Invalid playerdata: " + uuid.toString() + ".dat"); + Captions.PREFIX + "&6Invalid playerdata: " + uuid.toString() + ".dat"); } } for (String name : names) { @@ -171,126 +173,114 @@ import java.util.Map.Entry; } MainUtil.sendMessage(player, "&7 - Replacing cache"); - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - for (Entry entry : uCMap.entrySet()) { - String name = UUIDHandler.getName(entry.getKey()); - if (name != null) { - UUIDHandler.add(new StringWrapper(name), entry.getValue()); - } + TaskManager.runTaskAsync(() -> { + for (Entry entry : uCMap.entrySet()) { + String name = UUIDHandler.getName(entry.getKey()); + if (name != null) { + UUIDHandler.add(new StringWrapper(name), entry.getValue()); } + } - MainUtil.sendMessage(player, "&7 - Scanning for applicable files (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); - for (String line : lines) { - try { - line = line.trim(); - if (line.isEmpty()) { - continue; - } - line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); - String[] split = line.split("\\|"); - String name = split[0]; - if (name.isEmpty() || name.length() > 16 || !StringMan - .isAlphanumericUnd(name)) { - continue; - } - UUID old = currentUUIDWrapper.getUUID(name); - if (old == null) { - continue; - } - UUID now = newWrapper.getUUID(name); - UUIDHandler.add(new StringWrapper(name), now); - uCMap.put(old, now); - uCReverse.put(now, old); - } catch (Exception e2) { - e2.printStackTrace(); - } - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - MainUtil.sendMessage(player, "&7 - Replacing wrapper"); - UUIDHandler.setUUIDWrapper(newWrapper); - - MainUtil.sendMessage(player, "&7 - Updating plot objects"); - - for (Plot plot : PlotSquared.get().getPlots()) { - UUID value = uCMap.get(plot.owner); - if (value != null) { - plot.owner = value; - } - plot.getTrusted().clear(); - plot.getMembers().clear(); - plot.getDenied().clear(); - } - - MainUtil.sendMessage(player, "&7 - Deleting database"); - boolean result = DBFunc.deleteTables(); - - MainUtil.sendMessage(player, "&7 - Creating tables"); + MainUtil.sendMessage(player, "&7 - Scanning for applicable files (uuids.txt)"); + File file = new File(PlotSquared.get().IMP.getDirectory(), "uuids.txt"); + if (file.exists()) { try { - DBFunc.createTables(); - if (!result) { - MainUtil.sendMessage(player, "&cConversion failed! Attempting recovery"); - for (Plot plot : PlotSquared.get().getPlots()) { - UUID value = uCReverse.get(plot.owner); - if (value != null) { - plot.owner = value; + List lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); + for (String line : lines) { + try { + line = line.trim(); + if (line.isEmpty()) { + continue; } + line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); + String[] split = line.split("\\|"); + String name = split[0]; + if (name.isEmpty() || name.length() > 16 || !StringMan + .isAlphanumericUnd(name)) { + continue; + } + UUID old = currentUUIDWrapper.getUUID(name); + if (old == null) { + continue; + } + UUID now = newWrapper.getUUID(name); + UUIDHandler.add(new StringWrapper(name), now); + uCMap.put(old, now); + uCReverse.put(now, old); + } catch (Exception e2) { + e2.printStackTrace(); } - DBFunc.createPlotsAndData(new ArrayList<>(PlotSquared.get().getPlots()), - new Runnable() { - @Override public void run() { - MainUtil.sendMessage(player, "&6Recovery was successful!"); - } - }); - return; } - } catch (Exception e) { + } catch (IOException e) { e.printStackTrace(); + } + } + + MainUtil.sendMessage(player, "&7 - Replacing wrapper"); + UUIDHandler.setUUIDWrapper(newWrapper); + + MainUtil.sendMessage(player, "&7 - Updating plot objects"); + + for (Plot plot : PlotSquared.get().getPlots()) { + UUID value = uCMap.get(plot.owner); + if (value != null) { + plot.owner = value; + } + plot.getTrusted().clear(); + plot.getMembers().clear(); + plot.getDenied().clear(); + } + + MainUtil.sendMessage(player, "&7 - Deleting database"); + boolean result = DBFunc.deleteTables(); + + MainUtil.sendMessage(player, "&7 - Creating tables"); + + try { + DBFunc.createTables(); + if (!result) { + MainUtil.sendMessage(player, "&cConversion failed! Attempting recovery"); + for (Plot plot : PlotSquared.get().getPlots()) { + UUID value = uCReverse.get(plot.owner); + if (value != null) { + plot.owner = value; + } + } + DBFunc.createPlotsAndData(new ArrayList<>(PlotSquared.get().getPlots()), + () -> MainUtil.sendMessage(player, "&6Recovery was successful!")); return; } - - if (newWrapper instanceof OfflineUUIDWrapper) { - PlotSquared.get().worlds.set("UUID.force-lowercase", false); - PlotSquared.get().worlds.set("UUID.offline", true); - } else if (newWrapper instanceof DefaultUUIDWrapper) { - PlotSquared.get().worlds.set("UUID.force-lowercase", false); - PlotSquared.get().worlds.set("UUID.offline", false); - } - try { - 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, "&7 - Populating tables"); - - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - ArrayList plots = new ArrayList<>(PlotSquared.get().getPlots()); - DBFunc.createPlotsAndData(plots, new Runnable() { - @Override public void run() { - MainUtil.sendMessage(player, "&aConversion complete!"); - } - }); - } - }); - - 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"); + } catch (Exception e) { + e.printStackTrace(); + return; } + + if (newWrapper instanceof OfflineUUIDWrapper) { + PlotSquared.get().worlds.set("UUID.force-lowercase", false); + PlotSquared.get().worlds.set("UUID.offline", true); + } else if (newWrapper instanceof DefaultUUIDWrapper) { + PlotSquared.get().worlds.set("UUID.force-lowercase", false); + PlotSquared.get().worlds.set("UUID.offline", false); + } + try { + 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, "&7 - Populating tables"); + + TaskManager.runTaskAsync(() -> { + ArrayList plots = new ArrayList<>(PlotSquared.get().getPlots()); + DBFunc.createPlotsAndData(plots, + () -> MainUtil.sendMessage(player, "&aConversion complete!")); + }); + + 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"); }); return true; } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java deleted file mode 100644 index 40acef111..000000000 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/ClusterFlagRemoveEvent.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.github.intellectualsites.plotsquared.bukkit.events; - -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; - -/** - * Called when a flag is removed from a plot. - */ -public class ClusterFlagRemoveEvent extends Event implements Cancellable { - - private static final HandlerList handlers = new HandlerList(); - private final PlotCluster cluster; - private final Flag flag; - private boolean cancelled; - - /** - * PlotFlagRemoveEvent: Called when a flag is removed from a plot. - * - * @param flag Flag that was removed - * @param cluster PlotCluster from which the flag was removed - */ - public ClusterFlagRemoveEvent(Flag flag, PlotCluster cluster) { - this.cluster = cluster; - this.flag = flag; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - /** - * Get the cluster involved. - * - * @return PlotCluster - */ - public PlotCluster getCluster() { - return this.cluster; - } - - /** - * Get the flag involved. - * - * @return Flag - */ - public Flag getFlag() { - return this.flag; - } - - @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/github/intellectualsites/plotsquared/bukkit/events/PlayerLeavePlotEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerLeavePlotEvent.java index 465e8cee9..36482d44c 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerLeavePlotEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerLeavePlotEvent.java @@ -6,8 +6,7 @@ import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; /** - - + * */ public class PlayerLeavePlotEvent extends PlayerEvent { diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerPlotHelperEvent.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerPlotHelperEvent.java index 2773f9b73..573d53ea8 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerPlotHelperEvent.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/events/PlayerPlotHelperEvent.java @@ -7,8 +7,7 @@ import org.bukkit.event.HandlerList; import java.util.UUID; /** - - + * */ public class PlayerPlotHelperEvent extends PlotEvent { diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java index 6022632eb..03b0c8123 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitAugmentedGenerator.java @@ -4,6 +4,7 @@ import com.github.intellectualsites.plotsquared.plot.generator.AugmentedUtils; import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.generator.BlockPopulator; +import org.jetbrains.annotations.NotNull; import java.util.Random; @@ -24,7 +25,8 @@ public class BukkitAugmentedGenerator extends BlockPopulator { return generator; } - @Override public void populate(World world, Random r, Chunk chunk) { - AugmentedUtils.generate(world.getName(), chunk.getX(), chunk.getZ(), null); + @Override + public void populate(@NotNull World world, @NotNull Random random, @NotNull Chunk source) { + AugmentedUtils.generate(world.getName(), source.getX(), source.getZ(), null); } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitPlotGenerator.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitPlotGenerator.java index 9280f94f1..465fcab20 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitPlotGenerator.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/BukkitPlotGenerator.java @@ -4,21 +4,19 @@ 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.HybridPlotWorld; import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.ChunkLoc; +import com.github.intellectualsites.plotsquared.plot.object.ChunkWrapper; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; 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; +import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; @@ -28,7 +26,8 @@ import java.util.Set; public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrapper { - private final GenChunk chunkSetter; + @SuppressWarnings("unused") public final boolean PAPER_ASYNC_SAFE = true; + private final IndependentPlotGenerator plotGenerator; private final ChunkGenerator platformGenerator; private final boolean full; @@ -41,24 +40,8 @@ public class BukkitPlotGenerator extends ChunkGenerator } this.plotGenerator = generator; this.platformGenerator = this; - populators = new ArrayList<>(); - this.populators.add(new BlockPopulator() { - - private LocalBlockQueue queue; - - @Override public void populate(World world, Random r, Chunk c) { - if (queue == null) { - queue = GlobalBlockQueue.IMP.getNewQueue(world.getName(), false); - } - 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)) { - queue.flush(); - } - } - }); - this.chunkSetter = new GenChunk(null, null); + this.populators = new ArrayList<>(); + this.populators.add(new PlotBlockPopulator(this.plotGenerator)); this.full = true; MainUtil.initCache(); } @@ -69,110 +52,8 @@ public class BukkitPlotGenerator extends ChunkGenerator + " is already a BukkitPlotGenerator!"); } this.full = false; - 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 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 PlotSquared.get().IMP.getDefaultGenerator() - .getNewPlotArea(world, id, min, max); - } - - @Override public BlockBucket[][] generateBlockBucketChunk(PlotArea settings) { - BlockBucket[][] blockBuckets = new BlockBucket[16][]; - HybridPlotWorld hpw = (HybridPlotWorld) settings; - // Bedrock - if (hpw.PLOT_BEDROCK) { - for (short x = 0; x < 16; x++) { - for (short z = 0; z < 16; z++) { - blockBuckets[0][(z << 4) | x] = - BlockBucket.withSingle(PlotBlock.get("bedrock")); - } - } - } - for (short x = 0; x < 16; x++) { - for (short z = 0; z < 16; z++) { - for (int y = 1; y < hpw.PLOT_HEIGHT; y++) { - blockBuckets[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = hpw.MAIN_BLOCK; - } - blockBuckets[hpw.PLOT_HEIGHT >> 4][((hpw.PLOT_HEIGHT & 0xF) << 8) | (z << 4) - | x] = hpw.MAIN_BLOCK; - } - } - return blockBuckets; - } - - @Override - public void generateChunk(final ScopedLocalBlockQueue result, PlotArea settings) { - 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) { - result.setBiome(x, z, biome.name()); - } - - @Override public Biome getBiome(int arg0, int arg1) { - return Biome.FOREST; - } - }; - try { - // ChunkData will spill a bit - ChunkData data = cg.generateChunkData(w, r, cx, cz, grid); - if (data != null) { - return; - } - } catch (Throwable ignored) { - } - /* TODO: Redo this - // Populator spillage - short[][] tmp = cg.generateExtBlockSections(w, r, cx, cz, grid); - if (tmp != null) { - for (int i = 0; i < tmp.length; i++) { - short[] section = tmp[i]; - if (section == null) { - if (i < 7) { - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - for (int y = i << 4; y < (i << 4) + 16; y++) { - result.setBlock(x, y, z, PlotBlock.get("air")); - } - } - } - } - continue; - } - for (int j = 0; j < section.length; j++) { - int x = MainUtil.x_loc[i][j]; - int y = MainUtil.y_loc[i][j]; - int z = MainUtil.z_loc[i][j]; - result.setBlock(x, y, z, section[j], (byte) 0); - } - } - } - */ - for (BlockPopulator populator : cg.getDefaultPopulators(w)) { - populator.populate(w, r, w.getChunkAt(cx, cz)); - } - } - }; - this.chunkSetter = new GenChunk(null, new ChunkWrapper(world, 0, 0)); + this.plotGenerator = new DelegatePlotGenerator(cg, world); MainUtil.initCache(); } @@ -192,7 +73,7 @@ public class BukkitPlotGenerator extends ChunkGenerator return this.platformGenerator; } - @Override public List getDefaultPopulators(World world) { + @Override @NotNull public List getDefaultPopulators(@NotNull World world) { try { if (!this.loaded) { String name = world.getName(); @@ -226,50 +107,54 @@ public class BukkitPlotGenerator extends ChunkGenerator if (populators == null && platformGenerator != null) { populators = new ArrayList<>(platformGenerator.getDefaultPopulators(world)); } - for (BlockPopulator populator : this.populators) { - if (!existing.contains(populator)) { - toAdd.add(populator); + if (populators != null) { + for (BlockPopulator populator : this.populators) { + if (!existing.contains(populator)) { + toAdd.add(populator); + } } } return toAdd; } - @Override - public ChunkData generateChunkData(World world, Random random, int cx, int cz, BiomeGrid grid) { - GenChunk result = this.chunkSetter; + @Override @NotNull + public ChunkData generateChunkData(@NotNull World world, @NotNull Random random, int x, int z, + @NotNull BiomeGrid biome) { + + GenChunk result = new GenChunk(); if (this.getPlotGenerator() instanceof SingleWorldGenerator) { - if (result.getCd() != null) { - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - grid.setBiome(x, z, Biome.PLAINS); + if (result.getChunkData() != null) { + for (int chunkX = 0; chunkX < 16; chunkX++) { + for (int chunkZ = 0; chunkZ < 16; chunkZ++) { + biome.setBiome(chunkX, chunkZ, Biome.PLAINS); } } - return result.getCd(); + return result.getChunkData(); } } // Set the chunk location - result.setChunk(new ChunkWrapper(world.getName(), cx, cz)); + result.setChunk(new ChunkWrapper(world.getName(), x, z)); // Set the result data - result.setCd(createChunkData(world)); - result.grid = grid; + result.setChunkData(createChunkData(world)); + result.biomeGrid = biome; result.result = null; // Catch any exceptions (as exceptions usually thrown) try { // Fill the result data if necessary if (this.platformGenerator != this) { - return this.platformGenerator.generateChunkData(world, random, cx, cz, grid); + return this.platformGenerator.generateChunkData(world, random, x, z, biome); } else { - generate(world, result); + generate(new ChunkLoc(x, z), world, result); } } catch (Throwable e) { e.printStackTrace(); } // Return the result data - return result.getCd(); + return result.getChunkData(); } - private void generate(World world, ScopedLocalBlockQueue result) { + private void generate(ChunkLoc loc, World world, ScopedLocalBlockQueue result) { // Load if improperly loaded if (!this.loaded) { String name = world.getName(); @@ -277,17 +162,17 @@ public class BukkitPlotGenerator extends ChunkGenerator this.loaded = true; } // Process the chunk - if (ChunkManager.preProcessChunk(result)) { + if (ChunkManager.preProcessChunk(loc, result)) { return; } PlotArea area = PlotSquared.get().getPlotArea(world.getName(), null); try { - this.plotGenerator.generateChunk(this.chunkSetter, area); + this.plotGenerator.generateChunk(result, area); } catch (Throwable e) { // Recover from generator error e.printStackTrace(); } - ChunkManager.postProcessChunk(result); + ChunkManager.postProcessChunk(loc, result); } /** @@ -298,7 +183,7 @@ public class BukkitPlotGenerator extends ChunkGenerator * @param z Ignored * @return always true */ - @Override public boolean canSpawn(World world, int x, int z) { + @Override public boolean canSpawn(@NotNull final World world, final int x, final int z) { return true; } @@ -313,10 +198,11 @@ public class BukkitPlotGenerator extends ChunkGenerator } } - @Override public boolean equals(Object obj) { + @Override public boolean equals(final Object obj) { if (obj == null) { return false; } return toString().equals(obj.toString()) || toString().equals(obj.getClass().getName()); } + } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/DelegatePlotGenerator.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/DelegatePlotGenerator.java new file mode 100644 index 000000000..c8b57dc78 --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/DelegatePlotGenerator.java @@ -0,0 +1,91 @@ +package com.github.intellectualsites.plotsquared.bukkit.generator; + +import com.github.intellectualsites.plotsquared.bukkit.util.BukkitUtil; +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld; +import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator; +import com.github.intellectualsites.plotsquared.plot.object.BlockBucket; +import com.github.intellectualsites.plotsquared.plot.object.Location; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotManager; +import com.github.intellectualsites.plotsquared.plot.util.MathMan; +import com.github.intellectualsites.plotsquared.plot.util.block.ScopedLocalBlockQueue; +import lombok.RequiredArgsConstructor; +import org.bukkit.World; +import org.bukkit.block.Biome; +import org.bukkit.generator.BlockPopulator; +import org.bukkit.generator.ChunkGenerator; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Range; + +import java.util.Random; + +@RequiredArgsConstructor final class DelegatePlotGenerator extends IndependentPlotGenerator { + + private final ChunkGenerator chunkGenerator; + private final String world; + + @Override public void initialize(PlotArea area) { + } + + @Override public String getName() { + return this.chunkGenerator.getClass().getName(); + } + + @Override public PlotArea getNewPlotArea(String world, String id, PlotId min, PlotId max) { + return PlotSquared.get().IMP.getDefaultGenerator().getNewPlotArea(world, id, min, max); + } + + @Override public BlockBucket[][] generateBlockBucketChunk(PlotArea settings) { + BlockBucket[][] blockBuckets = new BlockBucket[16][]; + HybridPlotWorld hpw = (HybridPlotWorld) settings; + // Bedrock + if (hpw.PLOT_BEDROCK) { + for (short x = 0; x < 16; x++) { + for (short z = 0; z < 16; z++) { + blockBuckets[0][(z << 4) | x] = + BlockBucket.withSingle(PlotBlock.get("bedrock")); + } + } + } + for (short x = 0; x < 16; x++) { + for (short z = 0; z < 16; z++) { + for (int y = 1; y < hpw.PLOT_HEIGHT; y++) { + blockBuckets[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = hpw.MAIN_BLOCK; + } + blockBuckets[hpw.PLOT_HEIGHT >> 4][((hpw.PLOT_HEIGHT & 0xF) << 8) | (z << 4) | x] = + hpw.MAIN_BLOCK; + } + } + return blockBuckets; + } + + @Override public void generateChunk(final ScopedLocalBlockQueue result, PlotArea settings) { + World world = BukkitUtil.getWorld(this.world); + Location min = result.getMin(); + int chunkX = min.getX() >> 4; + int chunkZ = min.getZ() >> 4; + Random random = new Random(MathMan.pair((short) chunkX, (short) chunkZ)); + try { + ChunkGenerator.BiomeGrid grid = new ChunkGenerator.BiomeGrid() { + @Override public void setBiome(@Range(from = 0, to = 15) int x, + @Range(from = 0, to = 15) int z, Biome biome) { + result.setBiome(x, z, biome.name()); + } + + @Override @NotNull public Biome getBiome(int x, int z) { + return Biome.FOREST; + } + }; + chunkGenerator.generateChunkData(world, random, chunkX, chunkZ, grid); + return; + } catch (Throwable ignored) { + } + for (BlockPopulator populator : chunkGenerator.getDefaultPopulators(world)) { + populator.populate(world, random, world.getChunkAt(chunkX, chunkZ)); + } + } + +} diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/PlotBlockPopulator.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/PlotBlockPopulator.java new file mode 100644 index 000000000..9236e184a --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/generator/PlotBlockPopulator.java @@ -0,0 +1,36 @@ +package com.github.intellectualsites.plotsquared.bukkit.generator; + +import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.generator.IndependentPlotGenerator; +import com.github.intellectualsites.plotsquared.plot.object.ChunkWrapper; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +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 lombok.RequiredArgsConstructor; +import org.bukkit.Chunk; +import org.bukkit.World; +import org.bukkit.generator.BlockPopulator; +import org.jetbrains.annotations.NotNull; + +import java.util.Random; + +@RequiredArgsConstructor final class PlotBlockPopulator extends BlockPopulator { + + private final IndependentPlotGenerator plotGenerator; + private LocalBlockQueue queue; + + @Override public void populate(@NotNull final World world, @NotNull final Random random, + @NotNull final Chunk source) { + if (this.queue == null) { + this.queue = GlobalBlockQueue.IMP.getNewQueue(world.getName(), false); + } + final PlotArea area = PlotSquared.get().getPlotArea(world.getName(), null); + final ChunkWrapper wrap = new ChunkWrapper(area.worldname, source.getX(), source.getZ()); + final ScopedLocalBlockQueue chunk = this.queue.getForChunk(wrap.x, wrap.z); + if (this.plotGenerator.populateChunk(chunk, area)) { + this.queue.flush(); + } + } + +} diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ChunkListener.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ChunkListener.java index da1bb49c3..c55e4f440 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ChunkListener.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ChunkListener.java @@ -1,7 +1,7 @@ package com.github.intellectualsites.plotsquared.bukkit.listeners; import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; @@ -32,8 +32,7 @@ import java.util.HashSet; import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils.getRefClass; -@SuppressWarnings("unused") -public class ChunkListener implements Listener { +@SuppressWarnings("unused") public class ChunkListener implements Listener { private RefMethod methodGetHandleChunk; private RefField mustSave; @@ -49,7 +48,7 @@ public class ChunkListener implements Listener { this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); } catch (Throwable ignored) { PlotSquared.debug(PlotSquared.get().IMP.getPluginName() - + "/Server not compatible for chunk processor trim/gc"); + + "/Server not compatible for chunk processor trim/gc"); Settings.Chunk_Processor.AUTO_TRIM = false; } @@ -60,48 +59,45 @@ public class ChunkListener implements Listener { for (World world : Bukkit.getWorlds()) { world.setAutoSave(false); } - TaskManager.runTaskRepeat(new Runnable() { - @Override public void run() { - try { - HashSet toUnload = new HashSet<>(); - for (World world : Bukkit.getWorlds()) { - String worldName = world.getName(); - if (!PlotSquared.get().hasPlotArea(worldName)) { + TaskManager.runTaskRepeat(() -> { + try { + HashSet toUnload = new HashSet<>(); + for (World world : Bukkit.getWorlds()) { + String worldName = world.getName(); + 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); + Chunk[] chunks = world.getLoadedChunks(); + for (Chunk chunk : chunks) { + if ((boolean) methodIsChunkInUse + .invoke(chunkMap, chunk.getX(), chunk.getZ())) { 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); - Chunk[] chunks = world.getLoadedChunks(); - for (Chunk chunk : chunks) { - if ((boolean) methodIsChunkInUse - .invoke(chunkMap, chunk.getX(), chunk.getZ())) { - continue; - } - int x = chunk.getX(); - int z = chunk.getZ(); - if (!shouldSave(worldName, x, z)) { - unloadChunk(worldName, chunk, false); - continue; - } - toUnload.add(chunk); + int x = chunk.getX(); + int z = chunk.getZ(); + if (!shouldSave(worldName, x, z)) { + unloadChunk(worldName, chunk, false); + continue; } + toUnload.add(chunk); } - if (toUnload.isEmpty()) { + } + if (toUnload.isEmpty()) { + return; + } + long start = System.currentTimeMillis(); + for (Chunk chunk : toUnload) { + if (System.currentTimeMillis() - start > 5) { return; } - long start = System.currentTimeMillis(); - for (Chunk chunk : toUnload) { - if (System.currentTimeMillis() - start > 5) { - return; - } - chunk.unload(true, false); - } - } catch (Throwable e) { - e.printStackTrace(); + chunk.unload(true); } + } catch (Throwable e) { + e.printStackTrace(); } }, 1); } @@ -112,20 +108,20 @@ public class ChunkListener implements Listener { } Object c = this.methodGetHandleChunk.of(chunk).call(); RefField.RefExecutor field = this.mustSave.of(c); - if ((Boolean) field.get() == true) { + if ((Boolean) field.get()) { field.set(false); if (chunk.isLoaded()) { ignoreUnload = true; - chunk.unload(false, false); + chunk.unload(false); ignoreUnload = false; } } return true; } - public boolean shouldSave(String world, int X, int Z) { - int x = X << 4; - int z = Z << 4; + public boolean shouldSave(String world, int chunkX, int chunkZ) { + int x = chunkX << 4; + int z = chunkZ << 4; int x2 = x + 15; int z2 = z + 15; Plot plot = new Location(world, x, 1, z).getOwnedPlotAbs(); @@ -148,13 +144,12 @@ 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; } + Chunk chunk = event.getChunk(); if (Settings.Chunk_Processor.AUTO_TRIM) { - Chunk chunk = event.getChunk(); String world = chunk.getWorld().getName(); if (PlotSquared.get().hasPlotArea(world)) { if (unloadChunk(world, chunk, true)) { @@ -163,17 +158,15 @@ public class ChunkListener implements Listener { } } if (processChunk(event.getChunk(), true)) { - event.setCancelled(true); + chunk.setForceLoaded(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) { @@ -226,39 +219,37 @@ public class ChunkListener implements Listener { private void cleanChunk(final Chunk chunk) { TaskManager.index.incrementAndGet(); final Integer currentIndex = TaskManager.index.get(); - Integer task = TaskManager.runTaskRepeat(new Runnable() { - @Override public void run() { - if (!chunk.isLoaded()) { + Integer task = TaskManager.runTaskRepeat(() -> { + if (!chunk.isLoaded()) { + Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); + TaskManager.tasks.remove(currentIndex); + PlotSquared + .debug(Captions.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); + chunk.unload(true); + return; + } + BlockState[] tiles = chunk.getTileEntities(); + if (tiles.length == 0) { + Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); + TaskManager.tasks.remove(currentIndex); + PlotSquared + .debug(Captions.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); + chunk.unload(true); + return; + } + long start = System.currentTimeMillis(); + int i = 0; + while (System.currentTimeMillis() - start < 250) { + if (i >= tiles.length) { Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); TaskManager.tasks.remove(currentIndex); - PlotSquared - .debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); - chunk.unload(true, true); + PlotSquared.debug( + Captions.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); + chunk.unload(true); return; } - BlockState[] tiles = chunk.getTileEntities(); - if (tiles.length == 0) { - Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); - TaskManager.tasks.remove(currentIndex); - PlotSquared - .debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); - chunk.unload(true, true); - return; - } - long start = System.currentTimeMillis(); - int i = 0; - while (System.currentTimeMillis() - start < 250) { - if (i >= tiles.length) { - Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); - TaskManager.tasks.remove(currentIndex); - PlotSquared - .debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!"); - chunk.unload(true, true); - return; - } - tiles[i].getBlock().setType(Material.AIR, false); - i++; - } + tiles[i].getBlock().setType(Material.AIR, false); + i++; } }, 5); TaskManager.tasks.put(currentIndex, task); @@ -277,14 +268,14 @@ public class ChunkListener implements Listener { } } PlotSquared.debug( - C.PREFIX.s() + "&a detected unsafe chunk and processed: " + (chunk.getX() << 4) - + "," + (chunk.getX() << 4)); + Captions.PREFIX.s() + "&a detected unsafe chunk and processed: " + (chunk.getX() + << 4) + "," + (chunk.getX() << 4)); } if (tiles.length > Settings.Chunk_Processor.MAX_TILES) { if (unload) { PlotSquared.debug( - C.PREFIX.s() + "&c detected unsafe chunk: " + (chunk.getX() << 4) + "," + ( - chunk.getX() << 4)); + Captions.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 index 9f787297d..27a24ba9d 100644 --- 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 @@ -7,6 +7,7 @@ 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.Chunk; import org.bukkit.World; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Entity; @@ -18,23 +19,52 @@ 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.event.vehicle.VehicleBlockCollisionEvent; +import org.bukkit.event.vehicle.VehicleCreateEvent; +import org.bukkit.event.vehicle.VehicleMoveEvent; +import org.bukkit.event.vehicle.VehicleUpdateEvent; +import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; import java.util.List; -@SuppressWarnings("unused") public class EntitySpawnListener implements Listener { +public class EntitySpawnListener implements Listener { + private final static String KEY = "P2"; private static boolean ignoreTP = false; + private static boolean hasPlotArea = false; + private static String areaName = null; + + public static void testNether(Entity entity) { + @NotNull World world = entity.getWorld(); + if (world.getEnvironment() != World.Environment.NETHER + && world.getEnvironment() != World.Environment.THE_END) { + return; + } + test(entity); + } + + public static void testCreate(Entity entity) { + @NotNull World world = entity.getWorld(); + if (areaName == world.getName()) { + } else { + areaName = world.getName(); + hasPlotArea = PlotSquared.get().hasPlotArea(areaName); + } + if (!hasPlotArea) + return; + test(entity); + } public static void test(Entity entity) { - List meta = entity.getMetadata("plotworld"); - World world = entity.getLocation().getWorld(); - if (meta == null || meta.isEmpty()) { + @NotNull World world = entity.getWorld(); + List meta = entity.getMetadata(KEY); + if (meta.isEmpty()) { if (PlotSquared.get().hasPlotArea(world.getName())) { - entity.setMetadata("plotworld", + entity.setMetadata(KEY, new FixedMetadataValue((Plugin) PlotSquared.get().IMP, entity.getLocation())); } } else { @@ -65,16 +95,17 @@ import java.util.List; Entity entity = event.getEntity(); Location location = BukkitUtil.getLocation(entity.getLocation()); PlotArea area = location.getPlotArea(); - if (area == null) { + if (!location.isPlotArea()) { return; } - Plot plot = area.getOwnedPlotAbs(location); + Plot plot = location.getOwnedPlotAbs(); if (plot == null) { if (!area.MOB_SPAWNING) { EntityType type = entity.getType(); switch (type) { case DROPPED_ITEM: if (Settings.Enabled_Components.KILL_ROAD_ITEMS) { + event.setCancelled(true); break; } case PLAYER: @@ -95,48 +126,47 @@ import java.util.List; event.setCancelled(true); } case SHULKER: - if (!entity.hasMetadata("plot")) { - entity.setMetadata("plot", + if (!entity.hasMetadata("shulkerPlot")) { + entity.setMetadata("shulkerPlot", new FixedMetadataValue((Plugin) PlotSquared.get().IMP, plot.getId())); } } } + @EventHandler public void onChunkLoad(ChunkLoadEvent event) { + @NotNull Chunk chunk = event.getChunk(); + for (Entity entity : chunk.getEntities()) { + testCreate(entity); + } + } + @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()); + testNether(event.getVehicle()); } @EventHandler public void onVehicle(VehicleCreateEvent event) { - test(event.getVehicle()); + testCreate(event.getVehicle()); } @EventHandler public void onVehicle(VehicleBlockCollisionEvent event) { - test(event.getVehicle()); + testNether(event.getVehicle()); } @EventHandler public void onTeleport(EntityTeleportEvent event) { Entity ent = event.getEntity(); - if (ent instanceof Vehicle || ent instanceof ArmorStand) - test(event.getEntity()); + if (ent instanceof Vehicle || ent instanceof ArmorStand) { + testNether(event.getEntity()); + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void vehicleMove(VehicleMoveEvent event) throws IllegalAccessException { - test(event.getVehicle()); + public void vehicleMove(VehicleMoveEvent event) { + testNether(event.getVehicle()); } @EventHandler public void spawn(CreatureSpawnEvent event) { - switch (event.getEntityType()) { - case ARMOR_STAND: - test(event.getEntity()); + if (event.getEntityType() == EntityType.ARMOR_STAND) { + testCreate(event.getEntity()); } } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ForceFieldListener.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ForceFieldListener.java index 97d1bb7d7..d2d588970 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ForceFieldListener.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/ForceFieldListener.java @@ -2,7 +2,7 @@ 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.config.Captions; import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; @@ -85,7 +85,8 @@ import java.util.UUID; if (plot.isAdded(uuid)) { Set players = getNearbyPlayers(player, plot); for (PlotPlayer oPlayer : players) { - if (!Permissions.hasPermission(oPlayer, C.PERMISSION_ADMIN_ENTRY_FORCEFIELD)) { + if (!Permissions + .hasPermission(oPlayer, Captions.PERMISSION_ADMIN_ENTRY_FORCEFIELD)) { ((BukkitPlayer) oPlayer).player .setVelocity(calculateVelocity(plotPlayer, oPlayer)); } @@ -95,7 +96,8 @@ import java.util.UUID; if (oPlayer == null) { return; } - if (!Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_ENTRY_FORCEFIELD)) { + if (!Permissions + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_ENTRY_FORCEFIELD)) { player.setVelocity(calculateVelocity(oPlayer, plotPlayer)); } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlayerEvents.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlayerEvents.java index 8e4ea13a0..84cfc2e04 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlayerEvents.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlayerEvents.java @@ -5,7 +5,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.listener.PlayerBlockEventType; @@ -14,13 +14,13 @@ import com.github.intellectualsites.plotsquared.plot.object.*; import com.github.intellectualsites.plotsquared.plot.util.*; import org.bukkit.Bukkit; import org.bukkit.ChatColor; +import org.bukkit.FluidCollisionMode; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.type.Piston; import org.bukkit.command.PluginCommand; import org.bukkit.entity.*; import org.bukkit.event.Event; @@ -36,12 +36,14 @@ import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.*; import org.bukkit.event.vehicle.VehicleCreateEvent; import org.bukkit.event.vehicle.VehicleDestroyEvent; +import org.bukkit.event.vehicle.VehicleEntityCollisionEvent; 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.material.Directional; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.Plugin; @@ -109,7 +111,6 @@ import java.util.regex.Pattern; case EGG: case ENDER_PEARL: case FIREBALL: - case LINGERING_POTION: case LLAMA_SPIT: case SHULKER_BULLET: case SMALL_FIREBALL: @@ -117,13 +118,11 @@ import java.util.regex.Pattern; case SPECTRAL_ARROW: case SPLASH_POTION: case THROWN_EXP_BOTTLE: - case TIPPED_ARROW: // projectile case FALLING_BLOCK: case PRIMED_TNT: // Block entities case AREA_EFFECT_CLOUD: - case COMPLEX_PART: case ENDER_CRYSTAL: case ENDER_SIGNAL: case EVOKER_FANGS: @@ -133,7 +132,6 @@ import java.util.regex.Pattern; case LEASH_HITCH: case LIGHTNING: case UNKNOWN: - case WEATHER: case WITHER_SKULL: // non moving / unmovable return EntityUtil.checkEntity(plot, Flags.ENTITY_CAP); @@ -153,16 +151,19 @@ import java.util.regex.Pattern; return EntityUtil.checkEntity(plot, Flags.ENTITY_CAP, Flags.VEHICLE_CAP); case BAT: case CHICKEN: + case CAT: case COD: case COW: case DOLPHIN: case DONKEY: + case FOX: case HORSE: case IRON_GOLEM: case LLAMA: case MULE: case MUSHROOM_COW: case OCELOT: + case PANDA: case PARROT: case PIG: case POLAR_BEAR: @@ -173,6 +174,7 @@ import java.util.regex.Pattern; case SKELETON_HORSE: case SNOWMAN: case SQUID: + case TRADER_LLAMA: case TROPICAL_FISH: case TURTLE: case VILLAGER: @@ -210,6 +212,9 @@ import java.util.regex.Pattern; case WITHER_SKELETON: case ZOMBIE: case ZOMBIE_VILLAGER: + case PILLAGER: + case PHANTOM: + case RAVAGER: // monster return EntityUtil .checkEntity(plot, Flags.ENTITY_CAP, Flags.MOB_CAP, Flags.HOSTILE_CAP); @@ -235,6 +240,31 @@ import java.util.regex.Pattern; } } + @EventHandler public void onVehicleEntityCollision(VehicleEntityCollisionEvent e) { + if (e.getVehicle().getType() == EntityType.BOAT) { + Location location = BukkitUtil.getLocation(e.getEntity()); + if (location.isPlotArea()) { + if (e.getEntity() instanceof Player) { + PlotPlayer player = BukkitUtil.getPlayer((Player) e.getEntity()); + Plot plot = player.getCurrentPlot(); + if (plot != null) { + if (!plot.isAdded(player.getUUID())) { + //Here the event is only canceled if the player is not the owner + //of the property on which he is located. + e.setCancelled(true); + } + } else { + e.setCancelled(true); + } + } else { + //Here the event is cancelled too, otherwise you can move the + //boat with EchoPets or other mobs running around on the plot. + e.setCancelled(true); + } + } + } + } + @EventHandler public void onRedstoneEvent(BlockRedstoneEvent event) { Block block = event.getBlock(); /* switch (block.getType()) { @@ -289,7 +319,7 @@ import java.util.regex.Pattern; if (area == null) { return; } - Plot plot = area.getOwnedPlot(loc); + Plot plot = loc.getOwnedPlot(); if (plot == null) { return; } @@ -381,7 +411,8 @@ import java.util.regex.Pattern; switch (block.getType()) { case PISTON: case STICKY_PISTON: - Piston piston = (Piston) block.getBlockData(); + org.bukkit.block.data.Directional piston = + (org.bukkit.block.data.Directional) block.getBlockData(); Location loc = BukkitUtil.getLocation(block.getLocation()); PlotArea area = loc.getPlotArea(); if (area == null) { @@ -425,12 +456,12 @@ import java.util.regex.Pattern; if (!(shooter instanceof Player)) { return; } - Location l = BukkitUtil.getLocation(entity); - if (!PlotSquared.get().hasPlotArea(l.getWorld())) { + Location location = BukkitUtil.getLocation(entity); + if (!PlotSquared.get().hasPlotArea(location.getWorld())) { return; } PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter); - Plot plot = l.getOwnedPlot(); + Plot plot = location.getOwnedPlot(); if (plot != null && !plot.isAdded(pp.getUUID())) { entity.remove(); event.setCancelled(true); @@ -452,14 +483,14 @@ import java.util.regex.Pattern; if (shooter instanceof Player) { PlotPlayer pp = BukkitUtil.getPlayer((Player) shooter); if (plot == null) { - if (!Permissions.hasPermission(pp, C.PERMISSION_PROJECTILE_UNOWNED)) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_PROJECTILE_UNOWNED)) { entity.remove(); return false; } return true; } if (plot.isAdded(pp.getUUID()) || Permissions - .hasPermission(pp, C.PERMISSION_PROJECTILE_OTHER)) { + .hasPermission(pp, Captions.PERMISSION_PROJECTILE_OTHER)) { return true; } entity.remove(); @@ -500,35 +531,34 @@ import java.util.regex.Pattern; } String[] parts = msg.split(" "); Plot plot = pp.getCurrentPlot(); - 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))) { - event.setCancelled(true); - return; - } - } + // 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, Captions.PERMISSION_ADMIN_BUILD_OTHER, true))) { + event.setCancelled(true); + return; + } } if (plot == null) { return; } Optional> flag = plot.getFlag(Flags.BLOCKED_CMDS); if (flag.isPresent() && !Permissions - .hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_BLOCKED_CMDS)) { + .hasPermission(pp, Captions.PERMISSION_ADMIN_INTERACT_BLOCKED_CMDS)) { List blocked_cmds = flag.get(); - String c = parts[0]; + String part = parts[0]; if (parts[0].contains(":")) { - c = parts[0].split(":")[1]; + part = parts[0].split(":")[1]; msg = msg.replace(parts[0].split(":")[0] + ':', ""); } - String l = c; + String s1 = part; List aliases = new ArrayList<>(); for (HelpTopic cmdLabel : Bukkit.getServer().getHelpMap().getHelpTopics()) { - if (c.equals(cmdLabel.getName())) { + if (part.equals(cmdLabel.getName())) { break; } String label = cmdLabel.getName().replaceFirst("/", ""); @@ -543,15 +573,15 @@ import java.util.regex.Pattern; } aliases.add(a); a = a.replaceFirst("/", ""); - if (!a.equals(label) && a.equals(c)) { - c = label; + if (!a.equals(label) && a.equals(part)) { + part = label; break; } } } } - if (!l.equals(c)) { - msg = msg.replace(l, c); + if (!s1.equals(part)) { + msg = msg.replace(s1, part); } for (String s : blocked_cmds) { Pattern pattern; @@ -568,7 +598,7 @@ import java.util.regex.Pattern; perm = "plots.admin.command.blocked-cmds.other"; } if (!Permissions.hasPermission(pp, perm)) { - MainUtil.sendMessage(pp, C.COMMAND_BLOCKED); + MainUtil.sendMessage(pp, Captions.COMMAND_BLOCKED); event.setCancelled(true); } return; @@ -606,6 +636,38 @@ import java.util.regex.Pattern; } EventUtil.manager.doJoinTask(pp); }, 20); + + if (pp.hasPermission(Captions.PERMISSION_ADMIN_UPDATE_NOTIFICATION.s()) + && PlotSquared.get().getUpdateUtility() != null) { + final UpdateUtility updateUtility = PlotSquared.get().getUpdateUtility(); + final BukkitMain bukkitMain = BukkitMain.getPlugin(BukkitMain.class); + updateUtility.checkForUpdate(bukkitMain.getPluginVersionString(), + ((updateDescription, throwable) -> { + if (throwable != null) { + bukkitMain.getLogger().severe(String + .format("Could not check for update. Reason: %s", + throwable.getMessage())); + } else { + if (updateDescription != null) { + new PlotMessage("-------- ").color("$2") + .text("PlotSquared Update Notification").color("$1") + .text(" --------").color("$2").send(pp); + new PlotMessage("There appears to be a PlotSquared update available!") + .color("$1").send(pp); + new PlotMessage(String.format("You are running version %s," + + " the newest available version is %s", + bukkitMain.getPluginVersionString(), + updateDescription.getVersion())).color("$1").send(pp); + new PlotMessage("Update URL").color("$1").text(": ").color("$2") + .text(updateDescription.getUrl()).tooltip("Download update") + .send(pp); + new PlotMessage("-------- ").color("$2") + .text("PlotSquared Update Notification").color("$1") + .text(" --------").color("$2").send(pp); + } + } + })); + } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @@ -619,23 +681,37 @@ import java.util.regex.Pattern; public void onTeleport(PlayerTeleportEvent event) { 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); + final Object lastLoc = + BukkitUtil.getPlayer(event.getPlayer()).deleteMeta(PlotPlayer.META_LOCATION); + final Object lastPlot = + 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 = PlotSquared.get().getPlotAreaAbs(loc); + PlotArea area = loc.getPlotArea(); if (area == null) { return; } Plot plot = area.getPlot(loc); if (plot != null) { - plotEntry(pp, plot); + final boolean result = Flags.DENY_TELEPORT.allowsTeleport(pp, plot); + if (!result) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_ENTRY_DENIED); + event.setCancelled(true); + if (lastLoc != null) { + pp.setMeta(PlotPlayer.META_LOCATION, lastLoc); + } + if (lastPlot != null) { + pp.setMeta(PlotPlayer.META_LAST_PLOT, lastPlot); + } + } else { + plotEntry(pp, plot); + } } } - return; } playerMove(event); } @@ -657,8 +733,9 @@ import java.util.regex.Pattern; if (passenger instanceof Player) { final Player player = (Player) passenger; // reset - if (moveTmp == null) + if (moveTmp == null) { moveTmp = new PlayerMoveEvent(null, from, to); + } moveTmp.setFrom(from); moveTmp.setTo(to); moveTmp.setCancelled(false); @@ -686,7 +763,7 @@ import java.util.regex.Pattern; vehicle.eject(); vehicle.setVelocity(new Vector(0d, 0d, 0d)); vehicle.teleport(dest); - vehicle.setPassenger(player); + vehicle.addPassenger(player); } return; } @@ -744,7 +821,8 @@ import java.util.regex.Pattern; if (now == null) { if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport && !pp .getMeta("kick", false)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_EXIT_DENIED); this.tmpTeleport = false; if (lastPlot.equals(BukkitUtil.getLocation(from).getPlot())) { player.teleport(from); @@ -757,9 +835,9 @@ import java.util.regex.Pattern; } } else if (now.equals(lastPlot)) { ForceFieldListener.handleForcefield(player, pp, now); - return; } else if (!plotEntry(pp, now) && this.tmpTeleport) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_ENTRY_DENIED); this.tmpTeleport = false; to.setX(from.getBlockX()); to.setY(from.getBlockY()); @@ -768,24 +846,21 @@ import java.util.regex.Pattern; this.tmpTeleport = true; return; } - Integer border = area.getBorder(); + int border = area.getBorder(); if (x2 > border && this.tmpTeleport) { - to.setX(x2 - 1); + to.setX(border - 1); this.tmpTeleport = false; player.teleport(event.getTo()); this.tmpTeleport = true; - MainUtil.sendMessage(pp, C.BORDER); - return; + MainUtil.sendMessage(pp, Captions.BORDER); } if (x2 < -border && this.tmpTeleport) { - to.setX(x2 + 1); + to.setX(-border + 1); this.tmpTeleport = false; player.teleport(event.getTo()); this.tmpTeleport = true; - MainUtil.sendMessage(pp, C.BORDER); - return; + MainUtil.sendMessage(pp, Captions.BORDER); } - return; } int z2; if (MathMan.roundInt(from.getZ()) != (z2 = MathMan.roundInt(to.getZ()))) { @@ -806,7 +881,8 @@ import java.util.regex.Pattern; if (now == null) { if (lastPlot != null && !plotExit(pp, lastPlot) && this.tmpTeleport && !pp .getMeta("kick", false)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_EXIT_DENIED); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_EXIT_DENIED); this.tmpTeleport = false; if (lastPlot.equals(BukkitUtil.getLocation(from).getPlot())) { player.teleport(from); @@ -819,9 +895,9 @@ import java.util.regex.Pattern; } } else if (now.equals(lastPlot)) { ForceFieldListener.handleForcefield(player, pp, now); - return; } else if (!plotEntry(pp, now) && this.tmpTeleport) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_ENTRY_DENIED); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_ENTRY_DENIED); this.tmpTeleport = false; player.teleport(from); to.setX(from.getBlockX()); @@ -831,26 +907,27 @@ import java.util.regex.Pattern; this.tmpTeleport = true; return; } - Integer border = area.getBorder(); + int border = area.getBorder(); if (z2 > border && this.tmpTeleport) { - to.setZ(z2 - 1); + to.setZ(border - 1); this.tmpTeleport = false; player.teleport(event.getTo()); this.tmpTeleport = true; - MainUtil.sendMessage(pp, C.BORDER); + MainUtil.sendMessage(pp, Captions.BORDER); } else if (z2 < -border && this.tmpTeleport) { - to.setZ(z2 + 1); + to.setZ(-border + 1); this.tmpTeleport = false; player.teleport(event.getTo()); this.tmpTeleport = true; - MainUtil.sendMessage(pp, C.BORDER); + MainUtil.sendMessage(pp, Captions.BORDER); } } } @EventHandler(priority = EventPriority.LOW) public void onChat(AsyncPlayerChatEvent event) { - if (event.isCancelled()) + if (event.isCancelled()) { return; + } PlotPlayer plotPlayer = BukkitUtil.getPlayer(event.getPlayer()); Location location = plotPlayer.getLocation(); @@ -864,12 +941,12 @@ import java.util.regex.Pattern; } event.setCancelled(true); String message = event.getMessage(); - String format = C.PLOT_CHAT_FORMAT.s(); + String format = Captions.PLOT_CHAT_FORMAT.s(); String sender = event.getPlayer().getDisplayName(); PlotId id = plot.getId(); Set recipients = event.getRecipients(); - Set spies = new HashSet<>(); recipients.clear(); + Set spies = new HashSet<>(); for (Entry entry : UUIDHandler.getPlayers().entrySet()) { PlotPlayer pp = entry.getValue(); if (pp.getAttribute("chatspy")) { @@ -884,15 +961,16 @@ import java.util.regex.Pattern; 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); + message = Captions.color(message); } String full = partial.replace("%msg%", message); for (Player receiver : recipients) { 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 = + Captions.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); } @@ -912,26 +990,27 @@ import java.util.regex.Pattern; 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); + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_GROUNDLEVEL)) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_DESTROY_GROUNDLEVEL); event.setCancelled(true); return; } } else if ( (location.getY() > area.MAX_BUILD_HEIGHT || location.getY() < area.MIN_BUILD_HEIGHT) && !Permissions - .hasPermission(plotPlayer, C.PERMISSION_ADMIN_BUILD_HEIGHTLIMIT)) { + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_HEIGHT_LIMIT)) { event.setCancelled(true); - MainUtil.sendMessage(plotPlayer, - C.HEIGHT_LIMIT.s().replace("{limit}", String.valueOf(area.MAX_BUILD_HEIGHT))); + MainUtil.sendMessage(plotPlayer, Captions.HEIGHT_LIMIT.s() + .replace("{limit}", String.valueOf(area.MAX_BUILD_HEIGHT))); } if (!plot.hasOwner()) { - if (Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { + if (Permissions + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED)) { return; } - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, - C.PERMISSION_ADMIN_DESTROY_UNOWNED); + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_DESTROY_UNOWNED); event.setCancelled(true); return; } @@ -942,16 +1021,17 @@ import java.util.regex.Pattern; .contains(PlotBlock.get(block.getType().name()))) { return; } - if (Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_DESTROY_OTHER)) { + if (Permissions + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { return; } - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, - C.PERMISSION_ADMIN_DESTROY_OTHER); + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + Captions.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); + } else if (Settings.Done.RESTRICT_BUILDING && plot.hasFlag(Flags.DONE)) { + if (!Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); return; } @@ -959,7 +1039,7 @@ import java.util.regex.Pattern; return; } PlotPlayer pp = BukkitUtil.getPlayer(player); - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_ROAD)) { + if (Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_DESTROY_ROAD)) { return; } if (PlotSquared.get().worldedit != null && pp.getAttribute("worldedit")) { @@ -968,7 +1048,8 @@ import java.util.regex.Pattern; return; } } - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_ROAD); + MainUtil + .sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_DESTROY_ROAD); event.setCancelled(true); } @@ -976,17 +1057,11 @@ import java.util.regex.Pattern; public void onBigBoom(EntityExplodeEvent event) { Location location = BukkitUtil.getLocation(event.getLocation()); PlotArea area = location.getPlotArea(); - if (area == null) { + boolean plotArea = location.isPlotArea(); + if (!plotArea) { if (!PlotSquared.get().hasPlotArea(location.getWorld())) { return; } - Iterator iterator = event.blockList().iterator(); - while (iterator.hasNext()) { - iterator.next(); - if (location.getPlotArea() != null) { - iterator.remove(); - } - } return; } Plot plot = area.getOwnedPlot(location); @@ -1039,7 +1114,7 @@ import java.util.regex.Pattern; plotExit(pp, plot); } if (PlotSquared.get().worldedit != null) { - if (!Permissions.hasPermission(pp, C.PERMISSION_WORLDEDIT_BYPASS)) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_WORLDEDIT_BYPASS)) { if (pp.getAttribute("worldedit")) { pp.removeAttribute("worldedit"); } @@ -1049,13 +1124,12 @@ import java.util.regex.Pattern; pp.deleteMeta("perm"); } Location loc = pp.getLocation(); - PlotArea area = PlotSquared.get().getPlotAreaAbs(loc); - if (area == null) { - return; - } - plot = area.getPlot(loc); - if (plot != null) { - plotEntry(pp, plot); + PlotArea area = loc.getPlotArea(); + if (loc.isPlotArea()) { + plot = loc.getPlot(); + if (plot != null) { + plotEntry(pp, plot); + } } } @@ -1067,8 +1141,9 @@ import java.util.regex.Pattern; PlotArea area = location.getPlotArea(); if (area != null) { Plot plot = area.getOwnedPlot(location); - if (plot != null && Flags.MOB_BREAK.isTrue(plot)) + if (plot != null && Flags.MOB_BREAK.isTrue(plot)) { return; + } event.setCancelled(true); } } @@ -1211,7 +1286,8 @@ import java.util.regex.Pattern; } if (!plot.hasOwner()) { PlotPlayer plotPlayer = BukkitUtil.getPlayer(player); - if (Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_DESTROY_UNOWNED)) { + if (Permissions + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED)) { return; } event.setCancelled(true); @@ -1223,7 +1299,7 @@ import java.util.regex.Pattern; Block block = event.getBlock(); if (destroy.isPresent() && destroy.get() .contains(PlotBlock.get(block.getType().name())) || Permissions - .hasPermission(plotPlayer, C.PERMISSION_ADMIN_DESTROY_OTHER)) { + .hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { return; } event.setCancelled(true); @@ -1232,7 +1308,7 @@ import java.util.regex.Pattern; return; } PlotPlayer plotPlayer = BukkitUtil.getPlayer(player); - if (Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_DESTROY_ROAD)) { + if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_DESTROY_ROAD)) { return; } event.setCancelled(true); @@ -1240,8 +1316,8 @@ import java.util.regex.Pattern; @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onFade(BlockFadeEvent event) { - Block b = event.getBlock(); - Location location = BukkitUtil.getLocation(b.getLocation()); + Block block = event.getBlock(); + Location location = BukkitUtil.getLocation(block.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; @@ -1251,7 +1327,7 @@ import java.util.regex.Pattern; event.setCancelled(true); return; } - switch (b.getType()) { + switch (block.getType()) { case ICE: if (Flags.ICE_MELT.isFalse(plot)) { event.setCancelled(true); @@ -1305,8 +1381,8 @@ import java.util.regex.Pattern; @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onGrow(BlockGrowEvent event) { - Block b = event.getBlock(); - Location location = BukkitUtil.getLocation(b.getLocation()); + Block block = event.getBlock(); + Location location = BukkitUtil.getLocation(block.getLocation()); if (location.isUnownedPlotArea()) { event.setCancelled(true); } @@ -1323,8 +1399,8 @@ import java.util.regex.Pattern; if (!PlotSquared.get().hasPlotArea(location.getWorld())) { return; } - for (Block b : event.getBlocks()) { - if (BukkitUtil.getLocation(b.getLocation().add(relative)).getPlotArea() != null) { + for (Block block1 : event.getBlocks()) { + if (BukkitUtil.getLocation(block1.getLocation().add(relative)).isPlotArea()) { event.setCancelled(true); return; } @@ -1337,8 +1413,8 @@ import java.util.regex.Pattern; return; } List blocks = event.getBlocks(); - for (Block b : blocks) { - Location bloc = BukkitUtil.getLocation(b.getLocation()); + for (Block block1 : blocks) { + Location bloc = BukkitUtil.getLocation(block1.getLocation()); if (!area.contains(bloc.getX(), bloc.getZ()) || !area .contains(bloc.getX() + relative.getBlockX(), bloc.getZ() + relative.getBlockZ())) { event.setCancelled(true); @@ -1365,7 +1441,7 @@ import java.util.regex.Pattern; try { for (Block pulled : event.getBlocks()) { location = BukkitUtil.getLocation(pulled.getLocation()); - if (location.getPlotArea() != null) { + if (location.isPlotArea()) { event.setCancelled(true); return; } @@ -1378,7 +1454,7 @@ import java.util.regex.Pattern; BlockFace dir = event.getDirection(); location = BukkitUtil.getLocation(block.getLocation() .add(dir.getModX() * 2, dir.getModY() * 2, dir.getModZ() * 2)); - if (location.getPlotArea() != null) { + if (location.isPlotArea()) { event.setCancelled(true); return; } @@ -1435,11 +1511,11 @@ import java.util.regex.Pattern; switch (type) { case WATER_BUCKET: case LAVA_BUCKET: { - if (event.getBlock().getType() == Material.DROPPER) + if (event.getBlock().getType() == Material.DROPPER) { return; + } BlockFace targetFace = - ((org.bukkit.material.Dispenser) event.getBlock().getState().getData()) - .getFacing(); + ((Directional) event.getBlock().getState().getData()).getFacing(); Location location = BukkitUtil.getLocation(event.getBlock().getRelative(targetFace).getLocation()); if (location.isPlotRoad()) { @@ -1463,7 +1539,7 @@ import java.util.regex.Pattern; if (area == null) { for (int i = blocks.size() - 1; i >= 0; i--) { location = BukkitUtil.getLocation(blocks.get(i).getLocation()); - if (location.getPlotArea() != null) { + if (location.isPlotArea()) { blocks.remove(i); } } @@ -1560,8 +1636,9 @@ import java.util.regex.Pattern; switch (newItem.getType()) { case LEGACY_BANNER: case PLAYER_HEAD: - if (newMeta != null) + if (newMeta != null) { break; + } default: return; } @@ -1577,37 +1654,41 @@ import java.util.regex.Pattern; switch (stateType) { case LEGACY_STANDING_BANNER: case LEGACY_WALL_BANNER: - if (itemType == Material.LEGACY_BANNER) + if (itemType == Material.LEGACY_BANNER) { break; + } case LEGACY_SKULL: - if (itemType == Material.LEGACY_SKULL_ITEM) + if (itemType == Material.LEGACY_SKULL_ITEM) { break; + } default: return; } } - Location l = BukkitUtil.getLocation(state.getLocation()); - PlotArea area = l.getPlotArea(); + Location location = BukkitUtil.getLocation(state.getLocation()); + PlotArea area = location.getPlotArea(); if (area == null) { return; } - Plot plot = area.getPlotAbs(l); + Plot plot = area.getPlotAbs(location); 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"); + MainUtil.sendMessage(pp, Captions.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"); + MainUtil + .sendMessage(pp, Captions.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"); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + "plots.admin.interact.other"); cancelled = true; } } @@ -1627,9 +1708,9 @@ import java.util.regex.Pattern; @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())) { + Projectile entity = event.getEntity(); + Location location = BukkitUtil.getLocation(entity); + if (!PlotSquared.get().hasPlotArea(location.getWorld())) { return; } if (!this.onProjectileHit(event)) { @@ -1640,37 +1721,48 @@ import java.util.regex.Pattern; @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onInteract(PlayerInteractAtEntityEvent e) { Entity entity = e.getRightClicked(); - if (!(entity instanceof ArmorStand)) { + if (!(entity instanceof ArmorStand) && !(entity instanceof ItemFrame)) { return; } - Location l = BukkitUtil.getLocation(e.getRightClicked().getLocation()); - PlotArea area = l.getPlotArea(); + Location location = BukkitUtil.getLocation(e.getRightClicked().getLocation()); + PlotArea area = location.getPlotArea(); if (area == null) { return; } - - EntitySpawnListener.test(entity); - - Plot plot = area.getPlotAbs(l); + EntitySpawnListener.testNether(entity); + Plot plot = location.getPlotAbs(); 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"); + MainUtil + .sendMessage(pp, Captions.NO_PERMISSION_EVENT, "plots.admin.interact.road"); e.setCancelled(true); } } else { - UUID uuid = pp.getUUID(); - if (!plot.isAdded(uuid)) { + if (Settings.Done.RESTRICT_BUILDING && plot.hasFlag(Flags.DONE)) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_OTHER); + e.setCancelled(true); + return; + } + } + if (!plot.hasOwner()) { + if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + "plots.admin.interact.unowned"); + e.setCancelled(true); + } + } else { + UUID uuid = pp.getUUID(); + if (plot.isAdded(uuid)) { + return; + } 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"); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + "plots.admin.interact.other"); e.setCancelled(true); } } @@ -1690,7 +1782,7 @@ import java.util.regex.Pattern; Iterator iterator = event.blockList().iterator(); while (iterator.hasNext()) { location = BukkitUtil.getLocation(iterator.next().getLocation()); - if (location.getPlotArea() != null) { + if (location.isPlotArea()) { iterator.remove(); } } @@ -1701,7 +1793,45 @@ import java.util.regex.Pattern; event.setCancelled(true); } event.blockList().removeIf( - b -> !plot.equals(area.getOwnedPlot(BukkitUtil.getLocation(b.getLocation())))); + blox -> !plot.equals(area.getOwnedPlot(BukkitUtil.getLocation(blox.getLocation())))); + } + + @EventHandler(priority = EventPriority.LOW) + public void onCancelledInteract(PlayerInteractEvent event) { + if (event.isCancelled() && event.getAction() == Action.RIGHT_CLICK_AIR) { + Player player = event.getPlayer(); + PlotPlayer pp = BukkitUtil.getPlayer(player); + PlotArea area = pp.getPlotAreaAbs(); + if (area == null) { + return; + } + if (event.getAction() == Action.RIGHT_CLICK_AIR) { + Material item = event.getItem().getType(); + if (item.toString().toLowerCase().endsWith("egg")) { + event.setCancelled(true); + event.setUseItemInHand(Event.Result.DENY); + } + } + ItemStack hand = player.getInventory().getItemInMainHand(); + ItemStack offHand = player.getInventory().getItemInOffHand(); + Material type = (hand == null) ? Material.AIR : hand.getType(); + Material offType = (offHand == null) ? Material.AIR : offHand.getType(); + if (type == Material.AIR) { + type = offType; + } + if (type.toString().toLowerCase().endsWith("egg")) { + Block block = player.getTargetBlockExact(5, FluidCollisionMode.SOURCE_ONLY); + if (block != null && block.getType() != Material.AIR) { + Location location = BukkitUtil.getLocation(block.getLocation()); + if (!EventUtil.manager + .checkPlayerBlockEvent(pp, PlayerBlockEventType.SPAWN_MOB, location, + new BukkitLazyBlock(PlotBlock.get(type.toString())), true)) { + event.setCancelled(true); + event.setUseItemInHand(Event.Result.DENY); + } + } + } + } } @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) @@ -1834,8 +1964,20 @@ import java.util.regex.Pattern; case CHAIN_COMMAND_BLOCK: case REPEATING_COMMAND_BLOCK: - case SIGN: - case WALL_SIGN: + case LEGACY_SIGN: + case LEGACY_WALL_SIGN: + case OAK_SIGN: + case ACACIA_SIGN: + case ACACIA_WALL_SIGN: + case BIRCH_SIGN: + case BIRCH_WALL_SIGN: + case DARK_OAK_SIGN: + case DARK_OAK_WALL_SIGN: + case JUNGLE_SIGN: + case JUNGLE_WALL_SIGN: + case OAK_WALL_SIGN: + case SPRUCE_SIGN: + case SPRUCE_WALL_SIGN: case REDSTONE_TORCH: case REDSTONE_WALL_TORCH: @@ -1851,10 +1993,17 @@ import java.util.regex.Pattern; case COMMAND_BLOCK: case COMPARATOR: case CRAFTING_TABLE: + //todo re-evaluate adding lectern here + case LECTERN: + case GRINDSTONE: + case LOOM: + case SMOKER: + case STONECUTTER: case DISPENSER: case DROPPER: case ENCHANTING_TABLE: case FURNACE: + case BLAST_FURNACE: case HOPPER: case JUKEBOX: case LEVER: @@ -1866,36 +2015,39 @@ import java.util.regex.Pattern; eventType = PlayerBlockEventType.TELEPORT_OBJECT; break; default: - int blockId = ((LegacyPlotBlock) PlotSquared.get().IMP.getLegacyMappings() - .fromStringToLegacy(blockType.name())).id; - if (blockId > 197) { + if (blockType.isInteractable()) { eventType = PlayerBlockEventType.INTERACT_BLOCK; } - break; } 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(); - if (type == Material.AIR) { + ItemStack hand = player.getInventory().getItemInMainHand(); + ItemStack offHand = player.getInventory().getItemInOffHand(); + Material type = (hand == null) ? Material.AIR : hand.getType(); + Material offType = (offHand == null) ? Material.AIR : offHand.getType(); + if ((type == Material.AIR && offType != Material.AIR && !player.isSneaking() + && blockType.isInteractable()) || (type == Material.AIR + && offType == Material.AIR)) { eventType = PlayerBlockEventType.INTERACT_BLOCK; break; } - if (type == null || type.isBlock()) { + if (type == Material.AIR) { + type = offType; + } + if (type.isBlock()) { location = BukkitUtil .getLocation(block.getRelative(event.getBlockFace()).getLocation()); eventType = PlayerBlockEventType.PLACE_BLOCK; break; } - Material handType = hand.getType(); - lb = new BukkitLazyBlock(PlotBlock.get(handType.toString())); - if (handType.toString().endsWith("egg")) { + lb = new BukkitLazyBlock(PlotBlock.get(type.toString())); + if (type.toString().toLowerCase().endsWith("egg")) { eventType = PlayerBlockEventType.SPAWN_MOB; } else { - switch (handType) { + switch (type) { case FIREWORK_ROCKET: case FIREWORK_STAR: eventType = PlayerBlockEventType.SPAWN_MOB; @@ -1957,12 +2109,6 @@ import java.util.regex.Pattern; case TNT_MINECART: eventType = PlayerBlockEventType.PLACE_VEHICLE; break; - case ITEM_FRAME: - case PAINTING: - location = BukkitUtil - .getLocation(block.getRelative(event.getBlockFace()).getLocation()); - eventType = PlayerBlockEventType.PLACE_HANGING; - break; default: eventType = PlayerBlockEventType.INTERACT_BLOCK; break; @@ -2096,8 +2242,8 @@ import java.util.regex.Pattern; @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockBurn(BlockBurnEvent event) { - Block b = event.getBlock(); - Location location = BukkitUtil.getLocation(b.getLocation()); + Block block = event.getBlock(); + Location location = BukkitUtil.getLocation(block.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { @@ -2141,19 +2287,21 @@ import java.util.regex.Pattern; if (player != null) { PlotPlayer pp = BukkitUtil.getPlayer(player); if (plot == null) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD); + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_ROAD); event.setCancelled(true); } } else if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { - MainUtil - .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); } } else if (!plot.isAdded(pp.getUUID())) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); } } else if (Flags.BLOCK_IGNITION.isFalse(plot)) { @@ -2206,10 +2354,10 @@ import java.util.regex.Pattern; @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBucketEmpty(PlayerBucketEmptyEvent event) { BlockFace bf = event.getBlockFace(); - Block b = + Block block = event.getBlockClicked().getLocation().add(bf.getModX(), bf.getModY(), bf.getModZ()) .getBlock(); - Location location = BukkitUtil.getLocation(b.getLocation()); + Location location = BukkitUtil.getLocation(block.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; @@ -2217,29 +2365,33 @@ import java.util.regex.Pattern; PlotPlayer pp = BukkitUtil.getPlayer(event.getPlayer()); Plot plot = area.getPlot(location); if (plot == null) { - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) { + if (Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { return; } - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_ROAD); event.setCancelled(true); } else if (!plot.hasOwner()) { - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { + if (Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { return; } - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); } else if (!plot.isAdded(pp.getUUID())) { - if (Flags.USE.contains(plot, PlotBlock.get(event.getBucket().getId(), 0))) { + if (Flags.USE.contains(plot, PlotBlock.get(event.getBucket().name()))) { return; } - if (Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { + if (Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { return; } - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); - } else if (Settings.Done.RESTRICT_BUILDING && plot.getFlags().containsKey(Flags.DONE)) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + } else if (Settings.Done.RESTRICT_BUILDING && plot.hasFlag(Flags.DONE)) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); } } @@ -2263,8 +2415,8 @@ import java.util.regex.Pattern; @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBucketFill(PlayerBucketFillEvent event) { - Block b = event.getBlockClicked(); - Location location = BukkitUtil.getLocation(b.getLocation()); + Block blockClicked = event.getBlockClicked(); + Location location = BukkitUtil.getLocation(blockClicked.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; @@ -2273,17 +2425,18 @@ import java.util.regex.Pattern; PlotPlayer plotPlayer = BukkitUtil.getPlayer(player); Plot plot = area.getPlot(location); if (plot == null) { - if (Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_BUILD_ROAD)) { + if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { return; } - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD); + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_ROAD); event.setCancelled(true); } else if (!plot.hasOwner()) { - if (Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { + if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { return; } - MainUtil - .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); } else if (!plot.isAdded(plotPlayer.getUUID())) { Optional> use = plot.getFlag(Flags.USE); @@ -2291,15 +2444,16 @@ import java.util.regex.Pattern; if (use.isPresent() && use.get().contains(PlotBlock.get(block.getType().name()))) { return; } - if (Permissions.hasPermission(plotPlayer, C.PERMISSION_ADMIN_BUILD_OTHER)) { + if (Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { return; } - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_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); + } else if (Settings.Done.RESTRICT_BUILDING && plot.hasFlag(Flags.DONE)) { + if (!Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); } } @@ -2326,8 +2480,8 @@ import java.util.regex.Pattern; @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onHangingPlace(HangingPlaceEvent event) { - Block b = event.getBlock().getRelative(event.getBlockFace()); - Location location = BukkitUtil.getLocation(b.getLocation()); + Block block = event.getBlock().getRelative(event.getBlockFace()); + Location location = BukkitUtil.getLocation(block.getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { return; @@ -2336,24 +2490,25 @@ import java.util.regex.Pattern; PlotPlayer pp = BukkitUtil.getPlayer(p); Plot plot = area.getPlot(location); if (plot == null) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD); + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_ROAD); event.setCancelled(true); } } else { if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_UNOWNED)) { - MainUtil - .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_UNOWNED); + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); } return; } if (!plot.isAdded(pp.getUUID())) { 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); + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); } return; @@ -2379,24 +2534,24 @@ import java.util.regex.Pattern; PlotPlayer pp = BukkitUtil.getPlayer(p); 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); + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_DESTROY_ROAD)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.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); + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_DESTROY_UNOWNED); event.setCancelled(true); } } else if (!plot.isAdded(pp.getUUID())) { if (plot.getFlag(Flags.HANGING_BREAK, false)) { return; } - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_DESTROY_OTHER)) { - MainUtil - .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_DESTROY_OTHER); + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_DESTROY_OTHER); event.setCancelled(true); } } @@ -2414,17 +2569,17 @@ import java.util.regex.Pattern; 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); + .hasPermission(player, Captions.PERMISSION_ADMIN_DESTROY_UNOWNED)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION_EVENT, + Captions.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); + .hasPermission(player, Captions.PERMISSION_ADMIN_DESTROY_OTHER)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_DESTROY_OTHER); event.setCancelled(true); } } @@ -2447,14 +2602,15 @@ import java.util.regex.Pattern; PlotPlayer pp = BukkitUtil.getPlayer(p); Plot plot = area.getPlot(location); if (plot == null) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_ROAD)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_ROAD); + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_INTERACT_ROAD)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_INTERACT_ROAD); event.setCancelled(true); } } else if (!plot.hasOwner()) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_UNOWNED)) { - MainUtil - .sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_UNOWNED); + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_INTERACT_UNOWNED)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_INTERACT_UNOWNED); event.setCancelled(true); } } else if (!plot.isAdded(pp.getUUID())) { @@ -2481,8 +2637,9 @@ import java.util.regex.Pattern; if (entity instanceof ItemFrame && plot.getFlag(Flags.MISC_INTERACT, false)) { return; } - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_INTERACT_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_INTERACT_OTHER); + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_INTERACT_OTHER)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_INTERACT_OTHER); event.setCancelled(true); } } @@ -2490,26 +2647,26 @@ import java.util.regex.Pattern; @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onVehicleDestroy(VehicleDestroyEvent event) { - Location l = BukkitUtil.getLocation(event.getVehicle()); - PlotArea area = l.getPlotArea(); + Location location = BukkitUtil.getLocation(event.getVehicle()); + PlotArea area = location.getPlotArea(); if (area == null) { return; } - Entity d = event.getAttacker(); - if (d instanceof Player) { - Player p = (Player) d; + Entity attacker = event.getAttacker(); + if (attacker instanceof Player) { + Player p = (Player) attacker; PlotPlayer pp = BukkitUtil.getPlayer(p); - Plot plot = area.getPlot(l); + Plot plot = area.getPlot(location); 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, Captions.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, + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.unowned"); event.setCancelled(true); return; @@ -2521,7 +2678,7 @@ import java.util.regex.Pattern; return; } if (!Permissions.hasPermission(pp, "plots.admin.vehicle.break.other")) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, "plots.admin.vehicle.break.other"); event.setCancelled(true); } @@ -2533,8 +2690,8 @@ import java.util.regex.Pattern; @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPotionSplash(PotionSplashEvent event) { ThrownPotion damager = event.getPotion(); - Location l = BukkitUtil.getLocation(damager); - if (!PlotSquared.get().hasPlotArea(l.getWorld())) { + Location location = BukkitUtil.getLocation(damager); + if (!PlotSquared.get().hasPlotArea(location.getWorld())) { return; } int count = 0; @@ -2551,9 +2708,9 @@ import java.util.regex.Pattern; @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.HIGHEST) public void onEntityCombustByEntity(EntityCombustByEntityEvent event) { - EntityDamageByEntityEvent eventChange = null; - eventChange = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), - EntityDamageEvent.DamageCause.FIRE_TICK, (double) event.getDuration()); + EntityDamageByEntityEvent eventChange = + new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), + EntityDamageEvent.DamageCause.FIRE_TICK, (double) event.getDuration()); onEntityDamageByEntityEvent(eventChange); if (eventChange.isCancelled()) { event.setCancelled(true); @@ -2563,12 +2720,21 @@ import java.util.regex.Pattern; @EventHandler(priority = EventPriority.HIGHEST) public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) { Entity damager = event.getDamager(); - Location l = BukkitUtil.getLocation(damager); - if (!PlotSquared.get().hasPlotArea(l.getWorld())) { + Location location = BukkitUtil.getLocation(damager); + if (!PlotSquared.get().hasPlotArea(location.getWorld())) { return; } Entity victim = event.getEntity(); - if (!entityDamage(damager, victim)) { +/* + if (victim.getType().equals(EntityType.ITEM_FRAME)) { + Plot plot = BukkitUtil.getLocation(victim).getPlot(); + if (plot != null && !plot.isAdded(damager.getUniqueId())) { + event.setCancelled(true); + return; + } + } +*/ + if (!entityDamage(damager, victim, event.getCause())) { if (event.isCancelled()) { if (victim instanceof Ageable) { Ageable ageable = (Ageable) victim; @@ -2582,18 +2748,37 @@ import java.util.regex.Pattern; } } - public boolean entityDamage(Entity damager, Entity victim) { + private boolean entityDamage(Entity damager, Entity victim) { + return entityDamage(damager, victim, null); + } + + private boolean entityDamage(Entity damager, Entity victim, + EntityDamageEvent.DamageCause cause) { 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; + if (dArea != null && dArea.contains(vloc.getX(), vloc.getZ())) { + vArea = dArea; + } else { + vArea = vloc.getPlotArea(); + } if (dArea == null && vArea == null) { return true; } - Plot dplot = dArea != null ? dArea.getPlot(dloc) : null; - Plot vplot = vArea != null ? vArea.getPlot(vloc) : null; + Plot dplot; + if (dArea != null) { + dplot = dArea.getPlot(dloc); + } else { + dplot = null; + } + Plot vplot; + if (vArea != null) { + vplot = vArea.getPlot(vloc); + } else { + vplot = null; + } Plot plot; String stub; @@ -2657,20 +2842,26 @@ import java.util.regex.Pattern; if (victim instanceof Hanging) { // hanging if (plot != null && (plot.getFlag(Flags.HANGING_BREAK, false) || plot .isAdded(plotPlayer.getUUID()))) { + if (Settings.Done.RESTRICT_BUILDING && plot.hasFlag(Flags.DONE)) { + if (!Permissions.hasPermission(plotPlayer, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, Captions.PERMISSION_ADMIN_BUILD_OTHER); + return false; + } + } return true; } if (!Permissions.hasPermission(plotPlayer, "plots.admin.destroy." + stub)) { - MainUtil.sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, "plots.admin.destroy." + stub); return false; } - } else if (victim.getEntityId() == 30) { + } else if (victim.getType() == EntityType.ARMOR_STAND) { 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, + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, "plots.admin.destroy." + stub); return false; } @@ -2681,8 +2872,8 @@ import java.util.regex.Pattern; return true; } if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { - MainUtil - .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + "plots.admin.pve." + stub); return false; } } else if (victim instanceof Tameable) { // victim is tameable @@ -2691,15 +2882,15 @@ import java.util.regex.Pattern; return true; } if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { - MainUtil - .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); + MainUtil.sendMessage(plotPlayer, Captions.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, + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, "plots.admin.pvp." + stub); return false; } else { @@ -2707,8 +2898,8 @@ import java.util.regex.Pattern; } } if (!Permissions.hasPermission(plotPlayer, "plots.admin.pvp." + stub)) { - MainUtil - .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pvp." + stub); + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + "plots.admin.pvp." + stub); return false; } } else if (victim instanceof Creature) { // victim is animal @@ -2717,8 +2908,8 @@ import java.util.regex.Pattern; return true; } if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { - MainUtil - .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + "plots.admin.pve." + stub); return false; } } else if (victim instanceof Vehicle) { // Vehicles are managed in vehicle destroy event @@ -2729,8 +2920,8 @@ import java.util.regex.Pattern; return true; } if (!Permissions.hasPermission(plotPlayer, "plots.admin.pve." + stub)) { - MainUtil - .sendMessage(plotPlayer, C.NO_PERMISSION_EVENT, "plots.admin.pve." + stub); + MainUtil.sendMessage(plotPlayer, Captions.NO_PERMISSION_EVENT, + "plots.admin.pve." + stub); return false; } } @@ -2739,36 +2930,43 @@ import java.util.regex.Pattern; .equals(dplot.guessOwner(), vplot.guessOwner()))) { return vplot != null && Flags.PVE.isTrue(vplot); } + //disable the firework damage. too much of a headache to support at the moment. + if (vplot != null) { + if (EntityDamageEvent.DamageCause.ENTITY_EXPLOSION == cause + && damager.getType() == EntityType.FIREWORK) { + return false; + } + } return ((vplot != null && Flags.PVE.isTrue(vplot)) || !(damager instanceof Arrow && !(victim instanceof Creature))); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerEggThrow(PlayerEggThrowEvent event) { - Location l = BukkitUtil.getLocation(event.getEgg().getLocation()); - PlotArea area = l.getPlotArea(); + Location location = BukkitUtil.getLocation(event.getEgg().getLocation()); + PlotArea area = location.getPlotArea(); if (area == null) { return; } Player player = event.getPlayer(); PlotPlayer plotPlayer = BukkitUtil.getPlayer(player); - Plot plot = area.getPlot(l); + Plot plot = area.getPlot(location); 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, Captions.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, + MainUtil.sendMessage(plotPlayer, Captions.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, Captions.NO_PERMISSION_EVENT, + "plots.admin.projectile.other"); event.setHatching(false); } } @@ -2786,15 +2984,15 @@ import java.util.regex.Pattern; 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)) { + && !Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_HEIGHT_LIMIT)) { event.setCancelled(true); - MainUtil.sendMessage(pp, - C.HEIGHT_LIMIT.s().replace("{limit}", String.valueOf(area.MAX_BUILD_HEIGHT))); + MainUtil.sendMessage(pp, Captions.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); + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_UNOWNED)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_UNOWNED); event.setCancelled(true); return; } @@ -2806,14 +3004,16 @@ import java.util.regex.Pattern; return; } } - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); return; } - } else if (Settings.Done.RESTRICT_BUILDING && plot.getFlags().containsKey(Flags.DONE)) { - if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_OTHER)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_OTHER); + } else if (Settings.Done.RESTRICT_BUILDING && plot.hasFlag(Flags.DONE)) { + if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_OTHER)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_OTHER); event.setCancelled(true); return; } @@ -2824,8 +3024,9 @@ import java.util.regex.Pattern; sendBlockChange(block.getLocation(), block.getBlockData()); } } - } else if (!Permissions.hasPermission(pp, C.PERMISSION_ADMIN_BUILD_ROAD)) { - MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, C.PERMISSION_ADMIN_BUILD_ROAD); + } else if (!Permissions.hasPermission(pp, Captions.PERMISSION_ADMIN_BUILD_ROAD)) { + MainUtil.sendMessage(pp, Captions.NO_PERMISSION_EVENT, + Captions.PERMISSION_ADMIN_BUILD_ROAD); event.setCancelled(true); } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlotPlusListener.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlotPlusListener.java index a4df7c6b3..b103ed7de 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlotPlusListener.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/PlotPlusListener.java @@ -4,6 +4,7 @@ import com.github.intellectualsites.plotsquared.bukkit.events.PlayerEnterPlotEve 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.flag.IntervalFlag; import com.github.intellectualsites.plotsquared.plot.listener.PlotListener; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; @@ -30,52 +31,49 @@ import java.util.Map.Entry; import java.util.Optional; import java.util.UUID; -@SuppressWarnings("unused") -public class PlotPlusListener extends PlotListener implements Listener { +@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() { - if (!healRunnable.isEmpty()) { - for (Iterator> iterator = - healRunnable.entrySet().iterator(); iterator.hasNext(); ) { - Entry entry = iterator.next(); - Interval value = entry.getValue(); - ++value.count; - if (value.count == value.interval) { - value.count = 0; - Player player = Bukkit.getPlayer(entry.getKey()); - if (player == null) { - iterator.remove(); - continue; - } - double level = player.getHealth(); - if (level != value.max) { - player.setHealth(Math.min(level + value.amount, value.max)); - } + plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, () -> { + if (!healRunnable.isEmpty()) { + for (Iterator> iterator = + healRunnable.entrySet().iterator(); iterator.hasNext(); ) { + Entry entry = iterator.next(); + Interval value = entry.getValue(); + ++value.count; + if (value.count == value.interval) { + value.count = 0; + Player player = Bukkit.getPlayer(entry.getKey()); + if (player == null) { + iterator.remove(); + continue; + } + double level = player.getHealth(); + if (level != value.max) { + player.setHealth(Math.min(level + value.amount, value.max)); } } } - if (!feedRunnable.isEmpty()) { - for (Iterator> iterator = - feedRunnable.entrySet().iterator(); iterator.hasNext(); ) { - Entry entry = iterator.next(); - Interval value = entry.getValue(); - ++value.count; - if (value.count == value.interval) { - value.count = 0; - Player player = Bukkit.getPlayer(entry.getKey()); - if (player == null) { - iterator.remove(); - continue; - } - int level = player.getFoodLevel(); - if (level != value.max) { - player.setFoodLevel(Math.min(level + value.amount, value.max)); - } + } + if (!feedRunnable.isEmpty()) { + for (Iterator> iterator = + feedRunnable.entrySet().iterator(); iterator.hasNext(); ) { + Entry entry = iterator.next(); + Interval value = entry.getValue(); + ++value.count; + if (value.count == value.interval) { + value.count = 0; + Player player = Bukkit.getPlayer(entry.getKey()); + if (player == null) { + iterator.remove(); + continue; + } + int level = player.getFoodLevel(); + if (level != value.max) { + player.setFoodLevel(Math.min(level + value.amount, value.max)); } } } @@ -83,8 +81,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; @@ -103,13 +100,11 @@ 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; } - Player player = (Player) event.getEntity(); - Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); + Plot plot = BukkitUtil.getLocation(event.getEntity()).getOwnedPlot(); if (plot == null) { return; } @@ -118,8 +113,7 @@ public class PlotPlusListener extends PlotListener implements Listener { } } - @EventHandler - public void onItemDrop(PlayerDropItemEvent event) { + @EventHandler public void onItemDrop(PlayerDropItemEvent event) { Player player = event.getPlayer(); PlotPlayer pp = BukkitUtil.getPlayer(player); Plot plot = BukkitUtil.getLocation(player).getOwnedPlot(); @@ -134,27 +128,24 @@ 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); - feed.ifPresent( value -> feedRunnable.put(player.getUniqueId(), new Interval(value[0], value[1], 20)) - ); - Optional heal = plot.getFlag(Flags.HEAL); - heal.ifPresent( value -> healRunnable.put(player.getUniqueId(), new Interval(value[0], value[1], 20)) - ); + Optional feed = plot.getFlag(Flags.FEED); + feed.ifPresent(value -> feedRunnable + .put(player.getUniqueId(), new Interval(value.getVal1(), value.getVal2(), 20))); + Optional heal = plot.getFlag(Flags.HEAL); + heal.ifPresent(value -> healRunnable + .put(player.getUniqueId(), new Interval(value.getVal1(), value.getVal2(), 20))); } - @EventHandler - public void onPlayerQuit(PlayerQuitEvent event) { + @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { Player player = event.getPlayer(); 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()) { @@ -165,8 +156,7 @@ public class PlotPlusListener extends PlotListener implements Listener { healRunnable.remove(leaver.getUniqueId()); } - @EventHandler - public void onItemPickup(EntityPickupItemEvent event) { + @EventHandler public void onItemPickup(EntityPickupItemEvent event) { LivingEntity ent = event.getEntity(); if (ent instanceof Player) { Player player = (Player) ent; diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/SingleWorldListener.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/SingleWorldListener.java index 6a3e26d59..fc13147dd 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/SingleWorldListener.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/SingleWorldListener.java @@ -22,17 +22,14 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils @SuppressWarnings("unused") public class SingleWorldListener implements Listener { private Method methodGetHandleChunk; - private Field mustSave, done, lit, s; + private Field mustSave; public SingleWorldListener(Plugin plugin) throws Exception { ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk"); ReflectionUtils.RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle").getRealMethod(); - this.mustSave = classChunk.getField("mustSave").getRealField(); try { - this.done = classChunk.getField("done").getRealField(); - this.lit = classChunk.getField("lit").getRealField(); - this.s = classChunk.getField("s").getRealField(); + this.mustSave = classChunk.getField("mustSave").getRealField(); } catch (Throwable ignore) { ignore.printStackTrace(); } @@ -42,14 +39,9 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils public void markChunkAsClean(Chunk chunk) { try { Object nmsChunk = methodGetHandleChunk.invoke(chunk); - if (done != null) - this.done.set(nmsChunk, true); - if (mustSave != null) + 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(); } @@ -59,10 +51,12 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils World world = event.getWorld(); String name = world.getName(); PlotAreaManager man = PlotSquared.get().getPlotAreaManager(); - if (!(man instanceof SinglePlotAreaManager)) + if (!(man instanceof SinglePlotAreaManager)) { return; - if (!isPlotId(name)) + } + if (!isPlotId(name)) { return; + } markChunkAsClean(event.getChunk()); } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/WorldEvents.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/WorldEvents.java index 98d6c0f5a..afa821975 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/WorldEvents.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/listeners/WorldEvents.java @@ -12,25 +12,26 @@ import org.bukkit.event.Listener; import org.bukkit.event.world.WorldInitEvent; import org.bukkit.generator.ChunkGenerator; -@SuppressWarnings("unused") 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 = PlotSquared.get().getPlotAreaManager(); - if (manager instanceof SinglePlotAreaManager) { - SinglePlotAreaManager single = (SinglePlotAreaManager) manager; - if (single.isWorld(name)) { - world.setKeepSpawnInMemory(false); - return; - } - } - ChunkGenerator gen = world.getGenerator(); - if (gen instanceof GeneratorWrapper) { - PlotSquared.get().loadWorld(name, (GeneratorWrapper) gen); - } else { - PlotSquared.get().loadWorld(name, new BukkitPlotGenerator(name, gen)); - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onWorldInit(WorldInitEvent event) { + World world = event.getWorld(); + String name = world.getName(); + PlotAreaManager manager = PlotSquared.get().getPlotAreaManager(); + if (manager instanceof SinglePlotAreaManager) { + SinglePlotAreaManager single = (SinglePlotAreaManager) manager; + if (single.isWorld(name)) { + world.setKeepSpawnInMemory(false); + return; + } } + ChunkGenerator gen = world.getGenerator(); + if (gen instanceof GeneratorWrapper) { + PlotSquared.get().loadWorld(name, (GeneratorWrapper) gen); + } else { + PlotSquared.get().loadWorld(name, new BukkitPlotGenerator(name, gen)); + } + } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitOfflinePlayer.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitOfflinePlayer.java index 390e9d9be..7c52a25de 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitOfflinePlayer.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitOfflinePlayer.java @@ -2,6 +2,7 @@ package com.github.intellectualsites.plotsquared.bukkit.object; import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer; import org.bukkit.OfflinePlayer; +import org.jetbrains.annotations.NotNull; import java.util.UUID; @@ -19,7 +20,7 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer { this.player = player; } - @Override public UUID getUUID() { + @NotNull @Override public UUID getUUID() { return this.player.getUniqueId(); } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitPlayer.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitPlayer.java index 1255c0fc4..7a34a9fdc 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitPlayer.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/BukkitPlayer.java @@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.bukkit.object; 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.Captions; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; @@ -19,6 +19,7 @@ import org.bukkit.event.EventException; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.permissions.PermissionAttachmentInfo; import org.bukkit.plugin.RegisteredListener; +import org.jetbrains.annotations.NotNull; import javax.annotation.Nonnull; import java.util.Arrays; @@ -28,6 +29,7 @@ import java.util.stream.Collectors; public class BukkitPlayer extends PlotPlayer { + private static boolean CHECK_EFFECTIVE = true; public final Player player; private boolean offline; private UUID uuid; @@ -57,7 +59,7 @@ public class BukkitPlayer extends PlotPlayer { return location == null ? BukkitUtil.getLocation(this.player) : location; } - @Override public UUID getUUID() { + @NotNull @Override public UUID getUUID() { if (this.uuid == null) { this.uuid = UUIDHandler.getUUID(this); } @@ -82,6 +84,11 @@ public class BukkitPlayer extends PlotPlayer { return true; } + @Override + public void sendTitle(String title, String subtitle, int fadeIn, int stay, int fadeOut) { + player.sendTitle(title, subtitle, fadeIn, stay, fadeOut); + } + private void callEvent(final Event event) { Preconditions.checkNotNull(event, "Event cannot be null"); @@ -106,15 +113,15 @@ public class BukkitPlayer extends PlotPlayer { } @Override public int hasPermissionRange(final String stub, final int range) { - if (hasPermission(C.PERMISSION_ADMIN.s())) { + if (hasPermission(Captions.PERMISSION_ADMIN.s())) { return Integer.MAX_VALUE; } final String[] nodes = stub.split("\\."); final StringBuilder n = new StringBuilder(); for (int i = 0; i < (nodes.length - 1); i++) { n.append(nodes[i]).append("."); - if (!stub.equals(n + C.PERMISSION_STAR.s())) { - if (hasPermission(n + C.PERMISSION_STAR.s())) { + if (!stub.equals(n + Captions.PERMISSION_STAR.s())) { + if (hasPermission(n + Captions.PERMISSION_STAR.s())) { return Integer.MAX_VALUE; } } @@ -123,27 +130,43 @@ public class BukkitPlayer extends PlotPlayer { return Integer.MAX_VALUE; } int max = 0; - String stubPlus = stub + "."; + if (CHECK_EFFECTIVE) { + boolean hasAny = false; + String stubPlus = stub + "."; final Set effective = player.getEffectivePermissions(); - if (!effective.isEmpty()) { - for (PermissionAttachmentInfo attach : effective) { - String perm = attach.getPermission(); - if (perm.startsWith(stubPlus)) { - 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 (!effective.isEmpty()) { + for (PermissionAttachmentInfo attach : effective) { + String permStr = attach.getPermission(); + if (permStr.startsWith(stubPlus)) { + hasAny = true; + String end = permStr.substring(stubPlus.length()); + if (MathMan.isInteger(end)) { + int val = Integer.parseInt(end); + if (val > range) { + return val; + } + if (val > max) { + max = val; + } + } } } - } - } else { - for (int i = range; i > 0; i--) { - if (hasPermission(stub + "." + i)) { - return i; + if (hasAny) { + return max; } + // Workaround + for (PermissionAttachmentInfo attach : effective) { + String permStr = attach.getPermission(); + if (permStr.startsWith("plots.") && !permStr.equals("plots.use")) { + return max; + } + } + CHECK_EFFECTIVE = false; + } + } + for (int i = range; i > 0; i--) { + if (hasPermission(stub + "." + i)) { + return i; } } return max; @@ -202,8 +225,6 @@ public class BukkitPlayer extends PlotPlayer { this.player.setPlayerWeather(WeatherType.DOWNFALL); break; case RESET: - this.player.resetPlayerWeather(); - break; default: this.player.resetPlayerWeather(); break; @@ -238,8 +259,6 @@ public class BukkitPlayer extends PlotPlayer { this.player.setGameMode(GameMode.SPECTATOR); break; case SURVIVAL: - this.player.setGameMode(GameMode.SURVIVAL); - break; default: this.player.setGameMode(GameMode.SURVIVAL); break; @@ -267,14 +286,15 @@ public class BukkitPlayer extends PlotPlayer { Preconditions.checkNotNull(id, "Specified block cannot be null"); if (PlotBlock.isEverything(id) || id.isAir()) { // Let's just stop all the discs because why not? - for (final Sound sound : Arrays.stream(Sound.values()).filter(sound -> sound.name().contains("DISC")).collect( - Collectors.toList())) { + for (final Sound sound : Arrays.stream(Sound.values()) + .filter(sound -> sound.name().contains("DISC")).collect(Collectors.toList())) { player.stopSound(sound); } // this.player.playEffect(BukkitUtil.getLocation(location), Effect.RECORD_PLAY, Material.AIR); } else { // this.player.playEffect(BukkitUtil.getLocation(location), Effect.RECORD_PLAY, id.to(Material.class)); - this.player.playSound(BukkitUtil.getLocation(location), Sound.valueOf(id.to(Material.class).name()), Float.MAX_VALUE, 1f); + this.player.playSound(BukkitUtil.getLocation(location), + Sound.valueOf(id.to(Material.class).name()), Float.MAX_VALUE, 1f); } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/ReplicatingEntityWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/ReplicatingEntityWrapper.java index e71373771..769fcc9b3 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/ReplicatingEntityWrapper.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/entity/ReplicatingEntityWrapper.java @@ -1,7 +1,12 @@ package com.github.intellectualsites.plotsquared.bukkit.object.entity; import com.github.intellectualsites.plotsquared.plot.PlotSquared; -import org.bukkit.*; +import org.bukkit.Art; +import org.bukkit.DyeColor; +import org.bukkit.Location; +import org.bukkit.Rotation; +import org.bukkit.TreeSpecies; +import org.bukkit.World; import org.bukkit.block.BlockFace; import org.bukkit.entity.*; import org.bukkit.inventory.EntityEquipment; @@ -10,13 +15,15 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.util.EulerAngle; import org.bukkit.util.Vector; +import java.util.List; + public final class ReplicatingEntityWrapper extends EntityWrapper { private final short depth; private final int hash; private final EntityBaseStats base = new EntityBaseStats(); - public ItemStack[] inventory; + private ItemStack[] inventory; // Extended private ItemStack stack; private byte dataByte; @@ -38,9 +45,9 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { if (depth == 0) { return; } - Entity passenger = entity.getPassenger(); - if (passenger != null) { - this.base.passenger = new ReplicatingEntityWrapper(passenger, depth); + List passengers = entity.getPassengers(); + if (passengers.size() > 0) { + this.base.passenger = new ReplicatingEntityWrapper(passengers.get(0), depth); } this.base.fall = entity.getFallDistance(); this.base.fire = (short) entity.getFireTicks(); @@ -61,7 +68,6 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { this.dataByte = getOrdinal(TreeSpecies.values(), boat.getWoodType()); return; case ARROW: - case COMPLEX_PART: case EGG: case ENDER_CRYSTAL: case ENDER_PEARL: @@ -85,15 +91,14 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { case MINECART_FURNACE: case SPLASH_POTION: case THROWN_EXP_BOTTLE: - case WEATHER: case WITHER_SKULL: case UNKNOWN: - case TIPPED_ARROW: case SPECTRAL_ARROW: case SHULKER_BULLET: case DRAGON_FIREBALL: - case LINGERING_POTION: case AREA_EFFECT_CLOUD: + case TRIDENT: + case LLAMA_SPIT: // Do this stuff later return; // MISC // @@ -132,13 +137,21 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { // START AGEABLE // // START TAMEABLE // case HORSE: - Horse horse = (Horse) entity; + case DONKEY: + case LLAMA: + case MULE: + case SKELETON_HORSE: + AbstractHorse horse = (AbstractHorse) entity; this.horse = new HorseStats(); this.horse.jump = horse.getJumpStrength(); - this.horse.chest = horse.isCarryingChest(); - this.horse.variant = horse.getVariant(); - this.horse.style = horse.getStyle(); - this.horse.color = horse.getColor(); + if (horse instanceof ChestedHorse) { + ChestedHorse horse1 = (ChestedHorse) horse; + this.horse.chest = horse1.isCarryingChest(); + } + //todo these horse features need fixing + //this.horse.variant = horse.getVariant(); + //this.horse.style = horse.getStyle(); + //this.horse.color = horse.getColor(); storeTameable(horse); storeAgeable(horse); storeLiving(horse); @@ -152,9 +165,14 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { storeLiving((LivingEntity) entity); return; // END TAMEABLE // + //todo fix sheep case SHEEP: Sheep sheep = (Sheep) entity; - this.dataByte = (byte) (sheep.isSheared() ? 1 : 0); + if (sheep.isSheared()) { + this.dataByte = (byte) 1; + } else { + this.dataByte = (byte) 0; + } this.dataByte2 = sheep.getColor().getDyeData(); storeAgeable(sheep); storeLiving(sheep); @@ -164,6 +182,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { case COW: case MUSHROOM_COW: case PIG: + case TURTLE: case POLAR_BEAR: storeAgeable((Ageable) entity); storeLiving((LivingEntity) entity); @@ -174,15 +193,6 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { storeLiving((LivingEntity) entity); return; // END AGEABLE // - case GUARDIAN: - this.dataByte = (byte) (((Guardian) entity).isElder() ? 1 : 0); - storeLiving((LivingEntity) entity); - return; - case SKELETON: - this.dataByte = getOrdinal(Skeleton.SkeletonType.values(), - ((Skeleton) entity).getSkeletonType()); - storeLiving((LivingEntity) entity); - return; case ARMOR_STAND: ArmorStand stand = (ArmorStand) entity; this.inventory = @@ -248,6 +258,10 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { EnderDragon entity1 = (EnderDragon) entity; this.dataByte = (byte) entity1.getPhase().ordinal(); return; + case SKELETON: + case WITHER_SKELETON: + case GUARDIAN: + case ELDER_GUARDIAN: case GHAST: case MAGMA_CUBE: case SQUID: @@ -273,6 +287,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { this.dataByte = (byte) 0; } storeLiving((LivingEntity) entity); + return; // END LIVING // default: PlotSquared.debug("&cCOULD NOT IDENTIFY ENTITY: " + entity.getType()); @@ -308,20 +323,23 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { if (this.lived.leashed) { // TODO leashes // World world = entity.getWorld(); - // Entity leash = world.spawnEntity(new Location(world, Math.floor(x) + lived.leashX, Math.floor(y) + lived.leashY, Math - // .floor(z) + lived.leashZ), EntityType.LEASH_HITCH); + // Entity leash = world.spawnEntity(new Location(world, Math.floor(x) + + // lived.leashX, Math.floor(y) + lived.leashY, Math.floor(z) + lived.leashZ), + // EntityType.LEASH_HITCH); // entity.setLeashHolder(leash); } } void restoreEquipment(LivingEntity entity) { EntityEquipment equipment = entity.getEquipment(); - 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); - equipment.setBoots(this.lived.boots); + if (equipment != null) { + 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); + equipment.setBoots(this.lived.boots); + } } private void restoreInventory(InventoryHolder entity) { @@ -332,7 +350,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { } } - public void storeLiving(LivingEntity lived) { + private void storeLiving(LivingEntity lived) { this.lived = new LivingEntityStats(); this.lived.potions = lived.getActivePotionEffects(); this.lived.loot = lived.getCanPickupItems(); @@ -425,7 +443,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { } if (this.base.passenger != null) { try { - entity.setPassenger(this.base.passenger.spawn(world, xOffset, zOffset)); + entity.addPassenger(this.base.passenger.spawn(world, xOffset, zOffset)); } catch (Exception ignored) { } } @@ -454,7 +472,6 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { ((Slime) entity).setSize(this.dataByte); return entity; case ARROW: - case COMPLEX_PART: case EGG: case ENDER_CRYSTAL: case ENDER_PEARL: @@ -477,15 +494,14 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { case SNOWBALL: case SPLASH_POTION: case THROWN_EXP_BOTTLE: - case WEATHER: - case TIPPED_ARROW: case SPECTRAL_ARROW: case SHULKER_BULLET: - case LINGERING_POTION: case AREA_EFFECT_CLOUD: case DRAGON_FIREBALL: case WITHER_SKULL: case MINECART_FURNACE: + case LLAMA_SPIT: + case TRIDENT: case UNKNOWN: // Do this stuff later return entity; @@ -510,12 +526,19 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { // START AGEABLE // // START TAMEABLE // case HORSE: - Horse horse = (Horse) entity; + case LLAMA: + case SKELETON_HORSE: + case DONKEY: + case MULE: + AbstractHorse horse = (AbstractHorse) entity; horse.setJumpStrength(this.horse.jump); - horse.setCarryingChest(this.horse.chest); - horse.setVariant(this.horse.variant); - horse.setStyle(this.horse.style); - horse.setColor(this.horse.color); + if (horse instanceof ChestedHorse) { + ((ChestedHorse) horse).setCarryingChest(this.horse.chest); + } + //todo broken as of 1.13 + //horse.setVariant(this.horse.variant); + //horse.setStyle(this.horse.style); + //horse.setColor(this.horse.color); restoreTameable(horse); restoreAgeable(horse); restoreLiving(horse); @@ -543,6 +566,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { case VILLAGER: case CHICKEN: case COW: + case TURTLE: case POLAR_BEAR: case MUSHROOM_COW: case PIG: @@ -557,19 +581,6 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { restoreAgeable((Ageable) entity); restoreLiving((LivingEntity) entity); return entity; - case GUARDIAN: - if (this.dataByte != 0) { - ((Guardian) entity).setElder(true); - } - restoreLiving((LivingEntity) entity); - return entity; - case SKELETON: - if (this.dataByte != 0) { - ((Skeleton) entity) - .setSkeletonType(Skeleton.SkeletonType.values()[this.dataByte]); - } - storeLiving((LivingEntity) entity); - return entity; case ARMOR_STAND: // CHECK positions ArmorStand stand = (ArmorStand) entity; @@ -665,6 +676,10 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { case BLAZE: case SNOWMAN: case SHULKER: + case GUARDIAN: + case ELDER_GUARDIAN: + case SKELETON: + case WITHER_SKELETON: restoreLiving((LivingEntity) entity); return entity; case IRON_GOLEM: diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/schematic/StateWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/schematic/StateWrapper.java index 3557f33af..aaf5f4aa5 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/schematic/StateWrapper.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/object/schematic/StateWrapper.java @@ -2,7 +2,7 @@ package com.github.intellectualsites.plotsquared.bukkit.object.schematic; 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.Captions; import com.sk89q.jnbt.*; import org.bukkit.Material; import org.bukkit.World; @@ -132,7 +132,7 @@ public class StateWrapper { .replace("\"underlined\":true,", "&n").replace("\"italic\":true,", "&o") .replace("[{\"text\":\"", "&0").replace("{\"text\":\"", "&0").replace("\"},", "") .replace("\"}]", "").replace("\"}", ""); - for (Entry entry : C.replacements.entrySet()) { + for (Entry entry : Captions.replacements.entrySet()) { str = str.replace(entry.getKey(), entry.getValue()); } return str; diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/DefaultTitleManager.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/DefaultTitleManager.java deleted file mode 100644 index a5447f9bf..000000000 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/DefaultTitleManager.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.github.intellectualsites.plotsquared.bukkit.titles; - -import com.github.intellectualsites.plotsquared.bukkit.chat.Reflection; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; - -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 fadeOutTime Fade out time - */ - DefaultTitleManager(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.packetActions = Reflection.getNMSClass("EnumTitleAction"); - this.chatBaseComponent = Reflection.getNMSClass("IChatBaseComponent"); - this.nmsChatSerializer = Reflection.getNMSClass("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); - } - } - } - - @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); - sendPacket.invoke(connection, packet); - } - - /** - * Reset the title settings. - * - * @param player Player - * @throws SecurityException - * @throws ReflectiveOperationException - * @throws 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); - sendPacket.invoke(connection, packet); - } - - Field getField(Class clazz, String name) { - try { - Field field = clazz.getDeclaredField(name); - field.setAccessible(true); - return field; - } catch (NoSuchFieldException | SecurityException e) { - e.printStackTrace(); - return null; - } - } - - 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()))) { - m.setAccessible(true); - return m; - } - } - return null; - } - -} 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 deleted file mode 100644 index c0d176019..000000000 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/DefaultTitle_111.java +++ /dev/null @@ -1,20 +0,0 @@ -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 deleted file mode 100644 index ae2b50a60..000000000 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/HackTitle.java +++ /dev/null @@ -1,22 +0,0 @@ -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/github/intellectualsites/plotsquared/bukkit/titles/HackTitleManager.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/HackTitleManager.java deleted file mode 100644 index 2ec197927..000000000 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/HackTitleManager.java +++ /dev/null @@ -1,177 +0,0 @@ -package com.github.intellectualsites.plotsquared.bukkit.titles; - -import com.github.intellectualsites.plotsquared.bukkit.chat.Reflection; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; - -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 fadeOutTime Fade out time - */ - HackTitleManager(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 = 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 { - if ((getProtocolVersion(player) >= 47) && isSpigot() && (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, 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 - 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, 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); - sendPacket.invoke(connection, packet); - } - } - } - - @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]); - sendPacket.invoke(connection, packet); - } - } - - @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]); - sendPacket.invoke(connection, packet); - } - } - - /** - * Get the protocol version of the player. - * - * @param player Player - * @return Protocol version - * @throws IllegalArgumentException - * @throws ReflectiveOperationException - * @throws 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); - return (Integer) getMethod("getVersion", networkManager.getClass()).invoke(networkManager); - } - - /** - * Check if running spigot. - * - * @return Spigot - */ - private boolean isSpigot() { - return Bukkit.getVersion().contains("Spigot"); - } - - /** - * Get class by url. - * - * @param namespace Namespace url - * @return Class - */ - private Class getClass(String namespace) { - try { - return Class.forName(namespace); - } catch (ClassNotFoundException ignored) { - } - return null; - } - - 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 { - Field f = getField(name, obj.getClass()); - f.setAccessible(true); - return f.get(obj); - } - - private Field getField(Class clazz, String name) { - try { - Field field = clazz.getDeclaredField(name); - field.setAccessible(true); - return field; - } catch (SecurityException | NoSuchFieldException e) { - e.printStackTrace(); - return null; - } - } - - 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()))) { - m.setAccessible(true); - return m; - } - } - return null; - } - -} diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager.java deleted file mode 100644 index f4c249f97..000000000 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager.java +++ /dev/null @@ -1,256 +0,0 @@ -package com.github.intellectualsites.plotsquared.bukkit.titles; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.HashMap; -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; - Class chatBaseComponent; - ChatColor titleColor = ChatColor.WHITE; - ChatColor subtitleColor = ChatColor.WHITE; - /* Title timings */ int fadeInTime = -1; - int stayTime = -1; - int fadeOutTime = -1; - boolean ticks = false; - /* Title text and color */ - private String title = ""; - /* Subtitle text and color */ - private String subtitle = ""; - - /** - * 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 - */ - TitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) { - this.title = title; - this.subtitle = subtitle; - this.fadeInTime = fadeInTime; - this.stayTime = stayTime; - this.fadeOutTime = fadeOutTime; - loadClasses(); - } - - abstract void loadClasses(); - - /** - * Gets title text. - * - * @return Title text - */ - public final String getTitle() { - return this.title; - } - - /** - * Sets the text for the title. - * - * @param title Title - */ - public final void setTitle(String title) { - this.title = title; - } - - /** - * Gets the subtitle text. - * - * @return Subtitle text - */ - public final String getSubtitle() { - return this.subtitle; - } - - /** - * Sets subtitle text. - * - * @param subtitle Subtitle text - */ - public final void setSubtitle(String subtitle) { - this.subtitle = subtitle; - } - - /** - * Sets the title color. - * - * @param color Chat color - */ - public final void setTitleColor(ChatColor color) { - this.titleColor = color; - } - - /** - * Sets the subtitle color. - * - * @param color Chat color - */ - public final void setSubtitleColor(ChatColor color) { - this.subtitleColor = color; - } - - /** - * Sets title fade in time. - * - * @param time Time - */ - public final void setFadeInTime(int time) { - this.fadeInTime = time; - } - - /** - * Sets title fade out time. - * - * @param time Time - */ - public final void setFadeOutTime(int time) { - this.fadeOutTime = time; - } - - /** - * Sets title stay time. - * - * @param time Time - */ - public final void setStayTime(int time) { - this.stayTime = time; - } - - /** - * Sets timings to ticks. - */ - public final void setTimingsToTicks() { - this.ticks = true; - } - - /** - * Sets timings to seconds. - */ - public final void setTimingsToSeconds() { - this.ticks = false; - } - - /** - * Sends the title to a player. - * - * @param player Player - * @throws IllegalArgumentException - * @throws ReflectiveOperationException - * @throws SecurityException - */ - public abstract void send(Player player) - throws IllegalArgumentException, ReflectiveOperationException, SecurityException; - - /** - * Broadcasts the title to all players. - * - * @throws Exception - */ - public final void broadcast() throws Exception { - for (Player player : Bukkit.getOnlinePlayers()) { - send(player); - } - } - - /** - * Clears the title. - * - * @param player Player - * @throws IllegalArgumentException - * @throws ReflectiveOperationException - * @throws SecurityException - */ - public abstract void clearTitle(Player player) - throws IllegalArgumentException, ReflectiveOperationException, SecurityException; - - /** - * Resets the title settings. - * - * @param player Player - * @throws IllegalArgumentException - * @throws ReflectiveOperationException - * @throws SecurityException - */ - public abstract void resetTitle(Player player) - throws IllegalArgumentException, ReflectiveOperationException, SecurityException; - - private Class getPrimitiveType(Class clazz) { - if (CORRESPONDING_TYPES.containsKey(clazz)) { - return CORRESPONDING_TYPES.get(clazz); - } else { - return clazz; - } - } - - private Class[] toPrimitiveTypeArray(Class[] classes) { - int a; - if (classes != null) { - a = classes.length; - } else { - a = 0; - } - Class[] types = new Class[a]; - for (int i = 0; i < a; i++) { - types[i] = getPrimitiveType(classes[i]); - } - return types; - } - - final Object getHandle(Object obj) { - try { - return getMethod("getHandle", obj.getClass()).invoke(obj); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - e.printStackTrace(); - return null; - } - } - - final Method getMethod(String name, Class clazz, Class... paramTypes) { - Class[] t = toPrimitiveTypeArray(paramTypes); - for (Method m : clazz.getMethods()) { - Class[] types = toPrimitiveTypeArray(m.getParameterTypes()); - if (m.getName().equals(name) && equalsTypeArray(types, t)) { - return m; - } - } - return null; - } - - private 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; - } - - boolean classListEqual(Class[] l1, Class[] l2) { - if (l1.length != l2.length) { - return false; - } - boolean equal = true; - for (int i = 0; i < l1.length; i++) { - if (l1[i] != l2[i]) { - equal = false; - break; - } - } - return equal; - } -} diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager_1_11.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager_1_11.java deleted file mode 100644 index 92155ba45..000000000 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/titles/TitleManager_1_11.java +++ /dev/null @@ -1,497 +0,0 @@ -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; - -/** - * Minecraft 1.8 Title - * For 1.11 - * - * @author Maxim Van de Wynckel - * @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 */ - private static Class packetActions; - /* Chat serializer */ - private static Class nmsChatSerializer; - private static Class chatBaseComponent; - /* NMS player and connection */ - private static Class nmsPlayer; - private static Class nmsPlayerConnection; - private static Field playerConnection; - private static Method sendPacket; - private static Class obcPlayer; - private static Method methodPlayerGetHandle; - /* Title text and color */ - private String title = ""; - private ChatColor titleColor = ChatColor.WHITE; - /* Subtitle text and color */ - private String subtitle = ""; - private ChatColor subtitleColor = ChatColor.WHITE; - /* Title timings */ - private int fadeInTime = -1; - private int stayTime = -1; - private int fadeOutTime = -1; - private boolean ticks = false; - - public TitleManager_1_11() { - loadClasses(); - } - - /** - * Create a new 1.8 title - * - * @param title Title - */ - public TitleManager_1_11(String title) { - this.title = title; - loadClasses(); - } - - /** - * Create a new 1.8 title - * - * @param title Title text - * @param subtitle Subtitle text - */ - public TitleManager_1_11(String title, String subtitle) { - this.title = title; - this.subtitle = subtitle; - loadClasses(); - } - - /** - * Copy 1.8 title - * - * @param title Title - */ - public TitleManager_1_11(TitleManager_1_11 title) { - // Copy title - this.title = title.getTitle(); - this.subtitle = title.getSubtitle(); - this.titleColor = title.getTitleColor(); - this.subtitleColor = title.getSubtitleColor(); - this.fadeInTime = title.getFadeInTime(); - this.fadeOutTime = title.getFadeOutTime(); - this.stayTime = title.getStayTime(); - this.ticks = title.isTicks(); - loadClasses(); - } - - /** - * 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 - */ - public TitleManager_1_11(String title, String subtitle, int fadeInTime, int stayTime, - int fadeOutTime) { - this.title = title; - this.subtitle = subtitle; - this.fadeInTime = fadeInTime; - this.stayTime = stayTime; - this.fadeOutTime = fadeOutTime; - 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 - */ - private void loadClasses() { - if (packetTitle == null) { - packetTitle = getNMSClass("PacketPlayOutTitle"); - packetActions = getNMSClass("PacketPlayOutTitle$EnumTitleAction"); - chatBaseComponent = getNMSClass("IChatBaseComponent"); - nmsChatSerializer = getNMSClass("ChatComponentText"); - nmsPlayer = getNMSClass("EntityPlayer"); - nmsPlayerConnection = getNMSClass("PlayerConnection"); - playerConnection = getField(nmsPlayer, "playerConnection"); - sendPacket = getMethod(nmsPlayerConnection, "sendPacket"); - obcPlayer = getOBCClass("entity.CraftPlayer"); - methodPlayerGetHandle = getMethod("getHandle", obcPlayer); - } - } - - /** - * Get title text - * - * @return Title text - */ - public String getTitle() { - return this.title; - } - - /** - * Set title text - * - * @param title Title - */ - public void setTitle(String title) { - this.title = title; - } - - /** - * Get subtitle text - * - * @return Subtitle text - */ - public String getSubtitle() { - return this.subtitle; - } - - /** - * Set subtitle text - * - * @param subtitle Subtitle text - */ - public void setSubtitle(String subtitle) { - this.subtitle = subtitle; - } - - /** - * Set timings to ticks - */ - public void setTimingsToTicks() { - ticks = true; - } - - /** - * Set timings to seconds - */ - public void setTimingsToSeconds() { - ticks = false; - } - - /** - * Send the title to a player - * - * @param player Player - */ - public void send(Player player) { - if (packetTitle != null) { - // First reset previous settings - resetTitle(player); - try { - // Send timings first - 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)); - // Send if set - if (fadeInTime != -1 && fadeOutTime != -1 && stayTime != -1) - sendPacket.invoke(connection, packet); - - 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); - 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); - sendPacket.invoke(connection, packet); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public void updateTimes(Player player) { - if (TitleManager_1_11.packetTitle != null) { - try { - Object handle = getHandle(player); - 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)) { - sendPacket.invoke(connection, packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public void updateTitle(Player player) { - if (TitleManager_1_11.packetTitle != null) { - try { - Object handle = getHandle(player); - 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); - sendPacket.invoke(connection, packet); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public void updateSubtitle(Player player) { - if (TitleManager_1_11.packetTitle != null) { - try { - 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); - sendPacket.invoke(connection, packet); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - /** - * Broadcast the title to all players - */ - public void broadcast() { - for (Player p : Bukkit.getOnlinePlayers()) { - send(p); - } - } - - /** - * Clear the title - * - * @param player Player - */ - public void clearTitle(Player player) { - try { - // Send timings first - Object handle = getHandle(player); - Object connection = playerConnection.get(handle); - Object[] actions = packetActions.getEnumConstants(); - Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent) - .newInstance(actions[4], null); - sendPacket.invoke(connection, packet); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Reset the title settings - * - * @param player Player - */ - public void resetTitle(Player player) { - try { - // Send timings first - Object handle = getHandle(player); - Object connection = playerConnection.get(handle); - Object[] actions = packetActions.getEnumConstants(); - Object packet = packetTitle.getConstructor(packetActions, chatBaseComponent) - .newInstance(actions[5], null); - sendPacket.invoke(connection, packet); - } catch (Exception e) { - e.printStackTrace(); - } - } - - private Class getPrimitiveType(Class clazz) { - return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz; - } - - private Class[] toPrimitiveTypeArray(Class[] classes) { - int a = classes != null ? classes.length : 0; - Class[] types = new Class[a]; - for (int i = 0; i < a; i++) - types[i] = getPrimitiveType(classes[i]); - return types; - } - - private Object getHandle(Player player) { - try { - return methodPlayerGetHandle.invoke(player); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - private Method getMethod(String name, Class clazz, Class... paramTypes) { - Class[] t = toPrimitiveTypeArray(paramTypes); - for (Method m : clazz.getMethods()) { - Class[] types = toPrimitiveTypeArray(m.getParameterTypes()); - if (m.getName().equals(name) && equalsTypeArray(types, t)) - return m; - } - return null; - } - - private String getVersion() { - String name = Bukkit.getServer().getClass().getPackage().getName(); - String version = name.substring(name.lastIndexOf('.') + 1) + "."; - return version; - } - - private Class getNMSClass(String className) { - String fullName = "net.minecraft.server." + getVersion() + className; - Class clazz = null; - try { - clazz = Class.forName(fullName); - } catch (Exception e) { - e.printStackTrace(); - } - return clazz; - } - - private Class getOBCClass(String className) { - String fullName = "org.bukkit.craftbukkit." + getVersion() + className; - Class clazz = null; - try { - clazz = Class.forName(fullName); - } catch (Exception e) { - e.printStackTrace(); - } - return clazz; - } - - private Field getField(Class clazz, String name) { - try { - Field field = clazz.getDeclaredField(name); - field.setAccessible(true); - return field; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - 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()))) { - m.setAccessible(true); - return m; - } - return null; - } - - private boolean ClassListEqual(Class[] l1, Class[] l2) { - boolean equal = true; - if (l1.length != l2.length) - return false; - for (int i = 0; i < l1.length; i++) - if (l1[i] != l2[i]) { - equal = false; - break; - } - return equal; - } - - public ChatColor getTitleColor() { - 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; - } -} 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 index a133d9630..ef3af32d9 100644 --- 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 @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.object.ConsolePlayer; import com.github.intellectualsites.plotsquared.plot.object.PlotMessage; @@ -10,8 +10,9 @@ 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.Arrays; import java.util.List; +import java.util.stream.Collectors; public class BukkitChatManager extends ChatManager { @@ -20,14 +21,12 @@ public class BukkitChatManager extends ChatManager { } @Override public void color(PlotMessage message, String color) { - message.$(this).color(ChatColor.getByChar(C.color(color).substring(1))); + message.$(this).color(ChatColor.getByChar(Captions.color(color).substring(1))); } @Override public void tooltip(PlotMessage message, PlotMessage... tooltips) { - List lines = new ArrayList<>(); - for (PlotMessage tooltip : tooltips) { - lines.add(tooltip.$(this)); - } + List lines = + Arrays.stream(tooltips).map(tooltip -> tooltip.$(this)).collect(Collectors.toList()); message.$(this).formattedTooltip(lines); } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitChunkManager.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitChunkManager.java index 1a388e9b5..744f4b6e9 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitChunkManager.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitChunkManager.java @@ -106,289 +106,11 @@ public class BukkitChunkManager extends ChunkManager { Set chunks = super.getChunkChunks(world); for (Chunk chunk : Bukkit.getWorld(world).getLoadedChunks()) { ChunkLoc loc = new ChunkLoc(chunk.getX() >> 5, chunk.getZ() >> 5); - if (!chunks.contains(loc)) { - chunks.add(loc); - } + chunks.add(loc); } return chunks; } - @Override - 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(); - - final RegionWrapper region = - new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); - final World oldWorld = Bukkit.getWorld(pos1.getWorld()); - final BukkitWorld oldBukkitWorld = new BukkitWorld(oldWorld); - final World newWorld = Bukkit.getWorld(newPos.getWorld()); - final String newWorldName = newWorld.getName(); - 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) { - int bx = value[2]; - int bz = value[3]; - int tx = value[4]; - int tz = value[5]; - ChunkLoc loc = new ChunkLoc(value[0], value[1]); - int cxx = loc.x << 4; - int czz = loc.z << 4; - Chunk chunk = oldWorld.getChunkAt(loc.x, loc.z); - map.saveEntitiesIn(chunk, region); - for (int x = bx & 15; x <= (tx & 15); x++) { - for (int z = bz & 15; z <= (tz & 15); z++) { - map.saveBlocks(oldBukkitWorld, 256, cxx + x, czz + z, relX, relZ); - } - } - } - }, () -> { - for (Entry entry : map.allBlocks.entrySet()) { - PlotLoc loc = entry.getKey(); - BaseBlock[] blocks = entry.getValue(); - for (int y = 0; y < blocks.length; y++) { - if (blocks[y] != null) { - BaseBlock block = blocks[y]; - queue.setBlock(loc.x, y, loc.z, block); - } - } - } - queue.enqueue(); - GlobalBlockQueue.IMP.addTask(() -> { - //map.restoreBlocks(newWorld, 0, 0); - map.restoreEntities(newWorld, relX, relZ); - TaskManager.runTask(whenDone); - }); - }, 5); - return true; - } - - @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(); - 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 List 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); - final BukkitWorld bukkitWorldObj = new BukkitWorld(worldObj); - TaskManager.runTask(new Runnable() { - @Override public void run() { - long start = System.currentTimeMillis(); - while (!chunks.isEmpty() && System.currentTimeMillis() - start < 5) { - final ChunkLoc chunk = chunks.remove(0); - int x = chunk.x; - int z = chunk.z; - int xxb = x << 4; - int zzb = z << 4; - int xxt = xxb + 15; - int zzt = zzb + 15; - Chunk chunkObj = worldObj.getChunkAt(x, z); - if (!chunkObj.load(false)) { - continue; - } - final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false); - RegionWrapper currentPlotClear = - new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); - if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z) { - AugmentedUtils - .bypass(ignoreAugment, () -> queue.regenChunkSafe(chunk.x, chunk.z)); - continue; - } - boolean checkX1 = false; - - int xxb2; - - if (x == bcx) { - xxb2 = p1x - 1; - checkX1 = true; - } else { - xxb2 = xxb; - } - boolean checkX2 = false; - int xxt2; - if (x == tcx) { - xxt2 = p2x + 1; - checkX2 = true; - } else { - xxt2 = xxt; - } - boolean checkZ1 = false; - int zzb2; - if (z == bcz) { - zzb2 = p1z - 1; - checkZ1 = true; - } else { - zzb2 = zzb; - } - boolean checkZ2 = false; - int zzt2; - if (z == tcz) { - zzt2 = p2z + 1; - checkZ2 = true; - } else { - zzt2 = zzt; - } - final ContentMap map = new ContentMap(); - if (checkX1) { - map.saveRegion(bukkitWorldObj, xxb, xxb2, zzb2, zzt2); // - } - if (checkX2) { - map.saveRegion(bukkitWorldObj, xxt2, xxt, zzb2, zzt2); // - } - if (checkZ1) { - map.saveRegion(bukkitWorldObj, xxb2, xxt2, zzb, zzb2); // - } - if (checkZ2) { - map.saveRegion(bukkitWorldObj, xxb2, xxt2, zzt2, zzt); // - } - if (checkX1 && checkZ1) { - map.saveRegion(bukkitWorldObj, xxb, xxb2, zzb, zzb2); // - } - if (checkX2 && checkZ1) { - map.saveRegion(bukkitWorldObj, xxt2, xxt, zzb, zzb2); // ? - } - if (checkX1 && checkZ2) { - map.saveRegion(bukkitWorldObj, xxb, xxb2, zzt2, zzt); // ? - } - if (checkX2 && checkZ2) { - map.saveRegion(bukkitWorldObj, xxt2, xxt, zzt2, zzt); // - } - map.saveEntitiesOut(chunkObj, currentPlotClear); - AugmentedUtils.bypass(ignoreAugment, - () -> setChunkInPlotArea(null, new RunnableVal() { - @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 x1 = 0; x1 < 16; x1++) { - for (int z1 = 0; z1 < 16; z1++) { - PlotLoc loc = new PlotLoc(bx + x1, bz + z1); - BaseBlock[] ids = map.allBlocks.get(loc); - if (ids != null) { - for (int y = 0; y < Math.min(128, ids.length); y++) { - BaseBlock id = ids[y]; - if (id != null) { - value.setBlock(x1, y, z1, id); - } else { - value.setBlock(x1, y, z1, PlotBlock.get("air")); - } - } - for (int y = Math.min(128, ids.length); - y < ids.length; y++) { - BaseBlock id = ids[y]; - if (id != null) { - value.setBlock(x1, y, z1, id); - } - } - } - } - } - } - }, world, chunk)); - //map.restoreBlocks(worldObj, 0, 0); - map.restoreEntities(worldObj, 0, 0); - } - if (!chunks.isEmpty()) { - TaskManager.runTaskLater(this, 1); - } else { - TaskManager.runTaskLater(whenDone, 1); - } - } - }); - return true; - } - - @Override - 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(); - int bz = pos1.getZ(); - int tx = pos2.getX(); - int tz = pos2.getZ(); - 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 (entity.hasMetadata("ps-tmp-teleport")) { - continue; - } - entity.remove(); - } - } - } - } - - @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 (!PlotSquared.get().isMainThread(Thread.currentThread())) { - TaskManager - .runTask(() -> BukkitUtil.getWorld(world).unloadChunk(loc.x, loc.z, save, safe)); - } else { - BukkitUtil.getWorld(world).unloadChunk(loc.x, loc.z, save, safe); - } - } - - @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()); - - int relX = bot2.getX() - bot1.getX(); - int relZ = bot2.getZ() - bot1.getZ(); - - final ArrayDeque maps = new ArrayDeque<>(); - - for (int x = bot1.getX() >> 4; x <= top1.getX() >> 4; x++) { - for (int z = bot1.getZ() >> 4; z <= top1.getZ() >> 4; z++) { - Chunk chunk1 = world1.getChunkAt(x, z); - Chunk chunk2 = world2.getChunkAt(x + (relX >> 4), z + (relZ >> 4)); - maps.add(swapChunk(world1, world2, chunk1, chunk2, region1, region2)); - } - } - GlobalBlockQueue.IMP.addTask(() -> { - for (ContentMap map : maps) { - map.restoreEntities(world1, 0, 0); - TaskManager.runTaskLater(whenDone, 1); - } - }); - } - @Override public int[] countEntities(Plot plot) { int[] existing = (int[]) plot.getMeta("EntityCount"); if (existing != null && (System.currentTimeMillis() - (long) plot.getMeta("EntityCountTime") @@ -398,8 +120,8 @@ public class BukkitChunkManager extends ChunkManager { PlotArea area = plot.getArea(); World world = BukkitUtil.getWorld(area.worldname); - com.github.intellectualsites.plotsquared.plot.object.Location bot = plot.getBottomAbs(); - com.github.intellectualsites.plotsquared.plot.object.Location top = plot.getTopAbs(); + Location bot = plot.getBottomAbs(); + Location top = plot.getTopAbs(); int bx = bot.getX() >> 4; int bz = bot.getZ() >> 4; @@ -464,6 +186,271 @@ public class BukkitChunkManager extends ChunkManager { return count; } + @Override public boolean copyRegion(Location pos1, Location pos2, Location newPos, + final Runnable whenDone) { + final int relX = newPos.getX() - pos1.getX(); + final int relZ = newPos.getZ() - pos1.getZ(); + + final RegionWrapper region = + new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); + final World oldWorld = Bukkit.getWorld(pos1.getWorld()); + final BukkitWorld oldBukkitWorld = new BukkitWorld(oldWorld); + final World newWorld = Bukkit.getWorld(newPos.getWorld()); + final String newWorldName = newWorld.getName(); + 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) { + int bx = value[2]; + int bz = value[3]; + int tx = value[4]; + int tz = value[5]; + ChunkLoc loc = new ChunkLoc(value[0], value[1]); + int cxx = loc.x << 4; + int czz = loc.z << 4; + Chunk chunk = oldWorld.getChunkAt(loc.x, loc.z); + map.saveEntitiesIn(chunk, region); + for (int x = bx & 15; x <= (tx & 15); x++) { + for (int z = bz & 15; z <= (tz & 15); z++) { + map.saveBlocks(oldBukkitWorld, 256, cxx + x, czz + z, relX, relZ); + } + } + } + }, () -> { + for (Entry entry : map.allBlocks.entrySet()) { + PlotLoc loc = entry.getKey(); + BaseBlock[] blocks = entry.getValue(); + for (int y = 0; y < blocks.length; y++) { + if (blocks[y] != null) { + BaseBlock block = blocks[y]; + queue.setBlock(loc.getX(), y, loc.getZ(), block); + } + } + } + queue.enqueue(); + GlobalBlockQueue.IMP.addTask(() -> { + //map.restoreBlocks(newWorld, 0, 0); + map.restoreEntities(newWorld, relX, relZ); + TaskManager.runTask(whenDone); + }); + }, 5); + return true; + } + + @Override public boolean regenerateRegion(final Location pos1, final Location pos2, + final boolean ignoreAugment, final Runnable whenDone) { + final String world = pos1.getWorld(); + + final int p1x = pos1.getX(); + 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 List 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); + final BukkitWorld bukkitWorldObj = new BukkitWorld(worldObj); + TaskManager.runTask(new Runnable() { + @Override public void run() { + long start = System.currentTimeMillis(); + while (!chunks.isEmpty() && System.currentTimeMillis() - start < 5) { + final ChunkLoc chunk = chunks.remove(0); + int x = chunk.x; + int z = chunk.z; + int xxb = x << 4; + int zzb = z << 4; + int xxt = xxb + 15; + int zzt = zzb + 15; + Chunk chunkObj = worldObj.getChunkAt(x, z); + if (!chunkObj.load(false)) { + continue; + } + final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false); + if (xxb >= p1x && xxt <= p2x && zzb >= p1z && zzt <= p2z + && PlotSquared.imp().getServerVersion()[1] == 13) { + AugmentedUtils + .bypass(ignoreAugment, () -> queue.regenChunkSafe(chunk.x, chunk.z)); + continue; + } + boolean checkX1 = false; + + int xxb2; + + if (x == bcx) { + xxb2 = p1x - 1; + checkX1 = true; + } else { + xxb2 = xxb; + } + boolean checkX2 = false; + int xxt2; + if (x == tcx) { + xxt2 = p2x + 1; + checkX2 = true; + } else { + xxt2 = xxt; + } + boolean checkZ1 = false; + int zzb2; + if (z == bcz) { + zzb2 = p1z - 1; + checkZ1 = true; + } else { + zzb2 = zzb; + } + boolean checkZ2 = false; + int zzt2; + if (z == tcz) { + zzt2 = p2z + 1; + checkZ2 = true; + } else { + zzt2 = zzt; + } + final ContentMap map = new ContentMap(); + if (checkX1) { + map.saveRegion(bukkitWorldObj, xxb, xxb2, zzb2, zzt2); // + } + if (checkX2) { + map.saveRegion(bukkitWorldObj, xxt2, xxt, zzb2, zzt2); // + } + if (checkZ1) { + map.saveRegion(bukkitWorldObj, xxb2, xxt2, zzb, zzb2); // + } + if (checkZ2) { + map.saveRegion(bukkitWorldObj, xxb2, xxt2, zzt2, zzt); // + } + if (checkX1 && checkZ1) { + map.saveRegion(bukkitWorldObj, xxb, xxb2, zzb, zzb2); // + } + if (checkX2 && checkZ1) { + map.saveRegion(bukkitWorldObj, xxt2, xxt, zzb, zzb2); // ? + } + if (checkX1 && checkZ2) { + map.saveRegion(bukkitWorldObj, xxb, xxb2, zzt2, zzt); // ? + } + if (checkX2 && checkZ2) { + map.saveRegion(bukkitWorldObj, xxt2, xxt, zzt2, zzt); // + } + RegionWrapper currentPlotClear = + new RegionWrapper(pos1.getX(), pos2.getX(), pos1.getZ(), pos2.getZ()); + map.saveEntitiesOut(chunkObj, currentPlotClear); + AugmentedUtils.bypass(ignoreAugment, + () -> setChunkInPlotArea(null, new RunnableVal() { + @Override public void run(ScopedLocalBlockQueue value) { + Location min = value.getMin(); + int bx = min.getX(); + int bz = min.getZ(); + for (int x1 = 0; x1 < 16; x1++) { + for (int z1 = 0; z1 < 16; z1++) { + PlotLoc loc = new PlotLoc(bx + x1, bz + z1); + BaseBlock[] ids = map.allBlocks.get(loc); + if (ids != null) { + for (int y = 0; y < Math.min(128, ids.length); y++) { + BaseBlock id = ids[y]; + if (id != null) { + value.setBlock(x1, y, z1, id); + } else { + value.setBlock(x1, y, z1, PlotBlock.get("air")); + } + } + for (int y = Math.min(128, ids.length); + y < ids.length; y++) { + BaseBlock id = ids[y]; + if (id != null) { + value.setBlock(x1, y, z1, id); + } + } + } + } + } + } + }, world, chunk)); + //map.restoreBlocks(worldObj, 0, 0); + map.restoreEntities(worldObj, 0, 0); + } + if (!chunks.isEmpty()) { + TaskManager.runTaskLater(this, 1); + } else { + TaskManager.runTaskLater(whenDone, 1); + } + } + }); + return true; + } + + @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 (!PlotSquared.get().isMainThread(Thread.currentThread())) { + TaskManager.runTask(() -> BukkitUtil.getWorld(world).unloadChunk(loc.x, loc.z, save)); + } else { + BukkitUtil.getWorld(world).unloadChunk(loc.x, loc.z, save); + } + } + + @Override public void clearAllEntities(Location pos1, Location pos2) { + String world = pos1.getWorld(); + List entities = BukkitUtil.getEntities(world); + int bx = pos1.getX(); + int bz = pos1.getZ(); + int tx = pos2.getX(); + int tz = pos2.getZ(); + 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 (entity.hasMetadata("ps-tmp-teleport")) { + continue; + } + entity.remove(); + } + } + } + } + + @Override public void swap(Location bot1, Location top1, Location bot2, Location top2, + final Runnable whenDone) { + RegionWrapper region1 = + new RegionWrapper(bot1.getX(), top1.getX(), bot1.getZ(), top1.getZ()); + RegionWrapper region2 = + new RegionWrapper(bot2.getX(), top2.getX(), bot2.getZ(), top2.getZ()); + final World world1 = Bukkit.getWorld(bot1.getWorld()); + World world2 = Bukkit.getWorld(bot2.getWorld()); + + int relX = bot2.getX() - bot1.getX(); + int relZ = bot2.getZ() - bot1.getZ(); + + final ArrayDeque maps = new ArrayDeque<>(); + + for (int x = bot1.getX() >> 4; x <= top1.getX() >> 4; x++) { + for (int z = bot1.getZ() >> 4; z <= top1.getZ() >> 4; z++) { + Chunk chunk1 = world1.getChunkAt(x, z); + Chunk chunk2 = world2.getChunkAt(x + (relX >> 4), z + (relZ >> 4)); + maps.add(swapChunk(world1, world2, chunk1, chunk2, region1, region2)); + } + } + GlobalBlockQueue.IMP.addTask(() -> { + for (ContentMap map : maps) { + map.restoreEntities(world1, 0, 0); + TaskManager.runTaskLater(whenDone, 1); + } + }); + } + private void count(int[] count, Entity entity) { switch (entity.getType()) { case PLAYER: @@ -478,7 +465,7 @@ public class BukkitChunkManager extends ChunkManager { case SNOWBALL: case ENDER_PEARL: case ARROW: - case TIPPED_ARROW: + case TRIDENT: case SHULKER_BULLET: case SPECTRAL_ARROW: case DRAGON_FIREBALL: @@ -488,18 +475,15 @@ public class BukkitChunkManager extends ChunkManager { case FALLING_BLOCK: // Block entities case ENDER_CRYSTAL: - case COMPLEX_PART: case FISHING_HOOK: case ENDER_SIGNAL: case EXPERIENCE_ORB: case LEASH_HITCH: case FIREWORK: - case WEATHER: case LIGHTNING: case WITHER_SKULL: case UNKNOWN: case AREA_EFFECT_CLOUD: - case LINGERING_POTION: case EVOKER_FANGS: // non moving / unremovable break; @@ -539,6 +523,16 @@ public class BukkitChunkManager extends ChunkManager { case SKELETON_HORSE: case ZOMBIE_HORSE: case MULE: + case DOLPHIN: + case TURTLE: + case COD: + case PARROT: + case SALMON: + case PUFFERFISH: + case TROPICAL_FISH: + case CAT: + case FOX: + case PANDA: // animal count[3]++; count[1]++; @@ -589,6 +583,7 @@ public class BukkitChunkManager extends ChunkManager { count[0]++; } + public static class ContentMap { final Set entities; @@ -617,14 +612,9 @@ public class BukkitChunkManager extends ChunkManager { } } - public void saveEntitiesIn(Chunk chunk, RegionWrapper region) { - saveEntitiesIn(chunk, region, 0, 0, false); - } - - public void saveEntitiesOut(Chunk chunk, RegionWrapper region) { + void saveEntitiesOut(Chunk chunk, RegionWrapper region) { for (Entity entity : chunk.getEntities()) { - com.github.intellectualsites.plotsquared.plot.object.Location loc = - BukkitUtil.getLocation(entity); + Location loc = BukkitUtil.getLocation(entity); int x = loc.getX(); int z = loc.getZ(); if (isIn(region, x, z)) { @@ -639,11 +629,14 @@ public class BukkitChunkManager extends ChunkManager { } } - public void saveEntitiesIn(Chunk chunk, RegionWrapper region, int offsetX, int offsetZ, + void saveEntitiesIn(Chunk chunk, RegionWrapper region) { + saveEntitiesIn(chunk, region, 0, 0, false); + } + + void saveEntitiesIn(Chunk chunk, RegionWrapper region, int offsetX, int offsetZ, boolean delete) { for (Entity entity : chunk.getEntities()) { - com.github.intellectualsites.plotsquared.plot.object.Location loc = - BukkitUtil.getLocation(entity); + Location loc = BukkitUtil.getLocation(entity); int x = loc.getX(); int z = loc.getZ(); if (!isIn(region, x, z)) { @@ -665,7 +658,7 @@ public class BukkitChunkManager extends ChunkManager { } } - public void restoreEntities(World world, int xOffset, int zOffset) { + void restoreEntities(World world, int xOffset, int zOffset) { for (EntityWrapper entity : this.entities) { try { entity.spawn(world, xOffset, zOffset); @@ -677,8 +670,8 @@ public class BukkitChunkManager extends ChunkManager { this.entities.clear(); } - public void saveBlocks(BukkitWorld world, int maxY, int x, int z, int offsetX, - int offsetZ) { + //todo optimize maxY + void saveBlocks(BukkitWorld world, int maxY, int x, int z, int offsetX, int offsetZ) { maxY = Math.min(255, maxY); BaseBlock[] ids; ids = new BaseBlock[maxY + 1]; diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitEventUtil.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitEventUtil.java index 808dabb7a..744d9084f 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitEventUtil.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitEventUtil.java @@ -1,9 +1,30 @@ package com.github.intellectualsites.plotsquared.bukkit.util; -import com.github.intellectualsites.plotsquared.bukkit.events.*; +import com.github.intellectualsites.plotsquared.bukkit.events.PlayerClaimPlotEvent; +import com.github.intellectualsites.plotsquared.bukkit.events.PlayerEnterPlotEvent; +import com.github.intellectualsites.plotsquared.bukkit.events.PlayerLeavePlotEvent; +import com.github.intellectualsites.plotsquared.bukkit.events.PlayerPlotDeniedEvent; +import com.github.intellectualsites.plotsquared.bukkit.events.PlayerPlotHelperEvent; +import com.github.intellectualsites.plotsquared.bukkit.events.PlayerPlotTrustedEvent; +import com.github.intellectualsites.plotsquared.bukkit.events.PlayerTeleportToPlotEvent; +import com.github.intellectualsites.plotsquared.bukkit.events.PlotAutoMergeEvent; +import com.github.intellectualsites.plotsquared.bukkit.events.PlotChangeOwnerEvent; +import com.github.intellectualsites.plotsquared.bukkit.events.PlotClearEvent; +import com.github.intellectualsites.plotsquared.bukkit.events.PlotComponentSetEvent; +import com.github.intellectualsites.plotsquared.bukkit.events.PlotDeleteEvent; +import com.github.intellectualsites.plotsquared.bukkit.events.PlotFlagAddEvent; +import com.github.intellectualsites.plotsquared.bukkit.events.PlotFlagRemoveEvent; +import com.github.intellectualsites.plotsquared.bukkit.events.PlotMergeEvent; +import com.github.intellectualsites.plotsquared.bukkit.events.PlotRateEvent; +import com.github.intellectualsites.plotsquared.bukkit.events.PlotUnlinkEvent; 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.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.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.Rating; import com.github.intellectualsites.plotsquared.plot.util.EventUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -16,99 +37,95 @@ import java.util.List; import java.util.UUID; /** - * Utility class for handling Bukkit {@link Event events} + * Utility class for handling Bukkit Events. */ public final class BukkitEventUtil extends EventUtil { - @Nullable public Player getPlayer(final PlotPlayer player) { - if (player instanceof BukkitPlayer) { - return ((BukkitPlayer) player).player; - } - return null; + @Nullable public Player getPlayer(final PlotPlayer player) { + if (player instanceof BukkitPlayer) { + return ((BukkitPlayer) player).player; } + return null; + } - private boolean callEvent(@Nonnull final Event event) { - Bukkit.getServer().getPluginManager().callEvent(event); - return !(event instanceof Cancellable) || !((Cancellable) event).isCancelled(); - } + private boolean callEvent(@Nonnull final Event event) { + Bukkit.getServer().getPluginManager().callEvent(event); + return !(event instanceof Cancellable) || !((Cancellable) event).isCancelled(); + } - @Override public boolean callClaim(PlotPlayer player, Plot plot, boolean auto) { - return callEvent(new PlayerClaimPlotEvent(getPlayer(player), plot, 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) { - return callEvent(new PlayerTeleportToPlotEvent(getPlayer(player), from, 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) { - return callEvent(new PlotComponentSetEvent(plot, component)); - } + @Override public boolean callComponentSet(Plot plot, String component) { + return callEvent(new PlotComponentSetEvent(plot, component)); + } - @Override public boolean callClear(Plot plot) { - return callEvent(new PlotClearEvent(plot)); - } + @Override public boolean callClear(Plot plot) { + return callEvent(new PlotClearEvent(plot)); + } - @Override public boolean callDelete(Plot plot) { - return callEvent(new PlotDeleteEvent(plot)); - } + @Override public boolean callDelete(Plot plot) { + return callEvent(new PlotDeleteEvent(plot)); + } - @Override public boolean callFlagAdd(Flag flag, Plot plot) { - return callEvent(new PlotFlagAddEvent(flag, 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) { - return callEvent(new PlotFlagRemoveEvent(flag, plot)); - } + @Override public boolean callFlagRemove(Flag flag, Plot plot, Object value) { + return callEvent(new PlotFlagRemoveEvent(flag, plot)); + } - @Override public boolean callMerge(Plot plot, int dir, int max) { - return callEvent(new PlotMergeEvent(BukkitUtil.getWorld(plot.getWorldName()), plot, dir, max)); - } + @Override public boolean callMerge(Plot plot, int dir, int max) { + return callEvent(new PlotMergeEvent(BukkitUtil.getWorld(plot.getWorldName()), plot, dir, max)); + } - @Override public boolean callAutoMerge(Plot plot, List plots) { - return callEvent(new PlotAutoMergeEvent(BukkitUtil.getWorld(plot.getWorldName()), plot, plots)); - } + @Override public boolean callAutoMerge(Plot plot, List plots) { + return callEvent(new PlotAutoMergeEvent(BukkitUtil.getWorld(plot.getWorldName()), plot, plots)); + } - @Override public boolean callUnlink(PlotArea area, List plots) { - return callEvent(new PlotUnlinkEvent(BukkitUtil.getWorld(area.worldname), area, plots)); - } + @Override public boolean callUnlink(PlotArea area, List plots) { + return callEvent(new PlotUnlinkEvent(BukkitUtil.getWorld(area.worldname), area, plots)); + } - @Override public void callEntry(PlotPlayer player, Plot plot) { - callEvent(new PlayerEnterPlotEvent(getPlayer(player), plot)); - } + @Override public void callEntry(PlotPlayer player, Plot plot) { + callEvent(new PlayerEnterPlotEvent(getPlayer(player), plot)); + } - @Override public void callLeave(PlotPlayer player, Plot plot) { - callEvent(new PlayerLeavePlotEvent(getPlayer(player), 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) { - callEvent(new PlayerPlotDeniedEvent(getPlayer(initiator), plot, player, 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) { - callEvent(new PlayerPlotTrustedEvent(getPlayer(initiator), plot, player, 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) { - callEvent(new PlayerPlotHelperEvent(getPlayer(initiator), plot, player, 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)); - } + @Override + 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) { - return callEvent(new ClusterFlagRemoveEvent(flag, cluster)); - } - - @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()) { - return null; - } - return event.getRating(); + @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()) { + return null; } + return event.getRating(); + } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitHybridUtils.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitHybridUtils.java index b7eebcc04..fb0d20fbc 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitHybridUtils.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitHybridUtils.java @@ -2,6 +2,7 @@ package com.github.intellectualsites.plotsquared.bukkit.util; import com.github.intellectualsites.plotsquared.bukkit.generator.BukkitPlotGenerator; import com.github.intellectualsites.plotsquared.plot.PlotSquared; +import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld; import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; import com.github.intellectualsites.plotsquared.plot.object.*; @@ -65,11 +66,13 @@ public class BukkitHybridUtils extends HybridUtils { System.gc(); final BlockBucket[][][] oldBlocks = new BlockBucket[256][width][length]; final PlotBlock[][][] newBlocks = new PlotBlock[256][width][length]; + final BlockBucket airBucket = BlockBucket.withSingle(StringPlotBlock.EVERYTHING); PlotArea area = PlotSquared.get().getPlotArea(world, null); - if (!(area instanceof HybridPlotWorld)) + if (!(area instanceof HybridPlotWorld)) { return; + } HybridPlotWorld hpw = (HybridPlotWorld) area; final BlockBucket[][] result = hpw.getBlockBucketChunk(); @@ -107,7 +110,12 @@ public class BukkitHybridUtils extends HybridUtils { } rz[i] = v; } - int minY = Math.min(hpw.PLOT_HEIGHT, hpw.ROAD_HEIGHT); + int minY; + if (Settings.Schematics.PASTE_ON_TOP) { + minY = hpw.SCHEM_Y; + } else { + minY = 1; + } for (short x = 0; x < 16; x++) { for (short z = 0; z < 16; z++) { BaseBlock[] blocks = hpw.G_SCH.get(MathMan.pair(rx[x], rz[z])); @@ -140,8 +148,7 @@ public class BukkitHybridUtils extends HybridUtils { continue; } int y = MainUtil.y_loc[i][j]; - oldBlocks[y][x][z] = - BlockBucket.withSingle(StringPlotBlock.EVERYTHING); + oldBlocks[y][x][z] = airBucket; } continue; } @@ -155,9 +162,7 @@ public class BukkitHybridUtils extends HybridUtils { continue; } int y = MainUtil.y_loc[i][j]; - oldBlocks[y][x][z] = result[i][j] != null ? - result[i][j] : - BlockBucket.withSingle(StringPlotBlock.EVERYTHING); + oldBlocks[y][x][z] = result[i][j] != null ? result[i][j] : airBucket; } } @@ -177,7 +182,7 @@ public class BukkitHybridUtils extends HybridUtils { BlockBucket old = oldBlocks[y][x][z]; try { if (old == null) { - old = BlockBucket.withSingle(StringPlotBlock.EVERYTHING); + old = airBucket; } PlotBlock now = newBlocks[y][x][z]; if (!old.getBlocks().contains(now)) { @@ -222,10 +227,6 @@ public class BukkitHybridUtils extends HybridUtils { types.add(now); } } catch (NullPointerException e) { - PlotSquared.log(old != null ? old.toString() : "old null"); - PlotSquared.log(x); - PlotSquared.log(y); - PlotSquared.log(z); e.printStackTrace(); } } @@ -303,7 +304,7 @@ public class BukkitHybridUtils extends HybridUtils { } } } - worldObj.unloadChunkRequest(X, Z, true); + worldObj.unloadChunkRequest(X, Z); } }, () -> TaskManager.runTaskAsync(run), 5); }); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitInventoryUtil.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitInventoryUtil.java index c40e13d09..2c66f8d3f 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitInventoryUtil.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitInventoryUtil.java @@ -17,106 +17,108 @@ import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; import java.util.List; +import java.util.stream.IntStream; public class BukkitInventoryUtil extends InventoryUtil { - public static ItemStack getItem(PlotItemStack item) { - if (item == null) { - return null; - } - ItemStack stack = new ItemStack(BukkitUtil.getMaterial(item.getPlotBlock()), item.amount); - ItemMeta meta = null; - if (item.name != null) { - meta = stack.getItemMeta(); - meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', item.name)); - } - if (item.lore != null) { - if (meta == null) { - meta = stack.getItemMeta(); - } - List lore = new ArrayList<>(); - for (String entry : item.lore) { - lore.add(ChatColor.translateAlternateColorCodes('&', entry)); - } - meta.setLore(lore); - } - if (meta != null) { - stack.setItemMeta(meta); - } - return stack; + @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(); + for (int i = 0; i < inv.size * 9; i++) { + PlotItemStack item = items[i]; + if (item != null) { + inventory.setItem(i, getItem(item)); + } } + bp.player.openInventory(inventory); + } - @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(); - for (int i = 0; i < inv.size * 9; i++) { - PlotItemStack item = items[i]; - if (item != null) { - inventory.setItem(i, getItem(item)); - } - } - bp.player.openInventory(inventory); + @Override public void close(PlotInventory inv) { + if (!inv.isOpen()) { + return; } + BukkitPlayer bp = (BukkitPlayer) inv.player; + bp.player.closeInventory(); + } - @Override public void close(PlotInventory inv) { - if (!inv.isOpen()) { - return; - } - BukkitPlayer bp = (BukkitPlayer) inv.player; - bp.player.closeInventory(); + @Override public void setItem(PlotInventory inv, int index, PlotItemStack item) { + BukkitPlayer bp = (BukkitPlayer) inv.player; + InventoryView opened = bp.player.getOpenInventory(); + if (!inv.isOpen()) { + return; } + opened.setItem(index, getItem(item)); + bp.player.updateInventory(); + } - @Override public void setItem(PlotInventory inv, int index, PlotItemStack item) { - BukkitPlayer bp = (BukkitPlayer) inv.player; - InventoryView opened = bp.player.getOpenInventory(); - if (!inv.isOpen()) { - return; - } - opened.setItem(index, getItem(item)); - bp.player.updateInventory(); + private static ItemStack getItem(PlotItemStack item) { + if (item == null) { + return null; } + ItemStack stack = new ItemStack(BukkitUtil.getMaterial(item.getPlotBlock()), item.amount); + ItemMeta meta = null; + if (item.name != null) { + meta = stack.getItemMeta(); + meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', item.name)); + } + if (item.lore != null) { + if (meta == null) { + meta = stack.getItemMeta(); + } + List lore = new ArrayList<>(); + for (String entry : item.lore) { + lore.add(ChatColor.translateAlternateColorCodes('&', entry)); + } + meta.setLore(lore); + } + if (meta != null) { + stack.setItemMeta(meta); + } + return stack; + } - public PlotItemStack getItem(ItemStack item) { - if (item == null) { - return null; - } - // int id = item.getTypeId(); - Material id = item.getType(); - short data = item.getDurability(); - int amount = item.getAmount(); - String name = null; - String[] lore = null; - if (item.hasItemMeta()) { - ItemMeta meta = item.getItemMeta(); - if (meta.hasDisplayName()) { - name = meta.getDisplayName(); - } - if (meta.hasLore()) { - List itemLore = meta.getLore(); - lore = itemLore.toArray(new String[itemLore.size()]); - } - } - return new PlotItemStack(id.name(), amount, name, lore); + public PlotItemStack getItem(ItemStack item) { + if (item == null) { + return null; } + // int id = item.getTypeId(); + Material id = item.getType(); + ItemMeta meta = item.getItemMeta(); + int amount = item.getAmount(); + String name = null; + String[] lore = null; + if (item.hasItemMeta()) { + assert meta != null; + if (meta.hasDisplayName()) { + name = meta.getDisplayName(); + } + if (meta.hasLore()) { + List itemLore = meta.getLore(); + lore = itemLore.toArray(new String[0]); + } + } + return new PlotItemStack(id.name(), amount, name, lore); + } - @Override public PlotItemStack[] getItems(PlotPlayer player) { - BukkitPlayer bp = (BukkitPlayer) player; - PlayerInventory inv = bp.player.getInventory(); - PlotItemStack[] items = new PlotItemStack[36]; - for (int i = 0; i < 36; i++) { - items[i] = getItem(inv.getItem(i)); - } - return items; - } + @Override public PlotItemStack[] getItems(PlotPlayer player) { + BukkitPlayer bp = (BukkitPlayer) player; + PlayerInventory inv = bp.player.getInventory(); + return IntStream.range(0, 36).mapToObj(i -> getItem(inv.getItem(i))) + .toArray(PlotItemStack[]::new); + } - @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; + @Override public boolean isOpen(PlotInventory plotInventory) { + if (!plotInventory.isOpen()) { + return false; } + BukkitPlayer bp = (BukkitPlayer) plotInventory.player; + InventoryView opened = bp.player.getOpenInventory(); + if (plotInventory.isOpen()) { + if (opened.getType() == InventoryType.CRAFTING) { + opened.getTitle(); + } + } + return false; + } } 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 index e9ec7742f..44c262b10 100644 --- 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 @@ -1,36 +1,47 @@ package com.github.intellectualsites.plotsquared.bukkit.util; +import com.github.intellectualsites.plotsquared.bukkit.BukkitMain; 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.LegacyMappings; import com.github.intellectualsites.plotsquared.plot.util.StringComparison; -import lombok.*; -import org.bukkit.Material; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; import java.util.stream.Collectors; +import lombok.AccessLevel; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import lombok.ToString; +import org.bukkit.Bukkit; +import org.bukkit.Material; + /** * 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) + * 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 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. + * 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 . + * You should have received a copy of the GNU General Public License along with this program. If + * not, see . */ public final class BukkitLegacyMappings extends LegacyMappings { @@ -75,7 +86,7 @@ public final class BukkitLegacyMappings extends LegacyMappings { 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, 1, "sandstone", "chiseled_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"), @@ -118,7 +129,7 @@ public final class BukkitLegacyMappings extends LegacyMappings { 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, "step", "stone_slab", "smooth_stone_slab"), new LegacyBlock(44, 1, "step", "sandstone_slab"), new LegacyBlock(44, 2, "step", "petrified_oak_slab"), new LegacyBlock(44, 3, "step", "cobblestone_slab"), @@ -139,10 +150,11 @@ public final class BukkitLegacyMappings extends LegacyMappings { 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(63, "sign_post", "sign", "oak_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(68, "wall_sign", "wall_sign", "oak_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"), @@ -182,10 +194,10 @@ public final class BukkitLegacyMappings extends LegacyMappings { 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, 1, "monster_eggs", "infested_cobblestone"), 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, 4, "monster_eggs", "infested_cracked_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"), @@ -208,7 +220,7 @@ public final class BukkitLegacyMappings extends LegacyMappings { 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(101, "iron_fence", "iron_bars"), 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"), @@ -541,7 +553,7 @@ public final class BukkitLegacyMappings extends LegacyMappings { 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, 27, "monster_egg", "zombie_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"), @@ -664,22 +676,24 @@ public final class BukkitLegacyMappings extends LegacyMappings { 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() { + @SuppressWarnings("deprecation") public BukkitLegacyMappings() { this.addAll(Arrays.asList(BLOCKS)); // Make sure to add new blocks as well final List missing = new ArrayList<>(); for (final Material material : Material.values()) { final String materialName = material.name().toLowerCase(Locale.ENGLISH); - if (OLD_STRING_TO_STRING_PLOT_BLOCK.get(materialName) == null) { - final LegacyBlock missingBlock = - new LegacyBlock(material.getId(), materialName, materialName); - missing.add(missingBlock); + if (NEW_STRING_TO_LEGACY_PLOT_BLOCK.get(materialName) == null) { + try { + final LegacyBlock missingBlock = + new LegacyBlock(material.getId(), materialName, materialName); + missing.add(missingBlock); + } catch (Exception ignored) { + } } } addAll(missing); @@ -687,13 +701,6 @@ public final class BukkitLegacyMappings extends LegacyMappings { private void addAll(@NonNull final Collection blocks) { 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()); - } */ LEGACY_ID_AND_DATA_TO_STRING_PLOT_BLOCK .put(new IdDataPair(legacyBlock.getNumericalId(), legacyBlock.getDataValue()), legacyBlock.toStringPlotBlock()); @@ -705,7 +712,14 @@ public final class BukkitLegacyMappings extends LegacyMappings { try { material = Material.valueOf(legacyBlock.getNewName()); } catch (final Exception e) { - material = Material.getMaterial(legacyBlock.getLegacyName(), true); + try { + material = Material.getMaterial(legacyBlock.getLegacyName(), true); + } catch (NoSuchMethodError error) { + PlotSquared.log("You can't use this version of PlotSquared on a server " + + "less than Minecraft 1.13.2"); + Bukkit.shutdown(); + break; + } } legacyBlock.material = material; } @@ -724,13 +738,10 @@ public final class BukkitLegacyMappings extends LegacyMappings { } /** - * 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 + * 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 @@ -741,19 +752,31 @@ public final class BukkitLegacyMappings extends LegacyMappings { } String workingString = string; String[] parts = null; + IdDataPair idDataPair = null; if (string.contains(":")) { parts = string.split(":"); if (parts.length > 1) { if (parts[0].equalsIgnoreCase("minecraft")) { workingString = parts[1]; } else { - workingString = parts[0]; + if (parts[0].matches("^\\d+$")) { + idDataPair = + new IdDataPair(Integer.parseInt(parts[0]), Integer.parseInt(parts[0])); + } else { + workingString = parts[0]; + } } } + } else if (string.matches("^\\d+$")) { + idDataPair = new IdDataPair(Integer.parseInt(string), 0); } PlotBlock plotBlock; - if (NEW_STRING_TO_LEGACY_PLOT_BLOCK.keySet().contains(workingString.toLowerCase())) { + if (Material.matchMaterial(workingString) != null) { return PlotBlock.get(workingString); + } else if (NEW_STRING_TO_LEGACY_PLOT_BLOCK.keySet().contains(workingString.toLowerCase())) { + return PlotBlock.get(workingString); + } else if ((plotBlock = fromLegacyToString(idDataPair)) != null) { + return plotBlock; } else if ((plotBlock = fromLegacyToString(workingString)) != null) { return plotBlock; } else { @@ -775,6 +798,13 @@ public final class BukkitLegacyMappings extends LegacyMappings { return LEGACY_ID_AND_DATA_TO_STRING_PLOT_BLOCK.get(new IdDataPair(id, data)); } + public PlotBlock fromLegacyToString(IdDataPair idDataPair) { + if (idDataPair == null) { + return null; + } + return LEGACY_ID_AND_DATA_TO_STRING_PLOT_BLOCK.get(idDataPair); + } + public PlotBlock fromLegacyToString(final String id) { return OLD_STRING_TO_STRING_PLOT_BLOCK.get(id); } @@ -804,6 +834,20 @@ public final class BukkitLegacyMappings extends LegacyMappings { this(numericalId, dataValue, legacyName, legacyName); } + LegacyBlock(final int numericalId, final int dataValue, @NonNull final String legacyName, + @NonNull final String newName, @NonNull final String new14Name) { + this(numericalId, dataValue, legacyName, + PlotSquared.get().IMP.getServerVersion()[1] == 13 ? newName : new14Name); + } + + LegacyBlock(final int numericalId, @NonNull final String legacyName, + @NonNull final String newName, @NonNull final String new14Name) { + this(numericalId, 0, legacyName, + Bukkit.getBukkitVersion().split("-")[0].split("\\.")[1].equals("13") ? + newName : + new14Name); + } + LegacyBlock(final int numericalId, @NonNull final String legacyName, @NonNull final String newName) { this(numericalId, 0, legacyName, newName); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java index efdb034cd..958def626 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/BukkitSetupUtils.java @@ -9,8 +9,12 @@ 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.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; @@ -61,11 +65,11 @@ public class BukkitSetupUtils extends SetupUtils { } if (save) { for (Chunk chunk : world.getLoadedChunks()) { - chunk.unload(true, false); + chunk.unload(true); } } else { for (Chunk chunk : world.getLoadedChunks()) { - chunk.unload(false, false); + chunk.unload(false); } } Bukkit.unloadWorld(world, false); @@ -123,23 +127,28 @@ public class BukkitSetupUtils extends SetupUtils { break; } case 1: { - if (!PlotSquared.get().worlds.contains(worldPath)) { - PlotSquared.get().worlds.createSection(worldPath); - } - ConfigurationSection worldSection = - PlotSquared.get().worlds.getConfigurationSection(worldPath); - for (ConfigurationNode step : steps) { - worldSection.set(step.getConstant(), step.getValue()); - } - 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)) { + if (!object.plotManager.endsWith(":single")) { + if (!PlotSquared.get().worlds.contains(worldPath)) { + PlotSquared.get().worlds.createSection(worldPath); + } + if (steps.length != 0) { + ConfigurationSection worldSection = + PlotSquared.get().worlds.getConfigurationSection(worldPath); + for (ConfigurationNode step : steps) { + worldSection.set(step.getConstant(), step.getValue()); + } + } PlotSquared.get().worlds - .set("worlds." + world + ".generator.init", object.setupGenerator); + .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()) { @@ -166,9 +175,9 @@ public class BukkitSetupUtils extends SetupUtils { } catch (IOException e) { e.printStackTrace(); } + Plugin plugin = Bukkit.getPluginManager().getPlugin("Multiverse-Core"); if (object.setupGenerator != null) { - if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit - .getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { + if (plugin != null && plugin.isEnabled()) { Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal -g " + object.setupGenerator); setGenerator(world, object.setupGenerator); @@ -176,15 +185,6 @@ public class BukkitSetupUtils extends SetupUtils { 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); - setGenerator(world, object.setupGenerator); - if (Bukkit.getWorld(world) != null) { - return world; - } - } WorldCreator wc = new WorldCreator(object.world); wc.generator(object.setupGenerator); wc.environment(Environment.NORMAL); @@ -192,22 +192,13 @@ 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()) { + if (plugin != null && plugin.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.getWorld(world) != null) { - return world; - } - } World bw = Bukkit.createWorld(new WorldCreator(object.world).environment(Environment.NORMAL)); } 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 index dcee95c67..66b509615 100644 --- 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 @@ -2,7 +2,7 @@ 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.config.Captions; import com.github.intellectualsites.plotsquared.plot.object.*; import com.github.intellectualsites.plotsquared.plot.object.schematic.PlotItem; import com.github.intellectualsites.plotsquared.plot.util.*; @@ -13,7 +13,7 @@ import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.World; import org.bukkit.block.*; -import org.bukkit.block.data.type.WallSign; +import org.bukkit.block.data.Directional; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; @@ -174,9 +174,9 @@ import java.util.*; * * @param player the recipient of the message * @param caption the message - * @see MainUtil#sendMessage(PlotPlayer, C, String...) + * @see MainUtil#sendMessage(com.github.intellectualsites.plotsquared.commands.CommandCaller, Captions, String...) */ - public static void sendMessage(Player player, C caption) { + public static void sendMessage(Player player, Captions caption) { MainUtil.sendMessage(BukkitUtil.getPlayer(player), caption); } @@ -264,34 +264,28 @@ import java.util.*; 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) { - BlockFace facing = BlockFace.EAST; - if (world.getBlockAt(x, y, z + 1).getType().isSolid()) - facing = BlockFace.NORTH; - else if (world.getBlockAt(x + 1, y, z).getType().isSolid()) - facing = BlockFace.WEST; - else if (world.getBlockAt(x, y, z - 1).getType().isSolid()) - facing = BlockFace.SOUTH; - block.setType(Material.WALL_SIGN, false); - final WallSign sign = (WallSign) block.getBlockData(); - sign.setFacing(facing); - block.setBlockData(sign, false); - } - 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]); + @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 { + if (block.isLiquid()) { + return y; + } + air++; + } } - sign.update(true); } + return bukkitWorld.getMaxHeight() - 1; } @Override @Nullable public String[] getSign(@NonNull final Location location) { @@ -330,29 +324,39 @@ import java.util.*; } } - @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++; - } + @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.LEGACY_SIGN && type != Material.LEGACY_WALL_SIGN) { + BlockFace facing = BlockFace.EAST; + if (world.getBlockAt(x, y, z + 1).getType().isSolid()) { + facing = BlockFace.NORTH; + } else if (world.getBlockAt(x + 1, y, z).getType().isSolid()) { + facing = BlockFace.WEST; + } else if (world.getBlockAt(x, y, z - 1).getType().isSolid()) { + facing = BlockFace.SOUTH; } + if (PlotSquared.get().IMP.getServerVersion()[1] == 13) { + block.setType(Material.valueOf("WALL_SIGN"), false); + } else { + block.setType(Material.valueOf("OAK_WALL_SIGN"), false); + } + final Directional sign = (Directional) block.getBlockData(); + sign.setFacing(facing); + block.setBlockData(sign, false); + } + 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); } - return bukkitWorld.getMaxHeight() - 1; } @Override public int getBiomeFromString(@NonNull final String biomeString) { @@ -366,11 +370,7 @@ import java.util.*; @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; + return Arrays.stream(biomes).map(Enum::name).toArray(String[]::new); } @Override diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/Metrics.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/Metrics.java new file mode 100644 index 000000000..ff6e1b310 --- /dev/null +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/Metrics.java @@ -0,0 +1,695 @@ +package com.github.intellectualsites.plotsquared.bukkit.util; + +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.RegisteredServiceProvider; +import org.bukkit.plugin.ServicePriority; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + +import javax.net.ssl.HttpsURLConnection; +import java.io.*; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.logging.Level; +import java.util.zip.GZIPOutputStream; + +/** + * bStats collects some data for plugin authors. + *

    + * Check out https://bStats.org/ to learn more about bStats! + */ +@SuppressWarnings({"WeakerAccess", "unused"}) +public class Metrics { + + static { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D + final String defaultPackage = new String( + new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); + final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure nobody just copy & pastes the example and use the wrong package names + if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } + + // The version of this bStats class + public static final int B_STATS_VERSION = 1; + + // The url to which the data is sent + private static final String URL = "https://bStats.org/submitData/bukkit"; + + // Is bStats enabled on this server? + private boolean enabled; + + // Should failed requests be logged? + private static boolean logFailedRequests; + + // Should the sent data be logged? + private static boolean logSentData; + + // Should the response text be logged? + private static boolean logResponseStatusText; + + // The uuid of the server + private static String serverUUID; + + // The plugin + private final Plugin plugin; + + // A list with all custom charts + private final List charts = new ArrayList<>(); + + /** + * Class constructor. + * + * @param plugin The plugin which stats should be submitted. + */ + public Metrics(Plugin plugin) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null!"); + } + this.plugin = plugin; + + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + + // Check if the config file exists + if (!config.isSet("serverUuid")) { + + // Add default values + config.addDefault("enabled", true); + // Every server gets it's unique random id. + config.addDefault("serverUuid", UUID.randomUUID().toString()); + // Should failed request be logged? + config.addDefault("logFailedRequests", false); + // Should the sent data be logged? + config.addDefault("logSentData", false); + // Should the response text be logged? + config.addDefault("logResponseStatusText", false); + + // Inform the server owners about bStats + config.options().header( + "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + + "To honor their work, you should not disable it.\n" + + "This has nearly no effect on the server performance!\n" + + "Check out https://bStats.org/ to learn more :)" + ).copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { } + } + + // Load the data + enabled = config.getBoolean("enabled", true); + serverUUID = config.getString("serverUuid"); + logFailedRequests = config.getBoolean("logFailedRequests", false); + logSentData = config.getBoolean("logSentData", false); + logResponseStatusText = config.getBoolean("logResponseStatusText", false); + + if (enabled) { + boolean found = false; + // Search for all other bStats Metrics classes to see if we are the first one + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + found = true; // We aren't the first + break; + } catch (NoSuchFieldException ignored) { } + } + // Register our service + Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); + if (!found) { + // We are the first! + startSubmitting(); + } + } + } + + /** + * Checks if bStats is enabled. + * + * @return Whether bStats is enabled or not. + */ + public boolean isEnabled() { + return enabled; + } + + /** + * Adds a custom chart. + * + * @param chart The chart to add. + */ + public void addCustomChart(CustomChart chart) { + if (chart == null) { + throw new IllegalArgumentException("Chart cannot be null!"); + } + charts.add(chart); + } + + /** + * Starts the Scheduler which submits our data every 30 minutes. + */ + private void startSubmitting() { + final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + if (!plugin.isEnabled()) { // Plugin was disabled + timer.cancel(); + return; + } + // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler + // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) + Bukkit.getScheduler().runTask(plugin, () -> submitData()); + } + }, 1000 * 60 * 5, 1000 * 60 * 30); + // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start + // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! + // WARNING: Just don't do it! + } + + /** + * Gets the plugin specific data. + * This method is called using Reflection. + * + * @return The plugin specific data. + */ + public JSONObject getPluginData() { + JSONObject data = new JSONObject(); + + String pluginName = plugin.getDescription().getName(); + String pluginVersion = plugin.getDescription().getVersion(); + + data.put("pluginName", pluginName); // Append the name of the plugin + data.put("pluginVersion", pluginVersion); // Append the version of the plugin + JSONArray customCharts = new JSONArray(); + for (CustomChart customChart : charts) { + // Add the data of the custom charts + JSONObject chart = customChart.getRequestJsonObject(); + if (chart == null) { // If the chart is null, we skip it + continue; + } + customCharts.add(chart); + } + data.put("customCharts", customCharts); + + return data; + } + + /** + * Gets the server specific data. + * + * @return The server specific data. + */ + private JSONObject getServerData() { + // Minecraft specific data + int playerAmount; + try { + // Around MC 1.8 the return type was changed to a collection from an array, + // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) + ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() + : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed + } + int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; + String bukkitVersion = Bukkit.getVersion(); + + // OS/Java specific data + String javaVersion = System.getProperty("java.version"); + String osName = System.getProperty("os.name"); + String osArch = System.getProperty("os.arch"); + String osVersion = System.getProperty("os.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); + + JSONObject data = new JSONObject(); + + data.put("serverUUID", serverUUID); + + data.put("playerAmount", playerAmount); + data.put("onlineMode", onlineMode); + data.put("bukkitVersion", bukkitVersion); + + data.put("javaVersion", javaVersion); + data.put("osName", osName); + data.put("osArch", osArch); + data.put("osVersion", osVersion); + data.put("coreCount", coreCount); + + return data; + } + + /** + * Collects the data and sends it afterwards. + */ + private void submitData() { + final JSONObject data = getServerData(); + + JSONArray pluginData = new JSONArray(); + // Search for all other bStats Metrics classes to get their plugin data + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + + for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { + try { + pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider())); + } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } + } + } catch (NoSuchFieldException ignored) { } + } + + data.put("plugins", pluginData); + + // Create a new thread for the connection to the bStats server + new Thread(new Runnable() { + @Override + public void run() { + try { + // Send the data + sendData(plugin, data); + } catch (Exception e) { + // Something went wrong! :( + if (logFailedRequests) { + plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); + } + } + } + }).start(); + } + + /** + * Sends the data to the bStats server. + * + * @param plugin Any plugin. It's just used to get a logger instance. + * @param data The data to send. + * @throws Exception If the request failed. + */ + private static void sendData(Plugin plugin, JSONObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null!"); + } + if (Bukkit.isPrimaryThread()) { + throw new IllegalAccessException("This method must not be called from the main thread!"); + } + if (logSentData) { + plugin.getLogger().info("Sending data to bStats: " + data.toString()); + } + HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); + + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); + + // Add headers + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format + connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); + + // Send data + connection.setDoOutput(true); + DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); + outputStream.write(compressedData); + outputStream.flush(); + outputStream.close(); + + InputStream inputStream = connection.getInputStream(); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + + StringBuilder builder = new StringBuilder(); + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + bufferedReader.close(); + if (logResponseStatusText) { + plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString()); + } + } + + /** + * Gzips the given String. + * + * @param str The string to gzip. + * @return The gzipped String. + * @throws IOException If the compression failed. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + GZIPOutputStream gzip = new GZIPOutputStream(outputStream); + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + gzip.close(); + return outputStream.toByteArray(); + } + + /** + * Represents a custom chart. + */ + public static abstract class CustomChart { + + // The id of the chart + final String chartId; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + */ + CustomChart(String chartId) { + if (chartId == null || chartId.isEmpty()) { + throw new IllegalArgumentException("ChartId cannot be null or empty!"); + } + this.chartId = chartId; + } + + private JSONObject getRequestJsonObject() { + JSONObject chart = new JSONObject(); + chart.put("chartId", chartId); + try { + JSONObject data = getChartData(); + if (data == null) { + // If the data is null we don't send the chart. + return null; + } + chart.put("data", data); + } catch (Throwable t) { + if (logFailedRequests) { + Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); + } + return null; + } + return chart; + } + + protected abstract JSONObject getChartData() throws Exception; + + } + + /** + * Represents a custom simple pie. + */ + public static class SimplePie extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimplePie(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + String value = callable.call(); + if (value == null || value.isEmpty()) { + // Null = skip the chart + return null; + } + data.put("value", value); + return data; + } + } + + /** + * Represents a custom advanced pie. + */ + public static class AdvancedPie extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedPie(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.put(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + } + + /** + * Represents a custom drilldown pie. + */ + public static class DrilldownPie extends CustomChart { + + private final Callable>> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public DrilldownPie(String chartId, Callable>> callable) { + super(chartId); + this.callable = callable; + } + + @Override + public JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map> map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean reallyAllSkipped = true; + for (Map.Entry> entryValues : map.entrySet()) { + JSONObject value = new JSONObject(); + boolean allSkipped = true; + for (Map.Entry valueEntry : map.get(entryValues.getKey()).entrySet()) { + value.put(valueEntry.getKey(), valueEntry.getValue()); + allSkipped = false; + } + if (!allSkipped) { + reallyAllSkipped = false; + values.put(entryValues.getKey(), value); + } + } + if (reallyAllSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + } + + /** + * Represents a custom single line chart. + */ + public static class SingleLineChart extends CustomChart { + + private final Callable callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SingleLineChart(String chartId, Callable callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + int value = callable.call(); + if (value == 0) { + // Null = skip the chart + return null; + } + data.put("value", value); + return data; + } + + } + + /** + * Represents a custom multi line chart. + */ + public static class MultiLineChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public MultiLineChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue() == 0) { + continue; // Skip this invalid + } + allSkipped = false; + values.put(entry.getKey(), entry.getValue()); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + + } + + /** + * Represents a custom simple bar chart. + */ + public static class SimpleBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public SimpleBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + for (Map.Entry entry : map.entrySet()) { + JSONArray categoryValues = new JSONArray(); + categoryValues.add(entry.getValue()); + values.put(entry.getKey(), categoryValues); + } + data.put("values", values); + return data; + } + + } + + /** + * Represents a custom advanced bar chart. + */ + public static class AdvancedBarChart extends CustomChart { + + private final Callable> callable; + + /** + * Class constructor. + * + * @param chartId The id of the chart. + * @param callable The callable which is used to request the chart data. + */ + public AdvancedBarChart(String chartId, Callable> callable) { + super(chartId); + this.callable = callable; + } + + @Override + protected JSONObject getChartData() throws Exception { + JSONObject data = new JSONObject(); + JSONObject values = new JSONObject(); + Map map = callable.call(); + if (map == null || map.isEmpty()) { + // Null = skip the chart + return null; + } + boolean allSkipped = true; + for (Map.Entry entry : map.entrySet()) { + if (entry.getValue().length == 0) { + continue; // Skip this invalid + } + allSkipped = false; + JSONArray categoryValues = new JSONArray(); + for (int categoryValue : entry.getValue()) { + categoryValues.add(categoryValue); + } + values.put(entry.getKey(), categoryValues); + } + if (allSkipped) { + // Null = skip the chart + return null; + } + data.put("values", values); + return data; + } + } + +} diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/NbtFactory.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/NbtFactory.java index ffc69edfc..acf0f82fa 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/NbtFactory.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/NbtFactory.java @@ -154,6 +154,7 @@ public class NbtFactory { * @return The decoded NBT compound. * @throws IOException If anything went wrong. */ + @SuppressWarnings({"IOResourceOpenedButNotSafelyClosed", "resource"}) public static NbtCompound fromStream(InputStream input, StreamOptions option) throws IOException { DataInputStream data = null; @@ -189,24 +190,11 @@ public class NbtFactory { */ 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); + try (OutputStream output = stream.openStream(); + DataOutputStream data = new DataOutputStream( + option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output)) { invokeMethod(get().SAVE_COMPOUND, null, source.getHandle(), data); - suppress = false; - - } finally { - if (data != null) { - Closeables.close(data, suppress); - } else if (output != null) { - Closeables.close(output, suppress); - } } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/OfflinePlayerUtil.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/OfflinePlayerUtil.java index f1bc97bb1..a3e40fae1 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/OfflinePlayerUtil.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/OfflinePlayerUtil.java @@ -13,14 +13,6 @@ import static com.github.intellectualsites.plotsquared.plot.util.ReflectionUtils public class OfflinePlayerUtil { - public static Player loadPlayer(String name) { - return loadPlayer(Bukkit.getOfflinePlayer(name)); - } - - public static Player loadPlayer(UUID id) { - return loadPlayer(Bukkit.getOfflinePlayer(id)); - } - public static Player loadPlayer(OfflinePlayer player) { if (player == null) { return null; diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SendChunk.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SendChunk.java index f0987b219..6ed7317b6 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SendChunk.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SendChunk.java @@ -65,11 +65,7 @@ public class SendChunk { int view = Bukkit.getServer().getViewDistance(); for (Chunk chunk : chunks) { String world = chunk.getWorld().getName(); - ArrayList list = map.get(world); - if (list == null) { - list = new ArrayList<>(); - map.put(world, list); - } + ArrayList list = map.computeIfAbsent(world, k -> new ArrayList<>()); list.add(chunk); Object c = this.methodGetHandleChunk.of(chunk).call(); this.methodInitLighting.of(c).call(); @@ -92,14 +88,14 @@ public class SendChunk { if (location == null) { location = pp.getLocation(); } - int cx = location.getX() >> 4; - int cz = location.getZ() >> 4; + int chunkX = location.getX() >> 4; + int chunkZ = location.getZ() >> 4; Player player = ((BukkitPlayer) pp).player; Object entity = this.methodGetHandlePlayer.of(player).call(); for (Chunk chunk : list) { - int dx = Math.abs(cx - chunk.getX()); - int dz = Math.abs(cz - chunk.getZ()); + int dx = Math.abs(chunkX - chunk.getX()); + int dz = Math.abs(chunkZ - chunk.getZ()); if ((dx > view) || (dz > view)) { continue; } @@ -118,20 +114,17 @@ public class SendChunk { } } for (final Chunk chunk : chunks) { - TaskManager.runTask(new Runnable() { - @Override public void run() { - try { - chunk.unload(true, false); - } catch (Throwable ignored) { - String worldName = chunk.getWorld().getName(); - 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)"); - } + TaskManager.runTask(() -> { + try { + chunk.unload(true); + } catch (Throwable ignored) { + String worldName = chunk.getWorld().getName(); + 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/github/intellectualsites/plotsquared/bukkit/util/SetGenCB.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SetGenCB.java index 110635f2d..45814d639 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SetGenCB.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/SetGenCB.java @@ -5,12 +5,10 @@ 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; import java.lang.reflect.Field; import java.util.ArrayList; -import java.util.Iterator; public class SetGenCB { @@ -45,12 +43,8 @@ public class SetGenCB { } } if (!set) { - Iterator iterator = world.getPopulators().iterator(); - while (iterator.hasNext()) { - if (iterator.next() instanceof BukkitAugmentedGenerator) { - iterator.remove(); - } - } + world.getPopulators() + .removeIf(blockPopulator -> blockPopulator instanceof BukkitAugmentedGenerator); } PlotSquared.get() .loadWorld(world.getName(), PlotSquared.get().IMP.getGenerator(world.getName(), null)); diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/BukkitLocalQueue.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/BukkitLocalQueue.java index 77518690d..5d8f53355 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/BukkitLocalQueue.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/BukkitLocalQueue.java @@ -6,7 +6,6 @@ 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 com.sk89q.jnbt.CompoundTag; import com.sk89q.worldedit.bukkit.BukkitAdapter; @@ -20,21 +19,16 @@ import org.bukkit.block.Biome; import org.bukkit.block.Block; import org.bukkit.block.data.BlockData; -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 class BukkitLocalQueue extends BasicLocalBlockQueue { public BukkitLocalQueue(String world) { super(world); } - @Override public LocalChunk getLocalChunk(int x, int z) { - return (LocalChunk) new BasicLocalChunk(this, x, z) { + @Override public LocalChunk getLocalChunk(int x, int z) { + return new BasicLocalChunk(this, x, z) { // Custom stuff? }; } @@ -45,21 +39,21 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { @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) { + if (worldObj != null) { + Block block = worldObj.getBlockAt(x, y, z); + return PlotBlock.get(block.getType().toString()); + } else { return PlotBlock.get(0, 0); } - // 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) { World worldObj = Bukkit.getWorld(getWorld()); - worldObj.refreshChunk(x, z); + if (worldObj != null) { + worldObj.refreshChunk(x, z); + } else { + PlotSquared.debug("Error Refreshing Chunk"); + } } @Override public void fixChunkLighting(int x, int z) { @@ -68,15 +62,15 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { @Override public final void regenChunk(int x, int z) { World worldObj = Bukkit.getWorld(getWorld()); - worldObj.regenerateChunk(x, z); + if (worldObj != null) { + worldObj.regenerateChunk(x, z); + } else { + PlotSquared.debug("Error Regenerating Chunk"); + } } - @Override public final void setComponents(LocalChunk lc) { - if (isBaseBlocks()) { - setBaseBlocks(lc); - } else { - setBlocks(lc); - } + @Override public final void setComponents(LocalChunk lc) { + setBaseBlocks(lc); } public World getBukkitWorld() { @@ -87,31 +81,7 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { return getBukkitWorld().getChunkAt(x, z); } - public void setBlocks(LocalChunk lc) { - World worldObj = Bukkit.getWorld(getWorld()); - Chunk chunk = worldObj.getChunkAt(lc.getX(), lc.getZ()); - chunk.load(true); - for (int layer = 0; layer < lc.blocks.length; layer++) { - PlotBlock[] blocksLayer = (PlotBlock[]) lc.blocks[layer]; - if (blocksLayer != null) { - for (int j = 0; j < blocksLayer.length; j++) { - if (blocksLayer[j] != null) { - PlotBlock block = blocksLayer[j]; - int x = MainUtil.x_loc[layer][j]; - int y = MainUtil.y_loc[layer][j]; - int z = MainUtil.z_loc[layer][j]; - Block existing = chunk.getBlock(x, y, z); - if (equals(block, existing)) { - continue; - } - setMaterial(block, existing); - } - } - } - } - } - - public void setBaseBlocks(LocalChunk lc) { + public void setBaseBlocks(LocalChunk lc) { World worldObj = Bukkit.getWorld(getWorld()); Chunk chunk = worldObj.getChunkAt(lc.getX(), lc.getZ()); chunk.load(true); @@ -182,22 +152,17 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { legacyPlotBlock.id == 0 || legacyPlotBlock.data == block.getData()); } - public void setBiomes(LocalChunk lc) { + public void setBiomes(LocalChunk lc) { if (lc.biomes != null) { World worldObj = Bukkit.getWorld(getWorld()); int bx = lc.getX() << 4; int bz = lc.getX() << 4; - String last = null; - Biome biome = null; for (int x = 0; x < lc.biomes.length; x++) { String[] biomes2 = lc.biomes[x]; if (biomes2 != null) { - for (int y = 0; y < biomes2.length; y++) { - String biomeStr = biomes2[y]; + for (String biomeStr : biomes2) { if (biomeStr != null) { - if (last == null || !StringMan.isEqual(last, biomeStr)) { - biome = Biome.valueOf(biomeStr.toUpperCase()); - } + Biome biome = Biome.valueOf(biomeStr.toUpperCase()); worldObj.setBiome(bx, bz, biome); } } @@ -206,59 +171,4 @@ public class BukkitLocalQueue extends BasicLocalBlockQueue { } } - /** - * Exploiting a bug in the vanilla lighting algorithm for faster block placement - * - Could have been achieved without reflection by force unloading specific chunks - * - Much faster just setting the variable manually though - * - * @param chunk - * @return - */ - protected Object[] disableLighting(Chunk chunk) { - try { - if (chunkGetHandle == null) { - chunkGetHandle = chunk.getClass().getDeclaredMethod("getHandle"); - chunkGetHandle.setAccessible(true); - } - Object nmsChunk = chunkGetHandle.invoke(chunk); - if (fieldNeighbors == null) { - fieldNeighbors = nmsChunk.getClass().getDeclaredField("neighbors"); - fieldNeighbors.setAccessible(true); - } - Object value = fieldNeighbors.get(nmsChunk); - fieldNeighbors.set(nmsChunk, 0); - return new Object[] {nmsChunk, value}; - } catch (Throwable ignore) { - } - return null; - } - - protected void disableLighting(Object[] disableResult) { - if (disableResult != null) { - try { - fieldNeighbors.set(disableResult[0], 0); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - } - } - - protected void resetLighting(Object[] disableResult) { - if (disableResult != null) { - try { - fieldNeighbors.set(disableResult[0], disableResult[1]); - } catch (Throwable ignore) { - ignore.printStackTrace(); - } - } - } - - protected void enableLighting(Object[] disableResult) { - if (disableResult != null) { - try { - fieldNeighbors.set(disableResult[0], 0x739C0); - } catch (Throwable ignore) { - } - } - } } diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/GenChunk.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/GenChunk.java index b905c2d5b..fc2bc3574 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/GenChunk.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/util/block/GenChunk.java @@ -23,47 +23,47 @@ public class GenChunk extends ScopedLocalBlockQueue { public final Biome[] biomes; public PlotBlock[][] result; - public BiomeGrid grid; + public BiomeGrid biomeGrid; public Chunk chunk; public String world; - public int cx; - public int cz; - @Getter @Setter private ChunkData cd = null; + public int chunkX; + public int chunkZ; + @Getter @Setter private ChunkData chunkData = null; - public GenChunk(Chunk chunk, ChunkWrapper wrap) { + public GenChunk() { super(null, new Location(null, 0, 0, 0), new Location(null, 15, 255, 15)); this.biomes = Biome.values(); } - public void setChunk(Chunk chunk) { - this.chunk = chunk; - } - public Chunk getChunk() { if (chunk == null) { World worldObj = BukkitUtil.getWorld(world); if (worldObj != null) { - this.chunk = worldObj.getChunkAt(cx, cz); + this.chunk = worldObj.getChunkAt(chunkX, chunkZ); } } return chunk; } + public void setChunk(Chunk chunk) { + this.chunk = chunk; + } + public void setChunk(ChunkWrapper wrap) { chunk = null; world = wrap.world; - cx = wrap.x; - cz = wrap.z; + chunkX = wrap.x; + chunkZ = wrap.z; } @Override public void fillBiome(String biomeName) { - if (grid == null) { + if (biomeGrid == null) { return; } Biome biome = Biome.valueOf(biomeName.toUpperCase()); for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { - this.grid.setBiome(x, z, biome); + this.biomeGrid.setBiome(x, z, biome); } } } @@ -82,13 +82,14 @@ public class GenChunk extends ScopedLocalBlockQueue { Arrays.fill(data, start, end, block); } } - int minx = Math.min(pos1.getX(), pos2.getX()); - int miny = Math.min(pos1.getY(), pos2.getY()); - int minz = Math.min(pos1.getZ(), pos2.getZ()); - int maxx = Math.max(pos1.getX(), pos2.getX()); - int maxy = Math.max(pos1.getY(), pos2.getY()); - int maxz = Math.max(pos1.getZ(), pos2.getZ()); - cd.setRegion(minx, miny, minz, maxx, maxy, maxz, block.to(Material.class)); + int minX = Math.min(pos1.getX(), pos2.getX()); + int minY = Math.min(pos1.getY(), pos2.getY()); + int minZ = Math.min(pos1.getZ(), pos2.getZ()); + int maxX = Math.max(pos1.getX(), pos2.getX()); + int maxY = Math.max(pos1.getY(), pos2.getY()); + int maxZ = Math.max(pos1.getZ(), pos2.getZ()); + chunkData + .setRegion(minX, minY, minZ, maxX + 1, maxY + 1, maxZ + 1, block.to(Material.class)); } @Override public boolean setBiome(int x, int z, String biome) { @@ -96,8 +97,8 @@ public class GenChunk extends ScopedLocalBlockQueue { } public boolean setBiome(int x, int z, Biome biome) { - if (this.grid != null) { - this.grid.setBiome(x, z, biome); + if (this.biomeGrid != null) { + this.biomeGrid.setBiome(x, z, biome); return true; } return false; @@ -105,10 +106,10 @@ public class GenChunk extends ScopedLocalBlockQueue { @Override public boolean setBlock(int x, int y, int z, PlotBlock id) { if (this.result == null) { - this.cd.setBlock(x, y, z, id.to(Material.class)); + this.chunkData.setBlock(x, y, z, id.to(Material.class)); return true; } - this.cd.setBlock(x, y, z, id.to(Material.class)); + this.chunkData.setBlock(x, y, z, id.to(Material.class)); this.storeCache(x, y, z, id); return true; } @@ -125,10 +126,10 @@ public class GenChunk extends ScopedLocalBlockQueue { @Override public boolean setBlock(int x, int y, int z, BaseBlock id) { if (this.result == null) { - this.cd.setBlock(x, y, z, BukkitAdapter.adapt(id)); + this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id)); return true; } - this.cd.setBlock(x, y, z, BukkitAdapter.adapt(id)); + this.chunkData.setBlock(x, y, z, BukkitAdapter.adapt(id)); this.storeCache(x, y, z, PlotBlock.get(id.getBlockType().getId())); return true; } @@ -136,7 +137,7 @@ public class GenChunk extends ScopedLocalBlockQueue { @Override public PlotBlock getBlock(int x, int y, int z) { int i = MainUtil.CACHE_I[y][x][z]; if (result == null) { - return PlotBlock.get(cd.getType(x, y, z)); + return PlotBlock.get(chunkData.getType(x, y, z)); } PlotBlock[] array = result[i]; if (array == null) { @@ -147,11 +148,11 @@ public class GenChunk extends ScopedLocalBlockQueue { } public int getX() { - return chunk == null ? cx : chunk.getX(); + return chunk == null ? chunkX : chunk.getX(); } public int getZ() { - return chunk == null ? cz : chunk.getZ(); + return chunk == null ? chunkZ : chunk.getZ(); } @Override public String getWorld() { @@ -167,8 +168,7 @@ public class GenChunk extends ScopedLocalBlockQueue { } public GenChunk clone() { - GenChunk toReturn = - new GenChunk(chunk, new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ())); + GenChunk toReturn = new GenChunk(); if (this.result != null) { for (int i = 0; i < this.result.length; i++) { PlotBlock[] matrix = this.result[i]; @@ -178,7 +178,7 @@ public class GenChunk extends ScopedLocalBlockQueue { } } } - toReturn.cd = this.cd; + toReturn.chunkData = this.chunkData; return toReturn; } } 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 index 3660bef92..40d902f8e 100644 --- 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 @@ -7,12 +7,14 @@ 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 org.jetbrains.annotations.NotNull; +import java.util.Arrays; import java.util.UUID; public class DefaultUUIDWrapper extends UUIDWrapper { - @Override public UUID getUUID(PlotPlayer player) { + @NotNull @Override public UUID getUUID(PlotPlayer player) { return ((BukkitPlayer) player).player.getUniqueId(); } @@ -30,11 +32,7 @@ public class DefaultUUIDWrapper extends UUIDWrapper { @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; + return Arrays.stream(ops).map(BukkitOfflinePlayer::new).toArray(BukkitOfflinePlayer[]::new); } @Override public OfflinePlotPlayer getOfflinePlayer(String name) { diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/FileUUIDHandler.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/FileUUIDHandler.java index 2223feceb..64a6db419 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/FileUUIDHandler.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/FileUUIDHandler.java @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.object.OfflinePlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; @@ -47,204 +47,197 @@ public class FileUUIDHandler extends UUIDHandlerImplementation { } else { world = worlds.get(0).getName(); } - TaskManager.runTaskAsync(new Runnable() { - @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); - for (String line : lines) { - try { - line = line.trim(); - if (line.isEmpty()) { - continue; - } - line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); - String[] split = line.split("\\|"); - String name = split[0]; - if (name.isEmpty() || (name.length() > 16) || !StringMan - .isAlphanumericUnd(name)) { - continue; - } - UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); - if (uuid == null) { - continue; - } - UUIDHandler.add(new StringWrapper(name), uuid); - } catch (Exception e2) { - e2.printStackTrace(); + TaskManager.runTaskAsync(() -> { + PlotSquared.debug(Captions.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); + for (String line : lines) { + try { + line = line.trim(); + if (line.isEmpty()) { + continue; } + line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); + String[] split = line.split("\\|"); + String name = split[0]; + if (name.isEmpty() || (name.length() > 16) || !StringMan + .isAlphanumericUnd(name)) { + continue; + } + UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); + if (uuid == null) { + continue; + } + UUIDHandler.add(new StringWrapper(name), uuid); + } catch (Exception e2) { + e2.printStackTrace(); } - } catch (IOException e) { - e.printStackTrace(); } + } catch (IOException e) { + e.printStackTrace(); } - HashBiMap toAdd = - HashBiMap.create(new HashMap()); - if (Settings.UUID.NATIVE_UUID_PROVIDER) { - HashSet all = UUIDHandler.getAllUUIDS(); - 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) { - for (String current : dat) { - String s = current.replaceAll(".dat$", ""); - try { - 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); - if (!compound.containsKey("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"); - String name = (String) bukkit.get("lastKnownName"); - long last = (long) bukkit.get("lastPlayed"); - long first = (long) bukkit.get("firstPlayed"); - if (ExpireManager.IMP != null) { - ExpireManager.IMP.storeDate(uuid, last); - ExpireManager.IMP.storeAccountAge(uuid, last - first); - } - toAdd.put(new StringWrapper(name), uuid); + } + HashBiMap toAdd = HashBiMap.create(new HashMap<>()); + if (Settings.UUID.NATIVE_UUID_PROVIDER) { + HashSet all = UUIDHandler.getAllUUIDS(); + 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) { + for (String current : dat) { + String s = current.replaceAll(".dat$", ""); + try { + 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); + if (!compound.containsKey("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"); + String name = (String) bukkit.get("lastKnownName"); + long last = (long) bukkit.get("lastPlayed"); + long first = (long) bukkit.get("firstPlayed"); + if (ExpireManager.IMP != null) { + ExpireManager.IMP.storeDate(uuid, last); + ExpireManager.IMP.storeAccountAge(uuid, last - first); } - } - } catch (Exception e) { - e.printStackTrace(); - PlotSquared.debug(C.PREFIX + "Invalid playerdata: " + current); - } - } - } - add(toAdd); - if (all.isEmpty()) { - if (whenDone != null) { - whenDone.run(); - } - return; - } else { - PlotSquared.debug("Failed to cache: " + all.size() - + " uuids - slowly processing all files"); - } - } - HashSet worlds = Sets.newHashSet(world, "world"); - HashSet uuids = new HashSet<>(); - HashSet names = new HashSet<>(); - File playerDataFolder = null; - for (String worldName : worlds) { - // Getting UUIDs - playerDataFolder = - new File(container, worldName + File.separator + "playerdata"); - String[] dat = playerDataFolder.list(new DatFileFilter()); - if ((dat != null) && (dat.length != 0)) { - for (String current : dat) { - String s = current.replaceAll(".dat$", ""); - try { - UUID uuid = UUID.fromString(s); - uuids.add(uuid); - } catch (Exception ignored) { - PlotSquared.debug(C.PREFIX + "Invalid PlayerData: " + current); - } - } - break; - } - // Getting names - File playersFolder = new File(worldName + File.separator + "players"); - dat = playersFolder.list(new DatFileFilter()); - if ((dat != null) && (dat.length != 0)) { - for (String current : dat) { - names.add(current.replaceAll(".dat$", "")); - } - break; - } - } - for (UUID uuid : uuids) { - try { - 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); - if (!compound.containsKey("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"); - 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)) { - uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); - } else { - long most = (long) compound.get("UUIDMost"); - long least = (long) compound.get("UUIDLeast"); - uuid = new UUID(most, least); - } - } - if (ExpireManager.IMP != null) { - ExpireManager.IMP.storeDate(uuid, last); - ExpireManager.IMP.storeAccountAge(uuid, last - first); - } - toAdd.put(wrap, uuid); - } - } - } catch (Exception ignored) { - PlotSquared - .debug(C.PREFIX + "&6Invalid PlayerData: " + uuid.toString() + ".dat"); - } - } - for (String name : names) { - UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); - StringWrapper nameWrap = new StringWrapper(name); - toAdd.put(nameWrap, uuid); - } - - if (getUUIDMap().isEmpty()) { - for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper - .getOfflinePlayers()) { - long last = op.getLastPlayed(); - if (last != 0) { - String name = op.getName(); - StringWrapper wrap = new StringWrapper(name); - if (!toAdd.containsKey(wrap)) { - UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(op); - toAdd.put(wrap, uuid); - if (ExpireManager.IMP != null) { - ExpireManager.IMP.storeDate(uuid, last); + toAdd.put(new StringWrapper(name), uuid); } } + } catch (Exception e) { + e.printStackTrace(); + PlotSquared.debug(Captions.PREFIX + "Invalid playerdata: " + current); } } } add(toAdd); - if (whenDone != null) { - whenDone.run(); + if (all.isEmpty()) { + if (whenDone != null) { + whenDone.run(); + } + return; + } else { + PlotSquared.debug( + "Failed to cache: " + all.size() + " uuids - slowly processing all files"); } } + HashSet worlds1 = Sets.newHashSet(world, "world"); + HashSet uuids = new HashSet<>(); + HashSet names = new HashSet<>(); + File playerDataFolder = null; + for (String worldName : worlds1) { + // Getting UUIDs + playerDataFolder = new File(container, worldName + File.separator + "playerdata"); + String[] dat = playerDataFolder.list(new DatFileFilter()); + if ((dat != null) && (dat.length != 0)) { + for (String current : dat) { + String s = current.replaceAll(".dat$", ""); + try { + UUID uuid = UUID.fromString(s); + uuids.add(uuid); + } catch (Exception ignored) { + PlotSquared.debug(Captions.PREFIX + "Invalid PlayerData: " + current); + } + } + break; + } + // Getting names + File playersFolder = new File(worldName + File.separator + "players"); + dat = playersFolder.list(new DatFileFilter()); + if ((dat != null) && (dat.length != 0)) { + for (String current : dat) { + names.add(current.replaceAll(".dat$", "")); + } + break; + } + } + for (UUID uuid : uuids) { + try { + 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); + if (!compound.containsKey("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"); + 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)) { + uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); + } else { + long most = (long) compound.get("UUIDMost"); + long least = (long) compound.get("UUIDLeast"); + uuid = new UUID(most, least); + } + } + if (ExpireManager.IMP != null) { + ExpireManager.IMP.storeDate(uuid, last); + ExpireManager.IMP.storeAccountAge(uuid, last - first); + } + toAdd.put(wrap, uuid); + } + } + } catch (Exception ignored) { + PlotSquared.debug( + Captions.PREFIX + "&6Invalid PlayerData: " + uuid.toString() + ".dat"); + } + } + for (String name : names) { + UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name); + StringWrapper nameWrap = new StringWrapper(name); + toAdd.put(nameWrap, uuid); + } + + if (getUUIDMap().isEmpty()) { + for (OfflinePlotPlayer offlinePlotPlayer : FileUUIDHandler.this.uuidWrapper + .getOfflinePlayers()) { + long last = offlinePlotPlayer.getLastPlayed(); + if (last != 0) { + String name = offlinePlotPlayer.getName(); + StringWrapper wrap = new StringWrapper(name); + if (!toAdd.containsKey(wrap)) { + UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(offlinePlotPlayer); + toAdd.putIfAbsent(wrap, uuid); + if (ExpireManager.IMP != null) { + ExpireManager.IMP.storeDate(uuid, last); + } + } + } + } + } + add(toAdd); + if (whenDone != null) { + whenDone.run(); + } }); return true; } @Override public void fetchUUID(final String name, final RunnableVal ifFetch) { - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name); - TaskManager.runTask(ifFetch); - } + TaskManager.runTaskAsync(() -> { + 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 index 55e2039a0..3f33387b9 100644 --- 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 @@ -4,14 +4,14 @@ 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 org.jetbrains.annotations.NotNull; 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)); + @NotNull @Override public UUID getUUID(PlotPlayer player) { + return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8)); } @Override public UUID getUUID(OfflinePlotPlayer player) { diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java index c44fa6e72..306f67e4e 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/OfflineUUIDWrapper.java @@ -13,9 +13,11 @@ import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.Server; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.util.Arrays; import java.util.Collection; import java.util.UUID; @@ -32,9 +34,8 @@ public class OfflineUUIDWrapper extends UUIDWrapper { } } - @Override public UUID getUUID(PlotPlayer player) { - return UUID - .nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); + @NotNull @Override public UUID getUUID(PlotPlayer player) { + return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); } @Override public UUID getUUID(OfflinePlotPlayer player) { @@ -70,7 +71,7 @@ public class OfflineUUIDWrapper extends UUIDWrapper { public Player[] getOnlinePlayers() { if (this.getOnline == null) { Collection onlinePlayers = Bukkit.getOnlinePlayers(); - return onlinePlayers.toArray(new Player[onlinePlayers.size()]); + return onlinePlayers.toArray(new Player[0]); } try { Object players = this.getOnline.invoke(Bukkit.getServer(), this.arg); @@ -79,13 +80,13 @@ public class OfflineUUIDWrapper extends UUIDWrapper { } else { @SuppressWarnings("unchecked") Collection p = (Collection) players; - return p.toArray(new Player[p.size()]); + return p.toArray(new Player[0]); } } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ignored) { PlotSquared.debug("Failed to resolve online players"); this.getOnline = null; Collection onlinePlayers = Bukkit.getOnlinePlayers(); - return onlinePlayers.toArray(new Player[onlinePlayers.size()]); + return onlinePlayers.toArray(new Player[0]); } } @@ -95,11 +96,7 @@ public class OfflineUUIDWrapper extends UUIDWrapper { @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; + return Arrays.stream(ops).map(BukkitOfflinePlayer::new).toArray(BukkitOfflinePlayer[]::new); } @Override public OfflinePlotPlayer getOfflinePlayer(String name) { diff --git a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/SQLUUIDHandler.java b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/SQLUUIDHandler.java index 1c9a30bba..86cd9ae0d 100644 --- a/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/SQLUUIDHandler.java +++ b/Bukkit/src/main/java/com/github/intellectualsites/plotsquared/bukkit/uuid/SQLUUIDHandler.java @@ -1,7 +1,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.database.SQLite; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; @@ -71,135 +71,119 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { if (!super.startCaching(whenDone)) { return false; } - TaskManager.runTaskAsync(new Runnable() { - @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()) { - while (resultSet.next()) { - StringWrapper username = - new StringWrapper(resultSet.getString("username")); - UUID uuid = UUID.fromString(resultSet.getString("uuid")); - toAdd.put(new StringWrapper(username.value), uuid); - } + TaskManager.runTaskAsync(() -> { + try { + 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")); + UUID uuid = UUID.fromString(resultSet.getString("uuid")); + toAdd.put(new StringWrapper(username.value), uuid); } - add(toAdd); - // This should be called as long as there are some unknown plots - final ArrayDeque toFetch = new ArrayDeque<>(); - for (UUID u : UUIDHandler.getAllUUIDS()) { - if (!uuidExists(u)) { - toFetch.add(u); - } + } + add(toAdd); + // This should be called as long as there are some unknown plots + final ArrayDeque toFetch = new ArrayDeque<>(); + for (UUID u : UUIDHandler.getAllUUIDS()) { + if (!uuidExists(u)) { + toFetch.add(u); } - if (toFetch.isEmpty()) { + } + if (toFetch.isEmpty()) { + if (whenDone != null) { + whenDone.run(); + } + return; + } + FileUUIDHandler fileHandler = new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper); + fileHandler.startCaching(() -> { + // 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) { if (whenDone != null) { whenDone.run(); } return; } - FileUUIDHandler fileHandler = - new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper); - fileHandler.startCaching(new Runnable() { - @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) { - if (whenDone != null) { - whenDone.run(); - } - return; - } - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - while (!toFetch.isEmpty()) { - try { - 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); - String name = (String) response.get("name"); - if (name != null) { - add(new StringWrapper(name), uuid); - } - } - connection.disconnect(); - } - } 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); - } catch (InterruptedException e) { - e.printStackTrace(); - break; + TaskManager.runTaskAsync(() -> { + while (!toFetch.isEmpty()) { + try { + for (int i = 0; i < Math.min(MAX_REQUESTS, 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); + String name = (String) response.get("name"); + if (name != null) { + add(new StringWrapper(name), uuid); } } - if (whenDone != null) { - whenDone.run(); - } - return; + connection.disconnect(); } - }); + } 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); + } catch (InterruptedException e) { + e.printStackTrace(); + break; + } } + if (whenDone != null) { + whenDone.run(); + } + return; }); - } catch (SQLException e) { - throw new SQLUUIDHandlerException("Couldn't select :s", e); - } + }); + } catch (SQLException e) { + throw new SQLUUIDHandlerException("Couldn't select :s", e); } }); return true; } @Override public void fetchUUID(final String name, final RunnableVal ifFetch) { - PlotSquared.debug(C.PREFIX + "UUID for '" + name + PlotSquared.debug(Captions.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() { - try { - URL url = new URL(SQLUUIDHandler.this.PROFILE_URL); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("POST"); - connection.setRequestProperty("Content-Type", "application/json"); - connection.setUseCaches(false); - connection.setDoInput(true); - connection.setDoOutput(true); - String body = JSONArray.toJSONString(Collections.singletonList(name)); - OutputStream stream = connection.getOutputStream(); - stream.write(body.getBytes()); - stream.flush(); - stream.close(); - 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)); - } catch (IOException | ParseException e) { - e.printStackTrace(); - } - TaskManager.runTask(ifFetch); + TaskManager.runTaskAsync(() -> { + try { + URL url = new URL(SQLUUIDHandler.this.PROFILE_URL); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setUseCaches(false); + connection.setDoInput(true); + connection.setDoOutput(true); + String body = JSONArray.toJSONString(Collections.singletonList(name)); + OutputStream stream = connection.getOutputStream(); + stream.write(body.getBytes()); + stream.flush(); + stream.close(); + JSONArray array = (JSONArray) SQLUUIDHandler.this.jsonParser + .parse(new InputStreamReader(connection.getInputStream())); + JSONObject jsonProfile = (JSONObject) array.get(0); + String id = (String) jsonProfile.get("id"); + String name1 = (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)); + } catch (IOException | ParseException e) { + e.printStackTrace(); } + TaskManager.runTask(ifFetch); }); } @@ -212,47 +196,43 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation { } } - @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(?, ?)")) { - statement.setString(1, uuid.toString()); - statement.setString(2, name.toString()); - statement.execute(); - PlotSquared - .debug(C.PREFIX + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'"); - } catch (SQLException e) { - e.printStackTrace(); - } - } - }); - return true; - } - return false; - } - /** * This is useful for name changes */ @Override public void rename(final UUID uuid, final StringWrapper name) { super.rename(uuid, name); - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { + TaskManager.runTaskAsync(() -> { + try (PreparedStatement statement = getConnection() + .prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) { + statement.setString(1, name.value); + statement.setString(2, uuid.toString()); + statement.execute(); + PlotSquared.debug( + Captions.PREFIX + "Name change for '" + uuid + "' to '" + name.value + '\''); + } catch (SQLException e) { + e.printStackTrace(); + } + }); + } + + @Override public boolean add(final StringWrapper name, final UUID uuid) { + // Ignoring duplicates + if (super.add(name, uuid)) { + TaskManager.runTaskAsync(() -> { try (PreparedStatement statement = getConnection() - .prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) { - statement.setString(1, name.value); - statement.setString(2, uuid.toString()); + .prepareStatement("REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) { + statement.setString(1, uuid.toString()); + statement.setString(2, name.toString()); statement.execute(); - PlotSquared.debug( - C.PREFIX + "Name change for '" + uuid + "' to '" + name.value + '\''); + PlotSquared + .debug(Captions.PREFIX + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'"); } catch (SQLException e) { e.printStackTrace(); } - } - }); + }); + return true; + } + return false; } private class SQLUUIDHandlerException extends RuntimeException { diff --git a/Bukkit/src/main/resources/plugin.yml b/Bukkit/src/main/resources/plugin.yml index 565ceaf7f..4c6f33b10 100644 --- a/Bukkit/src/main/resources/plugin.yml +++ b/Bukkit/src/main/resources/plugin.yml @@ -62,7 +62,6 @@ permissions: plots.set.flag.vehicle-use.*: true plots.set.flag.vehicle-place.*: true plots.set.flag.vehicle-break.*: true - plots.set.flag.player-interact.*: true plots.set.flag.place.*: true plots.set.flag.break.*: true plots.set.flag.use.*: true @@ -72,19 +71,15 @@ permissions: plots.permpack.basicinbox: default: op children: - comments.notifications.enabled : true + comments.notifications.enabled: true plots.inbox.read.public: true plots.inbox.modify.public: true - plots.inbox.modify.public: true plots.inbox.write.public: true - plots.inbox.read.public: true plots.inbox.read.report: true plots.inbox.write.report: true - plots.inbox.read.report: true plots.inbox.read.owner: true plots.inbox.modify.owner: true plots.inbox.write.owner: true - plots.inbox.read.owner: true plots.comment: true plots.inbox: true plots.permpack.wilderness: @@ -256,9 +251,6 @@ permissions: plotme.limit.10: children: plots.plot.10: true - plotme.admin.home.other: - children: - plots.plot.: true plotme.admin.clear: children: plots.admin.command.clear: true diff --git a/Core/build.gradle b/Core/build.gradle index 14bda6198..3949c948e 100644 --- a/Core/build.gradle +++ b/Core/build.gradle @@ -1,11 +1,23 @@ -import org.ajoberstar.grgit.Grgit +repositories { + maven { url 'https://jitpack.io' } +} dependencies { - testCompile 'junit:junit:4.12' - compile 'org.yaml:snakeyaml:1.23' - compile 'com.google.code.gson:gson:2.8.5' - compileOnly 'org.projectlombok:lombok:1.18.4' + implementation 'org.yaml:snakeyaml:1.23' + //keep inline with Minecraft which uses gson 2.8.0 + implementation 'com.google.code.gson:gson:2.8.0' + implementation("org.projectlombok:lombok:1.18.6") + compileOnly("org.projectlombok:lombok:1.18.6") + testCompileOnly("org.projectlombok:lombok:1.18.6") + annotationProcessor("org.projectlombok:lombok:1.18.6") + testAnnotationProcessor("org.projectlombok:lombok:1.18.6") + implementation 'net.kyori:text-adapter-bukkit:3.0.2' + implementation 'com.github.Sauilitired:Jenkins4J:2.0-SNAPSHOT' + implementation 'com.squareup.okhttp3:okhttp:3.14.0' + implementation 'com.squareup.okio:okio:2.2.2' + implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.3.30' } + sourceCompatibility = 1.8 targetCompatibility = 1.8 @@ -21,34 +33,34 @@ processResources { } } -jar.archiveName = "Plotsquared-Api-${project.parent.version}.jar" -jar.destinationDir = file '../mvn/com/github/intellectualsites/plotsquared/Plotsquared-Api/' + project.parent.version +jar.setArchiveName("PlotSquared-API-${project.parent.version}.jar") +jar.destinationDir = file '../mvn/com/github/intellectualsites/plotsquared/PlotSquared-API/' + project.parent.version task createPom { doLast { pom { project { groupId 'com.github.intellectualsites.plotsquared' - artifactId 'Plotsquared' + artifactId 'PlotSquared-API' version project.parent.version } - }.writeTo("../mvn/com/github/intellectualsites/plotsquared/Plotsquared-Api/${project.parent.version}/Plotsquared-Api-${project.parent.version}.pom") + }.writeTo("../mvn/com/github/intellectualsites/plotsquared/PlotSquared-API/${project.parent.version}/PlotSquared-API-${project.parent.version}.pom") pom { project { groupId 'com.github.intellectualsites.plotsquared' - artifactId 'Plotsquared' + artifactId 'PlotSquared-API' version 'latest' } - }.writeTo("../mvn/com/github/intellectualsites/plotsquared/Plotsquared-Api/latest/Plotsquared-Api-latest.pom") + }.writeTo("../mvn/com/github/intellectualsites/plotsquared/PlotSquared-API/latest/PlotSquared-API-latest.pom") } } task copyFiles { doLast { copy { - from "../mvn/com/github/intellectualsites/plotsquared/Plotsquared-Api/${project.parent.version}/" - into '../mvn/com/github/intellectualsites/plotsquared/Plotsquared-Api/latest/' + from "../mvn/com/github/intellectualsites/plotsquared/PlotSquared-API/${project.parent.version}/" + into '../mvn/com/github/intellectualsites/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') } } } 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 index c966903be..d2b4e7343 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/api/PlotAPI.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/api/PlotAPI.java @@ -2,7 +2,7 @@ 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.config.Captions; import com.github.intellectualsites.plotsquared.plot.flag.Flag; import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.object.Plot; @@ -37,7 +37,7 @@ import java.util.UUID; @SuppressWarnings({"unused", "WeakerAccess"}) @NoArgsConstructor public class PlotAPI { /** - * Get all plots. + * Gets all plots. * * @return all plots * @see PlotSquared#getPlots() @@ -47,7 +47,7 @@ import java.util.UUID; } /** - * Return all plots for a player. + * Gets all plots for a player. * * @param player Player, whose plots to search for * @return all plots that a player owns @@ -57,7 +57,7 @@ import java.util.UUID; } /** - * Add a plot world. + * Adds a plot world. * * @param plotArea Plot World Object * @see PlotSquared#addPlotArea(PlotArea) @@ -67,17 +67,17 @@ import java.util.UUID; } /** - * Returns the PlotSquared configurations file. + * Gets the configuration file for this plugin. * - * @return main configuration - * @see PlotSquared#config + * @return the configuration file for PlotSquared + * = */ public YamlConfiguration getConfig() { - return PlotSquared.get().config; + return PlotSquared.get().getConfig(); } /** - * Get the PlotSquared storage file. + * Gets the PlotSquared storage file. * * @return storage configuration * @see PlotSquared#storage @@ -86,16 +86,6 @@ import java.util.UUID; 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. *

      @@ -114,7 +104,7 @@ import java.util.UUID; } /** - * Get the block/biome set queue + * Gets the block/biome set queue * * @return GlobalBlockQueue.IMP */ @@ -145,7 +135,7 @@ import java.util.UUID; } /** - * Get a list of PlotAreas in the world. + * Gets a list of PlotAreas in the world. * * @param world The world to check for plot areas * @return A set of PlotAreas @@ -161,20 +151,20 @@ import java.util.UUID; * Send a message to the console. The message supports color codes. * * @param message the message - * @see MainUtil#sendConsoleMessage(C, String...) + * @see MainUtil#sendConsoleMessage(Captions, String...) */ public void sendConsoleMessage(String message) { PlotSquared.log(message); } /** - * Send a message to the console. + * Sends a message to the console. * * @param caption the message * @see #sendConsoleMessage(String) - * @see C + * @see Captions */ - public void sendConsoleMessage(C caption) { + public void sendConsoleMessage(Captions caption) { sendConsoleMessage(caption.s()); } @@ -198,7 +188,7 @@ import java.util.UUID; } /** - * Get the PlotPlayer for a UUID. + * Gets the PlotPlayer for a UUID. * *

      Please note that PlotSquared can be configured to provide * different UUIDs than bukkit @@ -212,7 +202,7 @@ import java.util.UUID; } /** - * Get the PlotPlayer for a username. + * Gets the PlotPlayer for a username. * * @param player the player to wrap * @return a {@code PlotPlayer} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Command.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Command.java index a581b8585..e379edbac 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Command.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/commands/Command.java @@ -5,12 +5,16 @@ 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.config.Captions; 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 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.StringComparison; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; import java.io.IOException; import java.lang.reflect.InvocationTargetException; @@ -102,7 +106,7 @@ public abstract class Command { return this.id; } - public List getCommands(PlotPlayer player) { + public List getCommands(CommandCaller player) { List commands = new ArrayList<>(); for (Command cmd : this.allCommands) { if (cmd.canExecute(player, false)) { @@ -112,15 +116,10 @@ public abstract class Command { return commands; } - public List getCommands(CommandCategory cat, PlotPlayer player) { + public List getCommands(CommandCategory category, CommandCaller player) { List commands = getCommands(player); - if (cat != null) { - Iterator iterator = commands.iterator(); - while (iterator.hasNext()) { - if (iterator.next().category != cat) { - iterator.remove(); - } - } + if (category != null) { + commands.removeIf(command -> command.category != category); } return commands; } @@ -129,7 +128,7 @@ public abstract class Command { return this.allCommands; } - public boolean hasConfirmation(PlotPlayer player) { + public boolean hasConfirmation(CommandCaller player) { return this.confirmation && !player.hasPermission(getPermission() + ".confirm.bypass"); } @@ -158,10 +157,10 @@ public abstract class Command { this.perm = declaration.permission(); this.required = declaration.requiredType(); this.category = declaration.category(); - HashMap options = new HashMap<>(); List aliasOptions = new ArrayList<>(); aliasOptions.add(this.id); aliasOptions.addAll(Arrays.asList(declaration.aliases())); + HashMap options = new HashMap<>(); options.put("aliases", aliasOptions); options.put("description", declaration.description()); options.put("usage", declaration.usage()); @@ -245,18 +244,19 @@ public abstract class Command { 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); + .text(Captions.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") + .command(baseCommand + " " + (0 + 2)).text(Captions.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); + .color("$3").text("->").color("$3").text(Captions.CLICKABLE.s()).color("$2") + .send(player); } } @@ -274,7 +274,7 @@ public abstract class Command { if (this.parent == null) { MainCommand.getInstance().help.displayHelp(player, null, 0); } else { - C.COMMAND_SYNTAX.send(player, getUsage()); + Captions.COMMAND_SYNTAX.send(player, getUsage()); } return CompletableFuture.completedFuture(false); } @@ -286,7 +286,7 @@ public abstract class Command { Command cmd = getCommand(args[0]); if (cmd == null) { if (this.parent != null) { - C.COMMAND_SYNTAX.send(player, getUsage()); + Captions.COMMAND_SYNTAX.send(player, getUsage()); return CompletableFuture.completedFuture(false); } // Help command @@ -301,11 +301,11 @@ public abstract class Command { } catch (IllegalArgumentException ignored) { } // Command recommendation - MainUtil.sendMessage(player, C.NOT_VALID_SUBCOMMAND); + MainUtil.sendMessage(player, Captions.NOT_VALID_SUBCOMMAND); List commands = getCommands(player); if (commands.isEmpty()) { - MainUtil - .sendMessage(player, C.DID_YOU_MEAN, MainCommand.getInstance().help.getUsage()); + MainUtil.sendMessage(player, Captions.DID_YOU_MEAN, + MainCommand.getInstance().help.getUsage()); return CompletableFuture.completedFuture(false); } HashSet setArgs = new HashSet<>(args.length); @@ -323,7 +323,7 @@ public abstract class Command { if (cmd == null) { cmd = new StringComparison<>(args[0], this.allCommands).getMatchObject(); } - MainUtil.sendMessage(player, C.DID_YOU_MEAN, cmd.getUsage()); + MainUtil.sendMessage(player, Captions.DID_YOU_MEAN, cmd.getUsage()); return CompletableFuture.completedFuture(false); } String[] newArgs = Arrays.copyOfRange(args, 1, args.length); @@ -338,7 +338,7 @@ public abstract class Command { return CompletableFuture.completedFuture(true); } - public boolean checkArgs(PlotPlayer player, String[] args) { + public boolean checkArgs(CommandCaller player, String[] args) { Argument[] reqArgs = getRequiredArguments(); if (reqArgs != null && reqArgs.length > 0) { boolean failed = args.length < reqArgs.length; @@ -355,7 +355,7 @@ public abstract class Command { failed = failed || reqArgs[i].parse(args[i]) == null; } if (failed) { - C.COMMAND_SYNTAX.send(player, StringMan.join(fullSplit, " ")); + Captions.COMMAND_SYNTAX.send(player, StringMan.join(fullSplit, " ")); return false; } } @@ -363,14 +363,10 @@ public abstract class Command { } public int getMatch(String[] args, Command cmd) { - int count = 0; String perm = cmd.getPermission(); HashSet desc = new HashSet<>(); - for (String alias : cmd.getAliases()) { - if (alias.startsWith(args[0])) { - count += 5; - } - } + int count = cmd.getAliases().stream().filter(alias -> alias.startsWith(args[0])) + .mapToInt(alias -> 5).sum(); Collections.addAll(desc, cmd.getDescription().split(" ")); for (String arg : args) { if (perm.startsWith(arg)) { @@ -435,18 +431,19 @@ public abstract class Command { return null; } - public boolean canExecute(PlotPlayer player, boolean message) { + public boolean canExecute(CommandCaller player, boolean message) { if (player == null) { return true; } 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 ? + Captions.IS_CONSOLE : + Captions.NOT_CONSOLE); } } else if (!Permissions.hasPermission(player, getPermission())) { if (message) { - C.NO_PERMISSION.send(player, getPermission()); + Captions.NO_PERMISSION.send(player, getPermission()); } } else { return true; @@ -460,7 +457,6 @@ public abstract class Command { } public String getCommandString() { - String base; if (this.parent == null) { return "/" + toString(); } else { @@ -563,13 +559,13 @@ public abstract class Command { return this.getFullId().hashCode(); } - public void checkTrue(boolean mustBeTrue, C message, Object... args) { + public void checkTrue(boolean mustBeTrue, Captions message, Object... args) { if (!mustBeTrue) { throw new CommandException(message, args); } } - public T check(T object, C message, Object... args) { + public T check(T object, Captions message, Object... args) { if (object == null) { throw new CommandException(message, args); } @@ -583,14 +579,14 @@ public abstract class Command { public static class CommandException extends RuntimeException { private final Object[] args; - private final C message; + private final Captions message; - public CommandException(C message, Object... args) { + public CommandException(Captions message, Object... args) { this.message = message; this.args = args; } - public void perform(PlotPlayer player) { + public void perform(CommandCaller player) { if (player != null && message != null) { message.send(player, args); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfiguration.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfiguration.java index 668509bf3..a56c65901 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfiguration.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/file/FileConfiguration.java @@ -6,6 +6,7 @@ import com.github.intellectualsites.plotsquared.configuration.MemoryConfiguratio import java.io.*; import java.nio.charset.StandardCharsets; +import java.util.stream.Collectors; /** * This is a base class for all File based implementations of {@link @@ -14,13 +15,13 @@ import java.nio.charset.StandardCharsets; public abstract class FileConfiguration extends MemoryConfiguration { /** - * Creates an empty {@link FileConfiguration} with no default values. + * Creates an empty FileConfiguration with no default values. */ FileConfiguration() { } /** - * Creates an empty {@link FileConfiguration} using the specified {@link + * Creates an empty FileConfiguration using the specified {@link * Configuration} as a source for all default values. * * @param defaults Default value provider @@ -30,7 +31,7 @@ public abstract class FileConfiguration extends MemoryConfiguration { } /** - * Saves this {@link FileConfiguration} to the specified location. + * Saves this FileConfiguration to the specified location. * *

      If the file does not exist, it will be created. If already exists, it * will be overwritten. If it cannot be overwritten or created, an @@ -58,14 +59,14 @@ public abstract class FileConfiguration extends MemoryConfiguration { } /** - * Saves this {@link FileConfiguration} to a string, and returns it. + * Saves this FileConfiguration to a string, and returns it. * * @return String containing this configuration. */ public abstract String saveToString(); /** - * Loads this {@link FileConfiguration} from the specified location. + * Loads this FileConfiguration from the specified location. * *

      All the values contained within this configuration will be removed, * leaving only settings and defaults, and the new values will be loaded @@ -84,13 +85,13 @@ public abstract class FileConfiguration extends MemoryConfiguration { */ public void load(File file) throws IOException, InvalidConfigurationException { - FileInputStream stream = new FileInputStream(file); - - load(new InputStreamReader(stream, StandardCharsets.UTF_8)); + try (FileInputStream stream = new FileInputStream(file)) { + load(new InputStreamReader(stream, StandardCharsets.UTF_8)); + } } /** - * Loads this {@link FileConfiguration} from the specified reader. + * Loads this FileConfiguration from the specified reader. * *

      All the values contained within this configuration will be removed, * leaving only settings and defaults, and the new values will be loaded @@ -103,24 +104,20 @@ public abstract class FileConfiguration extends MemoryConfiguration { */ public void load(Reader reader) throws IOException, InvalidConfigurationException { - StringBuilder builder = new StringBuilder(); + String builder; try (BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader)) { - String line; - while ((line = input.readLine()) != null) { - builder.append(line); - builder.append('\n'); - } + builder = input.lines().map(line -> line + '\n').collect(Collectors.joining()); } - loadFromString(builder.toString()); + loadFromString(builder); } /** - * Loads this {@link FileConfiguration} from the specified string, as + * Loads this FileConfiguration from the specified string, as * opposed to from file. * *

      All the values contained within this configuration will be removed, @@ -136,7 +133,7 @@ public abstract class FileConfiguration extends MemoryConfiguration { public abstract void loadFromString(String contents) throws InvalidConfigurationException; /** - * Compiles the header for this {@link FileConfiguration} and returns the + * Compiles the header for this FileConfiguration and returns the * result. * *

      This will use the header from {@link #options()} -> {@link diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/ConfigurationSerialization.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/ConfigurationSerialization.java index 0783b4af5..cb1abd54a 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/ConfigurationSerialization.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/configuration/serialization/ConfigurationSerialization.java @@ -212,10 +212,15 @@ public class ConfigurationSerialization { 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); + if (ex instanceof InvocationTargetException) { + Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, + "Could not call method '" + method.toString() + "' of " + this.clazz + + " for deserialization", ex.getCause()); + } else { + Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, + "Could not call method '" + method.toString() + "' of " + this.clazz + + " for deserialization", ex); + } } return null; @@ -226,10 +231,15 @@ public class ConfigurationSerialization { 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); + if (ex instanceof InvocationTargetException) { + Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, + "Could not call constructor '" + ctor.toString() + "' of " + this.clazz + + " for deserialization", ex.getCause()); + } else { + Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, + "Could not call constructor '" + ctor.toString() + "' of " + this.clazz + + " for deserialization", ex); + } } return null; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONObject.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONObject.java index 9a84920dc..cd67bb158 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONObject.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/json/JSONObject.java @@ -9,6 +9,7 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; import java.util.Map.Entry; +import java.util.stream.IntStream; /** * A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces @@ -296,11 +297,7 @@ public class JSONObject { if (length == 0) { return null; } - String[] names = new String[length]; - for (int i = 0; i < length; i += 1) { - names[i] = fields[i].getName(); - } - return names; + return IntStream.range(0, length).mapToObj(i -> fields[i].getName()).toArray(String[]::new); } /** diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/IPlotMain.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/IPlotMain.java index e50ec9e8e..e1eb152b5 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/IPlotMain.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/IPlotMain.java @@ -8,6 +8,7 @@ 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 org.jetbrains.annotations.NotNull; import java.io.File; import java.util.List; @@ -15,28 +16,28 @@ import java.util.List; public interface IPlotMain extends ILogger { /** - * Log a message to console. + * Logs a message to console. * - * @param message The message to log + * @param message the message to log */ void log(String message); /** - * Get the `PlotSquared` directory. + * Gets the directory which contains PlotSquared files. The directory may not exist. * - * @return The plugin directory + * @return the PlotSquared directory */ File getDirectory(); /** - * Get the directory containing all the worlds. + * Gets the folder where all world data is stored. * - * @return The directory containing the worlds + * @return the world folder */ File getWorldContainer(); /** - * Wrap a player into a PlotPlayer object. + * Wraps a player into a PlotPlayer object. * * @param player The player to convert to a PlotPlayer * @return A PlotPlayer @@ -44,70 +45,56 @@ public interface IPlotMain extends ILogger { PlotPlayer wrapPlayer(Object player); /** - * Disable the implementation. - * - *

        - *
      • If a full disable isn't feasibly, just disable what it can. - *
      - */ - void disable(); - - /** - * Completely shut down the plugin + * Completely shuts down the plugin. */ void shutdown(); /** - * Get the version of the PlotSquared being used. + * Gets the version of the PlotSquared being used. * * @return the plugin version */ int[] getPluginVersion(); /** - * Get the version of the PlotSquared being used as a string. + * Gets 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. + * Gets the version of Minecraft that is running. * * @return */ int[] getServerVersion(); /** - * Get the server implementation name and version + * Gets the server implementation name and version */ String getServerImplementation(); /** - * Get the NMS package prefix. + * Gets the NMS package prefix. * * @return The NMS package prefix */ String getNMSPackage(); /** - * Get the schematic handler. + * Gets the schematic handler. * * @return The {@link SchematicHandler} */ SchematicHandler initSchematicHandler(); /** - * Get the Chat Manager. + * Starts the {@link ChatManager}. * - * @return The {@link ChatManager} + * @return the ChatManager */ ChatManager initChatManager(); @@ -124,7 +111,7 @@ public interface IPlotMain extends ILogger { void runEntityTask(); /** - * Register the implementation specific commands. + * Registerss the implementation specific commands. */ void registerCommands(); @@ -133,11 +120,6 @@ public interface IPlotMain extends ILogger { */ void registerPlayerEvents(); - /** - * Register inventory related events. - */ - void registerInventoryEvents(); - /** * Register plot plus related events. */ @@ -149,54 +131,54 @@ public interface IPlotMain extends ILogger { void registerForceFieldEvents(); /** - * Register the WorldEdit hook. + * Registers the WorldEdit hook. */ boolean initWorldEdit(); /** - * Get the economy provider. + * Gets the economy provider. * * @return */ EconHandler getEconomyHandler(); /** - * Get the {@link QueueProvider} class. + * Gets the {@link QueueProvider} class. * * @return */ QueueProvider initBlockQueue(); /** - * Get the {@link WorldUtil} class. + * Gets the {@link WorldUtil} class. * * @return */ WorldUtil initWorldUtil(); /** - * Get the EventUtil class. + * Gets the EventUtil class. * * @return */ EventUtil initEventUtil(); /** - * Get the chunk manager. + * Gets the chunk manager. * * @return */ ChunkManager initChunkManager(); /** - * Get the {@link SetupUtils} class. + * Gets the {@link SetupUtils} class. * * @return */ SetupUtils initSetupUtils(); /** - * Get {@link HybridUtils} class. + * Gets {@link HybridUtils} class. * * @return */ @@ -215,7 +197,7 @@ public interface IPlotMain extends ILogger { void setGenerator(String world); /** - * Get the {@link UUIDHandlerImplementation} which will cache and + * Gets the {@link UUIDHandlerImplementation} which will cache and * provide UUIDs. * * @return @@ -223,7 +205,7 @@ public interface IPlotMain extends ILogger { UUIDHandlerImplementation initUUIDHandler(); /** - * Get the {@link InventoryUtil} class (used for implementation specific + * Gets the {@link InventoryUtil} class (used for implementation specific * inventory guis). * * @return @@ -231,14 +213,14 @@ public interface IPlotMain extends ILogger { InventoryUtil initInventoryUtil(); /** - * Unregister a PlotPlayer from cache e.g. if they have logged off. + * Unregisters a {@link 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). + * Gets the generator wrapper for a world (world) and generator (name). * * @param world * @param name @@ -265,14 +247,7 @@ public interface IPlotMain extends ILogger { * * @return Default implementation generator */ - IndependentPlotGenerator getDefaultGenerator(); - - /** - * Get the class that will manage player titles. - * - * @return - */ - AbstractTitle initTitleManager(); + @NotNull IndependentPlotGenerator getDefaultGenerator(); List getPluginIds(); 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 index b7eb33b83..1736edf6f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/Platform.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/Platform.java @@ -1,6 +1,6 @@ package com.github.intellectualsites.plotsquared.plot; public enum Platform { - Bukkit, Sponge, Spigot, Cauldron + Bukkit, Sponge, Spigot, Paper } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotSquared.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotSquared.java index 2d55e9048..589309385 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotSquared.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotSquared.java @@ -5,11 +5,15 @@ 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.Captions; 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.database.DBFunc; +import com.github.intellectualsites.plotsquared.plot.database.Database; +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.generator.GeneratorWrapper; import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld; import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; @@ -40,7 +44,9 @@ import java.nio.file.Files; import java.sql.SQLException; import java.util.*; import java.util.Map.Entry; +import java.util.function.Consumer; import java.util.regex.Pattern; +import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -48,8 +54,8 @@ import java.util.zip.ZipInputStream; * An implementation of the core, with a static getter for easy access. */ @SuppressWarnings({"unused", "WeakerAccess"}) public class PlotSquared { - private static final Set EMPTY_SET = - Collections.unmodifiableSet(Collections.emptySet()); + private static final Set EMPTY_SET = Collections. + unmodifiableSet(Collections.emptySet()); private static PlotSquared instance; // Implementation public final IPlotMain IMP; @@ -63,17 +69,18 @@ import java.util.zip.ZipInputStream; public File commandsFile; public File translationFile; public YamlConfiguration style; - public YamlConfiguration config; public YamlConfiguration worlds; public YamlConfiguration storage; public YamlConfiguration commands; // Temporary hold the plots/clusters before the worlds load public HashMap> clusters_tmp; public HashMap> plots_tmp; + private YamlConfiguration config; // Implementation logger @Setter @Getter private ILogger logger; // Platform / Version / Update URL private PlotVersion version; + @Nullable @Getter private UpdateUtility updateUtility; // Files and configuration @Getter private File jarFile = null; // This file private File storageFile; @@ -128,7 +135,7 @@ import java.util.zip.ZipInputStream; this.translationFile = MainUtil.getFile(this.IMP.getDirectory(), Settings.Paths.TRANSLATIONS + File.separator + IMP.getPluginName() + ".use_THIS.yml"); - C.load(this.translationFile); + Captions.load(this.translationFile); // Setup plotAreaManager if (Settings.Enabled_Components.WORLDS) { @@ -150,16 +157,10 @@ import java.util.zip.ZipInputStream; } if (Settings.Enabled_Components.EVENTS) { this.IMP.registerPlayerEvents(); - this.IMP.registerInventoryEvents(); this.IMP.registerPlotPlusEvents(); } // Required this.IMP.registerWorldEvents(); - if (Settings.Enabled_Components.METRICS) { - this.IMP.startMetrics(); - } else { - PlotSquared.log(C.CONSOLE_PLEASE_ENABLE_METRICS.f(IMP.getPluginName())); - } if (Settings.Enabled_Components.CHUNK_PROCESSOR) { this.IMP.registerChunkProcessor(); } @@ -187,8 +188,6 @@ import java.util.zip.ZipInputStream; ChunkManager.manager = this.IMP.initChunkManager(); // Schematic handler SchematicHandler.manager = this.IMP.initSchematicHandler(); - // Titles - AbstractTitle.TITLE_CLASS = this.IMP.initTitleManager(); // Chat ChatManager.manager = this.IMP.initChatManager(); // Commands @@ -214,11 +213,8 @@ import java.util.zip.ZipInputStream; } // Economy if (Settings.Enabled_Components.ECONOMY) { - TaskManager.runTask(new Runnable() { - @Override public void run() { - EconHandler.manager = PlotSquared.this.IMP.getEconomyHandler(); - } - }); + TaskManager + .runTask(() -> EconHandler.manager = PlotSquared.this.IMP.getEconomyHandler()); } /* // Check for updates @@ -247,21 +243,20 @@ import java.util.zip.ZipInputStream; this.IMP.setGenerator(world); } } - TaskManager.runTaskLater(new Runnable() { - @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)"); - PlotSquared.this.IMP.setGenerator(world); - } + TaskManager.runTaskLater(() -> { + 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 worlds.yml, bukkit.yml and multiverse worlds.yml"); + debug( + "&8 - &7Your world management plugin may be faulty (or non existent)"); + PlotSquared.this.IMP.setGenerator(world); } } }, 1); @@ -289,11 +284,11 @@ import java.util.zip.ZipInputStream; e.printStackTrace(); } - PlotSquared.log(C.ENABLED.f(IMP.getPluginName())); + PlotSquared.log(Captions.ENABLED.f(IMP.getPluginName())); } /** - * Get an instance of PlotSquared. + * Gets an instance of PlotSquared. * * @return instance of PlotSquared */ @@ -342,25 +337,19 @@ import java.util.zip.ZipInputStream; } private void startUuidCatching() { - TaskManager.runTaskLater(new Runnable() { - @Override public void run() { - debug("Starting UUID caching"); - UUIDHandler.startCaching(new Runnable() { - @Override public void run() { - UUIDHandler.add(new StringWrapper("*"), DBFunc.EVERYONE); - foreachPlotRaw(new RunnableVal() { - @Override public void run(Plot plot) { - if (plot.hasOwner() && plot.temp != -1) { - if (UUIDHandler.getName(plot.owner) == null) { - UUIDHandler.implementation.unknown.add(plot.owner); - } - } - } - }); - startExpiryTasks(); + TaskManager.runTaskLater(() -> { + debug("Starting UUID caching"); + UUIDHandler.startCaching(() -> { + UUIDHandler.add(new StringWrapper("*"), DBFunc.EVERYONE); + forEachPlotRaw(plot -> { + if (plot.hasOwner() && plot.temp != -1) { + if (UUIDHandler.getName(plot.owner) == null) { + UUIDHandler.implementation.unknown.add(plot.owner); + } } }); - } + startExpiryTasks(); + }); }, 20); } @@ -392,7 +381,7 @@ import java.util.zip.ZipInputStream; } /** - * Get the current PlotSquared version. + * Gets the current PlotSquared version. * * @return current version in config or null */ @@ -401,8 +390,8 @@ import java.util.zip.ZipInputStream; } /** - * Get the server platform this plugin is running on this is running on. - *

      + * Gets the server platform this plugin is running on this is running on. + * *

      This will be either Bukkit or Sponge

      * * @return the server implementation @@ -495,11 +484,8 @@ import java.util.zip.ZipInputStream; if (this.plots_tmp == null) { this.plots_tmp = new HashMap<>(); } - HashMap map = this.plots_tmp.get(area.toString()); - if (map == null) { - map = new HashMap<>(); - this.plots_tmp.put(area.toString(), map); - } + HashMap map = + this.plots_tmp.computeIfAbsent(area.toString(), k -> new HashMap<>()); for (Plot plot : area.getPlots()) { map.put(plot.getId(), plot); } @@ -519,7 +505,7 @@ import java.util.zip.ZipInputStream; } /** - * Get all the base plots in a single set (for merged plots it just returns + * Gets all the base plots in a single set (for merged plots it just returns * the bottom plot). * * @return Set of base Plots @@ -527,14 +513,12 @@ import java.util.zip.ZipInputStream; public Set getBasePlots() { int size = getPlotCount(); final Set result = new HashSet<>(size); - foreachPlotArea(new RunnableVal() { - @Override public void run(PlotArea value) { - for (Plot plot : value.getPlots()) { - if (!plot.isBasePlot()) { - continue; - } - result.add(plot); + forEachPlotArea(value -> { + for (Plot plot : value.getPlots()) { + if (!plot.isBasePlot()) { + continue; } + result.add(plot); } }); return Collections.unmodifiableSet(result); @@ -567,11 +551,7 @@ import java.util.zip.ZipInputStream; result.add(plot); } } - Collections.sort(overflow, new Comparator() { - @Override public int compare(Plot a, Plot b) { - return a.hashCode() - b.hashCode(); - } - }); + overflow.sort(Comparator.comparingInt(Plot::hashCode)); result.addAll(overflow); return result; } @@ -581,12 +561,8 @@ import java.util.zip.ZipInputStream; * * @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 */ - // TODO: Re-evaluate deprecation of this, as it's being used internally - @Deprecated public ArrayList sortPlotsByHash(Collection plots) { + private ArrayList sortPlotsByHash(Collection plots) { int hardmax = 256000; int max = 0; int overflowSize = 0; @@ -618,7 +594,7 @@ import java.util.zip.ZipInputStream; overflow.add(plot); } } - Plot[] overflowArray = overflow.toArray(new Plot[overflow.size()]); + Plot[] overflowArray = overflow.toArray(new Plot[0]); sortPlotsByHash(overflowArray); ArrayList result = new ArrayList<>(cache.length + overflowArray.length); for (Plot plot : cache) { @@ -627,9 +603,7 @@ import java.util.zip.ZipInputStream; } } Collections.addAll(result, overflowArray); - for (Plot plot : extra) { - result.add(plot); - } + result.addAll(extra); return result; } @@ -638,8 +612,7 @@ import java.util.zip.ZipInputStream; * * @param input an array of plots to sort */ - // TODO: Re-evaluate deprecation of this, as it's being used internally - @Deprecated public void sortPlotsByHash(Plot[] input) { + private void sortPlotsByHash(Plot[] input) { List[] bucket = new ArrayList[32]; for (int i = 0; i < bucket.length; i++) { bucket[i] = new ArrayList<>(); @@ -648,26 +621,25 @@ import java.util.zip.ZipInputStream; int placement = 1; while (!maxLength) { maxLength = true; - for (Plot i : input) { - int tmp = MathMan.getPositiveId(i.hashCode()) / placement; - bucket[tmp & 31].add(i); + for (Plot plot : input) { + int tmp = MathMan.getPositiveId(plot.hashCode()) / placement; + bucket[tmp & 31].add(plot); if (maxLength && tmp > 0) { maxLength = false; } } int a = 0; - for (int b = 0; b < 32; b++) { - for (Plot i : bucket[b]) { - input[a++] = i; + for (int i = 0; i < 32; i++) { + for (Plot plot : bucket[i]) { + input[a++] = plot; } - bucket[b].clear(); + bucket[i].clear(); } placement *= 32; } } - // TODO: Re-evaluate deprecation of this, as it's being used internally - @Deprecated public ArrayList sortPlotsByTimestamp(Collection plots) { + private ArrayList sortPlotsByTimestamp(Collection plots) { int hardMax = 256000; int max = 0; int overflowSize = 0; @@ -699,7 +671,7 @@ import java.util.zip.ZipInputStream; overflow.add(plot); } } - Plot[] overflowArray = overflow.toArray(new Plot[overflow.size()]); + Plot[] overflowArray = overflow.toArray(new Plot[0]); sortPlotsByHash(overflowArray); ArrayList result = new ArrayList<>(cache.length + overflowArray.length); for (Plot plot : cache) { @@ -708,9 +680,7 @@ import java.util.zip.ZipInputStream; } } Collections.addAll(result, overflowArray); - for (Plot plot : extra) { - result.add(plot); - } + result.addAll(extra); return result; } @@ -719,29 +689,18 @@ import java.util.zip.ZipInputStream; * * @param input * @return - * @deprecated Unchecked, use {@link #sortPlots(Collection, SortType, PlotArea)} instead which will call this after checks */ - // TODO: Re-evaluate deprecation of this, as it's being used internally - @Deprecated public List sortPlotsByModified(Collection input) { + private List sortPlotsByModified(Collection input) { List list; if (input instanceof List) { list = (List) input; } else { 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)); - } - }); + list.sort(Comparator.comparingLong(a -> ExpireManager.IMP.getTimestamp(a.owner))); return list; } - public ArrayList sortPlots(Collection plots) { - return sortPlots(plots, SortType.DISTANCE_FROM_ORIGIN, null); - } - /** * Sort a collection of plots by world (with a priority world), then * by hashcode. @@ -764,7 +723,7 @@ import java.util.zip.ZipInputStream; } } else { for (PlotArea area : plotAreaManager.getAllPlotAreas()) { - map.put(area, new ArrayList(0)); + map.put(area, new ArrayList<>(0)); } Collection lastList = null; PlotArea lastWorld = null; @@ -779,17 +738,15 @@ import java.util.zip.ZipInputStream; } } List areas = Arrays.asList(plotAreaManager.getAllPlotAreas()); - Collections.sort(areas, new Comparator() { - @Override public int compare(PlotArea a, PlotArea b) { - if (priorityArea != null) { - if (a.equals(priorityArea)) { - return -1; - } else if (b.equals(priorityArea)) { - return 1; - } + areas.sort((a, b) -> { + if (priorityArea != null) { + if (a.equals(priorityArea)) { + return -1; + } else if (b.equals(priorityArea)) { + return 1; } - return a.hashCode() - b.hashCode(); } + return a.hashCode() - b.hashCode(); }); ArrayList toReturn = new ArrayList<>(plots.size()); for (PlotArea area : areas) { @@ -822,41 +779,35 @@ import java.util.zip.ZipInputStream; */ public Set getPlots(final PlotFilter... filters) { final HashSet set = new HashSet<>(); - foreachPlotArea(new RunnableVal() { - @Override public void run(PlotArea value) { + forEachPlotArea(value -> { + for (PlotFilter filter : filters) { + if (!filter.allowsArea(value)) { + return; + } + } + loop: + for (Entry entry2 : value.getPlotEntries()) { + Plot plot = entry2.getValue(); for (PlotFilter filter : filters) { - if (!filter.allowsArea(value)) { - return; + if (!filter.allowsPlot(plot)) { + continue loop; } } - loop: - for (Entry entry2 : value.getPlotEntries()) { - Plot plot = entry2.getValue(); - for (PlotFilter filter : filters) { - if (!filter.allowsPlot(plot)) { - continue loop; - } - } - set.add(plot); - } + set.add(plot); } }); return set; } /** - * Get all the plots in a single set. + * Gets all the plots across all plotworlds in one {@code Set}. * - * @return Set of Plots + * @return all the plots on the server loaded by this plugin */ public Set getPlots() { int size = getPlotCount(); final Set result = new HashSet<>(size); - foreachPlotArea(new RunnableVal() { - @Override public void run(PlotArea value) { - result.addAll(value.getPlots()); - } - }); + forEachPlotArea(value -> result.addAll(value.getPlots())); return result; } @@ -868,11 +819,8 @@ import java.util.zip.ZipInputStream; String world = entry.getKey(); PlotArea area = getPlotArea(world, null); if (area == null) { - HashMap map = this.plots_tmp.get(world); - if (map == null) { - map = new HashMap<>(); - this.plots_tmp.put(world, map); - } + HashMap map = + this.plots_tmp.computeIfAbsent(world, k -> new HashMap<>()); map.putAll(entry.getValue()); } else { for (Plot plot : entry.getValue().values()) { @@ -884,7 +832,7 @@ import java.util.zip.ZipInputStream; } /** - * Get all the plots owned by a player name. + * Gets all the plots owned by a player name. * * @param world the world * @param player the plot owner @@ -896,7 +844,7 @@ import java.util.zip.ZipInputStream; } /** - * Get all the plots owned by a player name. + * Gets all the plots owned by a player name. * * @param area the PlotArea * @param player the plot owner @@ -908,7 +856,7 @@ import java.util.zip.ZipInputStream; } /** - * Get all plots by a PlotPlayer. + * Gets all plots by a PlotPlayer. * * @param world the world * @param player the plot owner @@ -919,7 +867,7 @@ import java.util.zip.ZipInputStream; } /** - * Get all plots by a PlotPlayer. + * Gets all plots by a PlotPlayer. * * @param area the PlotArea * @param player the plot owner @@ -930,24 +878,21 @@ import java.util.zip.ZipInputStream; } /** - * Get all plots by a UUID in a world. + * Gets all plots by a UUID in a world. * * @param world the world * @param uuid the plot owner * @return Set of plot */ public Set getPlots(String world, UUID uuid) { - final Set plots = new HashSet<>(); - for (final Plot plot : getPlots(world)) { - if (plot.hasOwner() && plot.isOwnerAbs(uuid)) { - plots.add(plot); - } - } + final Set plots = + getPlots(world).stream().filter(plot -> plot.hasOwner() && plot.isOwnerAbs(uuid)) + .collect(Collectors.toSet()); return Collections.unmodifiableSet(plots); } /** - * Get all plots by a UUID in an area. + * Gets all plots by a UUID in an area. * * @param area the {@code PlotArea} * @param uuid the plot owner @@ -976,16 +921,12 @@ import java.util.zip.ZipInputStream; public Collection getPlots(String world) { final Set set = new HashSet<>(); - foreachPlotArea(world, new RunnableVal() { - @Override public void run(PlotArea value) { - set.addAll(value.getPlots()); - } - }); + forEachPlotArea(world, value -> set.addAll(value.getPlots())); return set; } /** - * Get the plots for a PlotPlayer. + * Gets the plots for a PlotPlayer. * * @param player the player to retrieve the plots for * @return Set of Plot @@ -1007,63 +948,54 @@ import java.util.zip.ZipInputStream; } /** - * Get the plots for a UUID. + * Gets 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 Set plots = new HashSet<>(); - foreachPlot(new RunnableVal() { - @Override public void run(Plot value) { - if (value.isOwnerAbs(uuid)) { - plots.add(value); - } + forEachPlot(value -> { + if (value.isOwnerAbs(uuid)) { + plots.add(value); } }); return Collections.unmodifiableSet(plots); } public boolean hasPlot(final UUID uuid) { - for (final PlotArea area : plotAreaManager.getAllPlotAreas()) { - if (area.hasPlot(uuid)) - return true; - } - return false; + return Arrays.stream(plotAreaManager.getAllPlotAreas()) + .anyMatch(area -> area.hasPlot(uuid)); } public Set getBasePlots(final UUID uuid) { final Set plots = new HashSet<>(); - foreachBasePlot(new RunnableVal() { - @Override public void run(Plot value) { - if (value.isOwner(uuid)) { - plots.add(value); - } + forEachBasePlot(value -> { + if (value.isOwner(uuid)) { + plots.add(value); } }); return Collections.unmodifiableSet(plots); } /** - * Get the plots for a UUID. + * Gets the plots for a UUID. * * @param uuid the UUID of the owner * @return Set of Plot */ public Set getPlotsAbs(final UUID uuid) { final Set plots = new HashSet<>(); - foreachPlot(new RunnableVal() { - @Override public void run(Plot value) { - if (value.isOwnerAbs(uuid)) { - plots.add(value); - } + forEachPlot(value -> { + if (value.isOwnerAbs(uuid)) { + plots.add(value); } }); return Collections.unmodifiableSet(plots); } /** - * Unregister a plot from local memory (does not call DB). + * Unregisters a plot from local memory without calling the database. * * @param plot the plot to remove * @param callEvent If to call an event about the plot being removed @@ -1154,12 +1086,13 @@ import java.util.zip.ZipInputStream; } // Conventional plot generator PlotArea plotArea = plotGenerator.getNewPlotArea(world, null, null, null); - PlotManager plotManager = plotGenerator.getNewPlotManager(); - 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()); + PlotManager plotManager = plotArea.getPlotManager(); + PlotSquared.log(Captions.PREFIX + "&aDetected world load for '" + world + "'"); PlotSquared - .log(C.PREFIX + "&3 - plotAreaManager: &7" + plotManager.getClass().getName()); + .log(Captions.PREFIX + "&3 - generator: &7" + baseGenerator + ">" + plotGenerator); + PlotSquared.log(Captions.PREFIX + "&3 - plotworld: &7" + plotArea.getClass().getName()); + PlotSquared.log( + Captions.PREFIX + "&3 - plotAreaManager: &7" + plotManager.getClass().getName()); if (!this.worlds.contains(path)) { this.worlds.createSection(path); worldSection = this.worlds.getConfigurationSection(path); @@ -1184,12 +1117,11 @@ import java.util.zip.ZipInputStream; debug("World possibly already loaded: " + world); return; } - PlotSquared.log(C.PREFIX + "&aDetected world load for '" + world + "'"); + PlotSquared.log(Captions.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); } @@ -1202,7 +1134,7 @@ import java.util.zip.ZipInputStream; worldSection.createSection("areas." + fullId); DBFunc.replaceWorld(world, world + ";" + name, pos1, pos2); // NPE - PlotSquared.log(C.PREFIX + "&3 - " + name + "-" + pos1 + "-" + pos2); + PlotSquared.log(Captions.PREFIX + "&3 - " + name + "-" + pos1 + "-" + pos2); GeneratorWrapper areaGen = this.IMP.getGenerator(world, gen_string); if (areaGen == null) { throw new IllegalArgumentException("Invalid Generator: " + gen_string); @@ -1216,12 +1148,14 @@ import java.util.zip.ZipInputStream; } catch (IOException e) { e.printStackTrace(); } - 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?)"); + PlotSquared.log( + Captions.PREFIX + "&c | &9generator: &7" + baseGenerator + ">" + + areaGen); + PlotSquared.log(Captions.PREFIX + "&c | &9plotworld: &7" + pa); + PlotSquared.log(Captions.PREFIX + "&c | &9manager: &7" + pa); + PlotSquared.log( + Captions.PREFIX + "&cNote: &7Area created for cluster:" + name + + " (invalid or old configuration?)"); areaGen.getPlotGenerator().initialize(pa); areaGen.augment(pa); toLoad.add(pa); @@ -1243,9 +1177,10 @@ import java.util.zip.ZipInputStream; } catch (IOException e) { e.printStackTrace(); } - 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()); + PlotSquared + .log(Captions.PREFIX + "&3 - generator: &7" + baseGenerator + ">" + areaGen); + PlotSquared.log(Captions.PREFIX + "&3 - plotworld: &7" + pa); + PlotSquared.log(Captions.PREFIX + "&3 - plotAreaManager: &7" + pa.getPlotManager()); areaGen.getPlotGenerator().initialize(pa); areaGen.augment(pa); addPlotArea(pa); @@ -1256,7 +1191,7 @@ import java.util.zip.ZipInputStream; "Invalid type for multi-area world. Expected `2`, got `" + 1 + "`"); } for (String areaId : areasSection.getKeys(false)) { - PlotSquared.log(C.PREFIX + "&3 - " + areaId); + PlotSquared.log(Captions.PREFIX + "&3 - " + areaId); String[] split = areaId.split("(?<=[^;-])-"); if (split.length != 3) { throw new IllegalArgumentException("Invalid Area identifier: " + areaId @@ -1265,7 +1200,7 @@ import java.util.zip.ZipInputStream; String name = split[0]; PlotId pos1 = PlotId.fromString(split[1]); PlotId pos2 = PlotId.fromString(split[2]); - if (pos1 == null || pos2 == null || name.isEmpty()) { + if (name.isEmpty()) { throw new IllegalArgumentException("Invalid Area identifier: " + areaId + ". Expected form `--`"); } @@ -1318,10 +1253,11 @@ import java.util.zip.ZipInputStream; } catch (IOException e) { e.printStackTrace(); } - 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()); + PlotSquared.log(Captions.PREFIX + "&aDetected area load for '" + world + "'"); + PlotSquared + .log(Captions.PREFIX + "&c | &9generator: &7" + baseGenerator + ">" + areaGen); + PlotSquared.log(Captions.PREFIX + "&c | &9plotworld: &7" + pa); + PlotSquared.log(Captions.PREFIX + "&c | &9manager: &7" + pa.getPlotManager()); areaGen.getPlotGenerator().initialize(pa); areaGen.augment(pa); addPlotArea(pa); @@ -1349,12 +1285,9 @@ import java.util.zip.ZipInputStream; "w=", "wall=", "b=", "border="); // Calculate the number of expected arguments - int expected = 0; - for (final String validArgument : validArguments) { - if (args.toLowerCase(Locale.ENGLISH).contains(validArgument)) { - expected += 1; - } - } + int expected = (int) validArguments.stream() + .filter(validArgument -> args.toLowerCase(Locale.ENGLISH).contains(validArgument)) + .count(); String[] split = args.toLowerCase(Locale.ENGLISH).split(","); @@ -1398,8 +1331,8 @@ import java.util.zip.ZipInputStream; } String key = pair[0].toLowerCase(); String value = pair[1]; - String base = "worlds." + world + "."; try { + String base = "worlds." + world + "."; switch (key) { case "s": case "size": @@ -1454,7 +1387,7 @@ import java.util.zip.ZipInputStream; ConfigurationSection section = this.worlds.getConfigurationSection("worlds." + world); plotworld.saveConfiguration(section); - plotworld.loadConfiguration(section); + plotworld.loadDefaultConfiguration(section); this.worlds.save(this.worldsFile); } catch (IOException e) { e.printStackTrace(); @@ -1471,20 +1404,16 @@ import java.util.zip.ZipInputStream; 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(); + return Arrays.stream(split).map(s -> String.format("%4s", s)).collect(Collectors.joining()); } - public boolean update(PlotPlayer sender, URL url) { + private boolean update(PlotPlayer sender, URL url) { try { String name = this.jarFile.getName(); - File newJar = new File("plugins/update/" + name); MainUtil.sendMessage(sender, "$1Downloading from provided URL: &7" + url); URLConnection con = url.openConnection(); try (InputStream stream = con.getInputStream()) { + File newJar = new File("plugins/update/" + name); File parent = newJar.getParentFile(); if (!parent.exists()) { parent.mkdirs(); @@ -1511,7 +1440,7 @@ import java.util.zip.ZipInputStream; } /** - * Copy a file from inside the jar to a location + * Copies a file from inside the jar to a location * * @param file Name of the file inside PlotSquared.jar * @param folder The output location relative to /plugins/PlotSquared/ @@ -1570,27 +1499,23 @@ import java.util.zip.ZipInputStream; for (PlotArea area : this.plotAreaManager.getAllPlotAreas()) { Map map2 = map.get(area.toString()); if (map2 == null) { - map.put(area.toString(), area.getPlotsRaw()); + map.put(area.toString(), area.getPlotsMap()); } else { - map2.putAll(area.getPlotsRaw()); + map2.putAll(area.getPlotsMap()); } } return map; } /** - * Close the database connection. + * Safely closes the database connection. */ public void disable() { try { // Validate that all data in the db is correct final HashSet plots = new HashSet<>(); try { - foreachPlotRaw(new RunnableVal() { - @Override public void run(Plot value) { - plots.add(value); - } - }); + forEachPlotRaw(plots::add); } catch (final Exception ignored) { } DBFunc.validatePlots(plots); @@ -1598,8 +1523,8 @@ import java.util.zip.ZipInputStream; // Close the connection DBFunc.close(); UUIDHandler.handleShutdown(); - } catch (NullPointerException ignored) { - ignored.printStackTrace(); + } catch (NullPointerException throwable) { + throwable.printStackTrace(); PlotSquared.log("&cCould not close database connection!"); } } @@ -1620,8 +1545,8 @@ import java.util.zip.ZipInputStream; File file = MainUtil.getFile(IMP.getDirectory(), Storage.SQLite.DB + ".db"); database = new SQLite(file); } else { - PlotSquared.log(C.PREFIX + "&cNo storage type is set!"); - this.IMP.disable(); + PlotSquared.log(Captions.PREFIX + "&cNo storage type is set!"); + this.IMP.shutdown(); //shutdown used instead of disable because no database is set return; } DBFunc.dbManager = new SQLManager(database, Storage.PREFIX, false); @@ -1638,8 +1563,8 @@ import java.util.zip.ZipInputStream; } this.clusters_tmp = DBFunc.getClusters(); } catch (ClassNotFoundException | SQLException e) { - PlotSquared.log( - C.PREFIX + "&cFailed to open DATABASE connection. The plugin will disable itself."); + PlotSquared.log(Captions.PREFIX + + "&cFailed to open DATABASE connection. The plugin will disable itself."); if (Storage.MySQL.USE) { PlotSquared.log("$4MYSQL"); } else if (Storage.SQLite.USE) { @@ -1651,7 +1576,7 @@ import java.util.zip.ZipInputStream; PlotSquared.log("&d==== End of stacktrace ===="); PlotSquared.log("&6Please go to the " + IMP.getPluginName() + " 'storage.yml' and configure the database correctly."); - this.IMP.disable(); + this.IMP.shutdown(); //shutdown used instead of disable because of database error } } @@ -1661,15 +1586,16 @@ import java.util.zip.ZipInputStream; * @throws IOException if the config failed to save */ public void setupConfig() throws IOException { - String lastVersionString = this.config.getString("version"); + String lastVersionString = this.getConfig().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)) { Settings.convertLegacy(configFile); - if (config.contains("worlds")) { - ConfigurationSection worldSection = config.getConfigurationSection("worlds"); + if (getConfig().contains("worlds")) { + ConfigurationSection worldSection = + getConfig().getConfigurationSection("worlds"); worlds.set("worlds", worldSection); try { worlds.save(worldsFile); @@ -1682,28 +1608,51 @@ import java.util.zip.ZipInputStream; } } Settings.load(configFile); - try { - InputStream stream = getClass().getResourceAsStream("/plugin.properties"); - BufferedReader br = new BufferedReader(new InputStreamReader(stream)); - //java.util.Scanner scanner = new java.util.Scanner(stream).useDelimiter("\\A"); - String versionString = br.readLine(); - String commitString = br.readLine(); - String dateString = br.readLine(); - //scanner.close(); - br.close(); - this.version = PlotVersion.tryParse(versionString, commitString, dateString); - 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); - System.out.println("Version is " + this.version); - } catch (Throwable ignore) { - ignore.printStackTrace(); + setupUpdateUtility(); + //Sets the version information for the settings.yml file + try (InputStream stream = getClass().getResourceAsStream("/plugin.properties")) { + try (BufferedReader br = new BufferedReader(new InputStreamReader(stream))) { + String versionString = br.readLine(); + String commitString = br.readLine(); + String dateString = br.readLine(); + this.version = PlotVersion.tryParse(versionString, commitString, dateString); + 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); + System.out.println("Version is " + this.version); + } + } catch (IOException throwable) { + throwable.printStackTrace(); } Settings.save(configFile); config = YamlConfiguration.loadConfiguration(configFile); } + private void setupUpdateUtility() { + try { + copyFile("updater.properties", "config"); + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader( + new FileInputStream(new File(new File(this.IMP.getDirectory(), "config"), + "updater.properties"))))) { + final Properties properties = new Properties(); + properties.load(bufferedReader); + final boolean enabled = + Boolean.valueOf(properties.getOrDefault("enabled", true).toString()); + if (enabled) { + this.updateUtility = new UpdateUtility(properties.getProperty("path"), + properties.getProperty("job"), properties.getProperty("artifact")); + } + } catch (final IOException throwable) { + throwable.printStackTrace(); + } + } catch (final Throwable throwable) { + throwable.printStackTrace(); + } + } + /** * Setup all configuration files
      * - Config: settings.yml
      @@ -1713,7 +1662,7 @@ import java.util.zip.ZipInputStream; public boolean setupConfigs() { File folder = new File(this.IMP.getDirectory(), "config"); if (!folder.exists() && !folder.mkdirs()) { - PlotSquared.log(C.PREFIX + PlotSquared.log(Captions.PREFIX + "&cFailed to create the /plugins/config folder. Please create it manually."); } try { @@ -1729,11 +1678,11 @@ import java.util.zip.ZipInputStream; .getString("configuration_version") .equalsIgnoreCase(LegacyConverter.CONFIGURATION_VERSION)) { // Conversion needed - log(C.LEGACY_CONFIG_FOUND.s()); + log(Captions.LEGACY_CONFIG_FOUND.s()); try { com.google.common.io.Files .copy(this.worldsFile, new File(folder, "worlds.yml.old")); - log(C.LEGACY_CONFIG_BACKUP.s()); + log(Captions.LEGACY_CONFIG_BACKUP.s()); final ConfigurationSection worlds = this.worlds.getConfigurationSection("worlds"); final LegacyConverter converter = new LegacyConverter(worlds); @@ -1742,9 +1691,9 @@ import java.util.zip.ZipInputStream; .set("configuration_version", LegacyConverter.CONFIGURATION_VERSION); this.worlds.set("worlds", worlds); // Redundant, but hey... ¯\_(ツ)_/¯ this.worlds.save(this.worldsFile); - log(C.LEGACY_CONFIG_DONE.s()); + log(Captions.LEGACY_CONFIG_DONE.s()); } catch (final Exception e) { - log(C.LEGACY_CONFIG_CONVERSION_FAILED.s()); + log(Captions.LEGACY_CONFIG_CONVERSION_FAILED.s()); e.printStackTrace(); } // Disable plugin @@ -1833,7 +1782,7 @@ import java.util.zip.ZipInputStream; if (Settings.DEBUG) { Map components = Settings.getFields(Settings.Enabled_Components.class); for (Entry component : components.entrySet()) { - PlotSquared.log(C.PREFIX + String + PlotSquared.log(Captions.PREFIX + String .format("&cKey: &6%s&c, Value: &6%s", component.getKey(), component.getValue())); } @@ -1860,51 +1809,50 @@ import java.util.zip.ZipInputStream; } /** - * Get the Java version. + * Gets the Java version. * * @return the java version */ - public double getJavaVersion() { + private double getJavaVersion() { return Double.parseDouble(System.getProperty("java.specification.version")); } - public void foreachPlotArea(@NonNull final RunnableVal runnable) { + public void forEachPlotArea(Consumer action) { for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) { - runnable.run(area); + action.accept(area); } } - public void foreachPlotArea(@NonNull final String world, - @NonNull final RunnableVal runnable) { + public void forEachPlotArea(@NonNull final String world, Consumer consumer) { final PlotArea[] array = this.plotAreaManager.getPlotAreas(world, null); if (array == null) { return; } for (final PlotArea area : array) { - runnable.run(area); + consumer.accept(area); } } - public void foreachPlot(@NonNull final RunnableVal runnable) { + public void forEachPlot(Consumer consumer) { for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) { - area.getPlots().forEach(runnable::run); + area.getPlots().forEach(consumer); } } - public void foreachPlotRaw(@NonNull final RunnableVal runnable) { + public void forEachPlotRaw(Consumer consumer) { for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) { - area.getPlots().forEach(runnable::run); + area.getPlots().forEach(consumer); } if (this.plots_tmp != null) { for (final HashMap entry : this.plots_tmp.values()) { - entry.values().forEach(runnable::run); + entry.values().forEach(consumer); } } } - public void foreachBasePlot(@NonNull final RunnableVal run) { + public void forEachBasePlot(Consumer consumer) { for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) { - area.foreachBasePlot(run); + area.forEachBasePlot(consumer); } } @@ -1918,11 +1866,8 @@ import java.util.zip.ZipInputStream; } public int getPlotCount() { - int count = 0; - for (final PlotArea area : this.plotAreaManager.getAllPlotAreas()) { - count += area.getPlotCount(); - } - return count; + return Arrays.stream(this.plotAreaManager.getAllPlotAreas()) + .mapToInt(PlotArea::getPlotCount).sum(); } public Set getPlotAreas() { @@ -1937,7 +1882,7 @@ import java.util.zip.ZipInputStream; } /** - * Get a list of PlotArea objects. + * Gets a list of PlotArea objects. * * @param world the world * @return Collection of PlotArea objects @@ -1949,7 +1894,7 @@ import java.util.zip.ZipInputStream; } /** - * Get the relevant plot area for a specified location. + * Gets 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. @@ -1970,7 +1915,7 @@ import java.util.zip.ZipInputStream; } /** - * Get the {@code PlotArea} which contains a location. + * Gets the {@code PlotArea} which contains a location. *
          *
        • If the plot area does not contain a location, null * will be returned. @@ -2012,11 +1957,11 @@ import java.util.zip.ZipInputStream; } /** - * Get Plots based on alias + * Gets Plots based on alias * * @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(@Nullable final String alias, @NonNull final String worldname) { @@ -2039,6 +1984,10 @@ import java.util.zip.ZipInputStream; return Collections.unmodifiableSet(set); } + public YamlConfiguration getConfig() { + return config; + } + public enum SortType { CREATION_DATE, CREATION_DATE_TIMESTAMP, LAST_MODIFIED, DISTANCE_FROM_ORIGIN } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotVersion.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotVersion.java index ecb423970..1d65c36e0 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotVersion.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/PlotVersion.java @@ -32,10 +32,9 @@ public class PlotVersion { @Override public String toString() { if (hash == 0 && build == 0) { - return "PlotSquared-" + year + "." + month + "." + day + "-SNAPSHOT"; + return "PlotSquared-NoVer-SNAPSHOT"; } else { - return "PlotSquared-" + year + "." + month + "." + day + "-" + Integer.toHexString(hash) - + "-" + build; + return "PlotSquared-4." + build; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Add.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Add.java index ed70d96d6..f6dba37a4 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Add.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Add.java @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; @@ -20,7 +20,7 @@ import java.util.concurrent.CompletableFuture; @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 { + requiredType = RequiredType.PLAYER) public class Add extends Command { public Add() { super(MainCommand.getInstance(), true); @@ -29,39 +29,41 @@ import java.util.concurrent.CompletableFuture; @Override public CompletableFuture 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); + final Plot plot = check(player.getCurrentPlot(), Captions.NOT_IN_PLOT); + checkTrue(plot.hasOwner(), Captions.PLOT_UNOWNED); 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()); + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_TRUST), + Captions.NO_PLOT_PERMS); + checkTrue(args.length == 1, Captions.COMMAND_SYNTAX, getUsage()); final Set uuids = MainUtil.getUUIDsFromString(args[0]); - checkTrue(!uuids.isEmpty(), C.INVALID_PLAYER, args[0]); - Iterator iter = uuids.iterator(); + checkTrue(!uuids.isEmpty(), Captions.INVALID_PLAYER, args[0]); + Iterator iterator = uuids.iterator(); int size = plot.getTrusted().size() + plot.getMembers().size(); - while (iter.hasNext()) { - UUID uuid = iter.next(); + while (iterator.hasNext()) { + UUID uuid = iterator.next(); 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(); + Permissions.hasPermission(player, Captions.PERMISSION_TRUST_EVERYONE) || Permissions + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_TRUST))) { + MainUtil.sendMessage(player, Captions.INVALID_PLAYER, MainUtil.getName(uuid)); + iterator.remove(); continue; } if (plot.isOwner(uuid)) { - MainUtil.sendMessage(player, C.ALREADY_OWNER, MainUtil.getName(uuid)); - iter.remove(); + MainUtil.sendMessage(player, Captions.ALREADY_OWNER, MainUtil.getName(uuid)); + iterator.remove(); continue; } if (plot.getMembers().contains(uuid)) { - MainUtil.sendMessage(player, C.ALREADY_ADDED, MainUtil.getName(uuid)); - iter.remove(); + MainUtil.sendMessage(player, Captions.ALREADY_ADDED, MainUtil.getName(uuid)); + iterator.remove(); continue; } 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); + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_TRUST), + Captions.PLOT_MAX_MEMBERS); // Success confirm.run(this, () -> { for (UUID uuid : uuids) { @@ -74,7 +76,7 @@ import java.util.concurrent.CompletableFuture; } plot.addMember(uuid); EventUtil.manager.callMember(player, plot, uuid, true); - MainUtil.sendMessage(player, C.MEMBER_ADDED); + MainUtil.sendMessage(player, Captions.MEMBER_ADDED); } }, null); 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 index 2eeb0a49d..8e0847f57 100644 --- 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 @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; @@ -15,29 +15,29 @@ 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 + category = CommandCategory.SETTINGS, requiredType = RequiredType.PLAYER) public class Alias extends SubCommand { @Override public boolean onCommand(PlotPlayer player, String[] args) { if (args.length == 0) { - C.COMMAND_SYNTAX.send(player, "/plot alias "); + Captions.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); + return !sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot.hasOwner()) { - sendMessage(player, C.PLOT_NOT_CLAIMED); + sendMessage(player, Captions.PLOT_NOT_CLAIMED); return false; } if (!plot.isOwner(player.getUUID())) { - MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } @@ -46,25 +46,25 @@ import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; switch (args[0].toLowerCase()) { case "set": if (args.length != 2) { - C.COMMAND_SYNTAX.send(player, "/plot alias "); + Captions.COMMAND_SYNTAX.send(player, "/plot alias "); return false; } - if (canExecuteCommand(player, C.PERMISSION_ALIAS_SET, false) || canExecuteCommand( - player, C.PERMISSION_ALIAS_SET_OBSOLETE, false)) { + if (canExecuteCommand(player, Captions.PERMISSION_ALIAS_SET, false) + || canExecuteCommand(player, Captions.PERMISSION_ALIAS_SET_OBSOLETE, false)) { result = setAlias(player, plot, args[1]); } else { - MainUtil.sendMessage(player, C.NO_PERMISSION); + MainUtil.sendMessage(player, Captions.NO_PERMISSION); } break; case "remove": - if (canExecuteCommand(player, C.PERMISSION_ALIAS_REMOVE, true)) { + if (canExecuteCommand(player, Captions.PERMISSION_ALIAS_REMOVE, true)) { result = removeAlias(player, plot); } break; default: - C.COMMAND_SYNTAX.send(player, "/plot alias "); + Captions.COMMAND_SYNTAX.send(player, "/plot alias "); result = false; } @@ -74,47 +74,47 @@ import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; private boolean setAlias(PlotPlayer player, Plot plot, String alias) { if (alias.isEmpty()) { - C.COMMAND_SYNTAX.send(player, "/plot alias "); + Captions.COMMAND_SYNTAX.send(player, "/plot alias "); return false; } if (alias.length() >= 50) { - MainUtil.sendMessage(player, C.ALIAS_TOO_LONG); + MainUtil.sendMessage(player, Captions.ALIAS_TOO_LONG); return false; } if (alias.contains(" ")) { - C.NOT_VALID_VALUE.send(player); + Captions.NOT_VALID_VALUE.send(player); return false; } if (MathMan.isInteger(alias)) { - C.NOT_VALID_VALUE.send(player); + Captions.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); + MainUtil.sendMessage(player, Captions.ALIAS_IS_TAKEN); return false; } } if (UUIDHandler.nameExists(new StringWrapper(alias)) || PlotSquared.get() .hasPlotArea(alias)) { - MainUtil.sendMessage(player, C.ALIAS_IS_TAKEN); + MainUtil.sendMessage(player, Captions.ALIAS_IS_TAKEN); return false; } plot.setAlias(alias); - MainUtil.sendMessage(player, C.ALIAS_SET_TO.s().replaceAll("%alias%", alias)); + MainUtil.sendMessage(player, Captions.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()); + MainUtil.sendMessage(player, Captions.ALIAS_REMOVED.s()); return true; } - private boolean canExecuteCommand(PlotPlayer player, C caption, boolean sendMessage) { + private boolean canExecuteCommand(PlotPlayer player, Captions caption, boolean sendMessage) { if (!Permissions.hasPermission(player, caption)) { if (sendMessage) { - MainUtil.sendMessage(player, C.NO_PERMISSION); + MainUtil.sendMessage(player, Captions.NO_PERMISSION); } return false; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Area.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Area.java index 9dc5ce20e..ed6a4a3dc 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Area.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Area.java @@ -3,7 +3,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.Configuration; import com.github.intellectualsites.plotsquared.plot.generator.AugmentedUtils; import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld; @@ -23,20 +23,20 @@ import java.util.Set; @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length == 0) { - C.COMMAND_SYNTAX.send(player, getUsage()); + Captions.COMMAND_SYNTAX.send(player, getUsage()); return false; } switch (args[0].toLowerCase()) { case "c": case "setup": case "create": - if (!Permissions.hasPermission(player, C.PERMISSION_AREA_CREATE)) { - C.NO_PERMISSION.send(player, C.PERMISSION_AREA_CREATE); + if (!Permissions.hasPermission(player, Captions.PERMISSION_AREA_CREATE)) { + Captions.NO_PERMISSION.send(player, Captions.PERMISSION_AREA_CREATE); return false; } switch (args.length) { case 1: - C.COMMAND_SYNTAX + Captions.COMMAND_SYNTAX .send(player, "/plot area create [world[:id]] [=]..."); return false; case 2: @@ -44,13 +44,13 @@ import java.util.Set; case "pos1": { // Set position 1 HybridPlotWorld area = player.getMeta("area_create_area"); if (area == null) { - C.COMMAND_SYNTAX.send(player, + Captions.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", + Captions.SET_ATTRIBUTE.send(player, "area_pos1", location.getX() + "," + location.getZ()); MainUtil.sendMessage(player, "You will now set pos2: /plot area create pos2" @@ -60,7 +60,7 @@ import java.util.Set; 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, + Captions.COMMAND_SYNTAX.send(player, "/plot area create [world[:id]] [=]..."); return false; } @@ -87,7 +87,7 @@ import java.util.Set; Set areas = PlotSquared.get().getPlotAreas(area.worldname, region); if (!areas.isEmpty()) { - C.CLUSTER_INTERSECTION + Captions.CLUSTER_INTERSECTION .send(player, areas.iterator().next().toString()); return false; } @@ -104,36 +104,34 @@ import java.util.Set; final String path = "worlds." + area.worldname + ".areas." + area.id + '-' + object.min + '-' + object.max; - Runnable run = new Runnable() { - @Override public void run() { - if (offsetX != 0) { - PlotSquared.get().worlds - .set(path + ".road.offset.x", offsetX); - } - if (offsetZ != 0) { - PlotSquared.get().worlds - .set(path + ".road.offset.z", offsetZ); - } - final String world = SetupUtils.manager.setupWorld(object); - if (WorldUtil.IMP.isWorld(world)) { - 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); - } - } else { - MainUtil.sendMessage(player, - "An error occurred while creating the world: " - + area.worldname); + Runnable run = () -> { + if (offsetX != 0) { + PlotSquared.get().worlds + .set(path + ".road.offset.x", offsetX); + } + if (offsetZ != 0) { + PlotSquared.get().worlds + .set(path + ".road.offset.z", offsetZ); + } + final String world = SetupUtils.manager.setupWorld(object); + if (WorldUtil.IMP.isWorld(world)) { + PlotSquared.get().loadWorld(world, null); + Captions.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); } + } else { + MainUtil.sendMessage(player, + "An error occurred while creating the world: " + + area.worldname); } }; if (hasConfirmation(player)) { @@ -145,7 +143,6 @@ import java.util.Set; return true; } default: // Start creation - final SetupObject object = new SetupObject(); String[] split = args[1].split(":"); String id; if (split.length == 2) { @@ -153,12 +150,13 @@ import java.util.Set; } else { id = null; } + final SetupObject object = new SetupObject(); object.world = split[0]; 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()); + Captions.SETUP_WORLD_TAKEN.send(player, pa.toString()); return false; } Set areas = PlotSquared.get().getPlotAreas(pa.worldname); @@ -170,7 +168,7 @@ import java.util.Set; for (int i = 2; i < args.length; i++) { String[] pair = args[i].split("="); if (pair.length != 2) { - C.COMMAND_SYNTAX.send(player, getCommandString() + Captions.COMMAND_SYNTAX.send(player, getCommandString() + " create [world[:id]] [=]..."); return false; } @@ -218,42 +216,40 @@ import java.util.Set; object.type = pa.TYPE; break; default: - C.COMMAND_SYNTAX.send(player, getCommandString() + Captions.COMMAND_SYNTAX.send(player, getCommandString() + " create [world[:id]] [=]..."); return false; } } if (pa.TYPE != 2) { if (WorldUtil.IMP.isWorld(pa.worldname)) { - C.SETUP_WORLD_TAKEN.send(player, pa.worldname); + Captions.SETUP_WORLD_TAKEN.send(player, pa.worldname); return false; } - Runnable run = new Runnable() { - @Override public void run() { - String path = "worlds." + pa.worldname; - if (!PlotSquared.get().worlds.contains(path)) { - PlotSquared.get().worlds.createSection(path); - } - ConfigurationSection section = - PlotSquared.get().worlds.getConfigurationSection(path); - pa.saveConfiguration(section); - pa.loadConfiguration(section); - 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); - } - try { - PlotSquared.get().worlds.save(PlotSquared.get().worldsFile); - } catch (IOException e) { - e.printStackTrace(); - } + Runnable run = () -> { + String path = "worlds." + pa.worldname; + if (!PlotSquared.get().worlds.contains(path)) { + PlotSquared.get().worlds.createSection(path); + } + ConfigurationSection section = + PlotSquared.get().worlds.getConfigurationSection(path); + pa.saveConfiguration(section); + pa.loadConfiguration(section); + object.plotManager = PlotSquared.imp().getPluginName(); + object.setupGenerator = PlotSquared.imp().getPluginName(); + String world = SetupUtils.manager.setupWorld(object); + if (WorldUtil.IMP.isWorld(world)) { + Captions.SETUP_FINISHED.send(player); + player.teleport(WorldUtil.IMP.getSpawn(world)); + } else { + MainUtil.sendMessage(player, + "An error occurred while creating the world: " + + pa.worldname); + } + try { + PlotSquared.get().worlds.save(PlotSquared.get().worldsFile); + } catch (IOException e) { + e.printStackTrace(); } }; if (hasConfirmation(player)) { @@ -265,7 +261,7 @@ import java.util.Set; return true; } if (pa.id == null) { - C.COMMAND_SYNTAX.send(player, getCommandString() + Captions.COMMAND_SYNTAX.send(player, getCommandString() + " create [world[:id]] [=]..."); return false; } @@ -288,8 +284,8 @@ import java.util.Set; return true; case "i": case "info": { - if (!Permissions.hasPermission(player, C.PERMISSION_AREA_INFO)) { - C.NO_PERMISSION.send(player, C.PERMISSION_AREA_INFO); + if (!Permissions.hasPermission(player, Captions.PERMISSION_AREA_INFO)) { + Captions.NO_PERMISSION.send(player, Captions.PERMISSION_AREA_INFO); return false; } PlotArea area; @@ -301,14 +297,14 @@ import java.util.Set; area = PlotSquared.get().getPlotAreaByString(args[1]); break; default: - C.COMMAND_SYNTAX.send(player, getCommandString() + " info [area]"); + Captions.COMMAND_SYNTAX.send(player, getCommandString() + " info [area]"); return false; } if (area == null) { if (args.length == 2) { - C.NOT_VALID_PLOT_WORLD.send(player, args[1]); + Captions.NOT_VALID_PLOT_WORLD.send(player, args[1]); } else { - C.NOT_IN_PLOT_WORLD.send(player); + Captions.NOT_IN_PLOT_WORLD.send(player); } return false; } @@ -335,13 +331,14 @@ import java.util.Set; + "\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); + Captions.PLOT_INFO_HEADER.s() + '\n' + value + '\n' + Captions.PLOT_INFO_FOOTER + .s(), false); return true; } case "l": case "list": - if (!Permissions.hasPermission(player, C.PERMISSION_AREA_LIST)) { - C.NO_PERMISSION.send(player, C.PERMISSION_AREA_LIST); + if (!Permissions.hasPermission(player, Captions.PERMISSION_AREA_LIST)) { + Captions.NO_PERMISSION.send(player, Captions.PERMISSION_AREA_LIST); return false; } int page; @@ -355,7 +352,7 @@ import java.util.Set; break; } default: - C.COMMAND_SYNTAX.send(player, getCommandString() + " list [#]"); + Captions.COMMAND_SYNTAX.send(player, getCommandString() + " list [#]"); return false; } ArrayList areas = new ArrayList<>(PlotSquared.get().getPlotAreas()); @@ -397,19 +394,19 @@ import java.util.Set; .color("$1").text(" - ").color("$2") .text(area.TYPE + ":" + area.TERRAIN).color("$3"); } - }, "/plot area list", C.AREA_LIST_HEADER_PAGED.s()); + }, "/plot area list", Captions.AREA_LIST_HEADER_PAGED.s()); return true; case "regen": case "clear": case "reset": case "regenerate": { - if (!Permissions.hasPermission(player, C.PERMISSION_AREA_REGEN)) { - C.NO_PERMISSION.send(player, C.PERMISSION_AREA_REGEN); + if (!Permissions.hasPermission(player, Captions.PERMISSION_AREA_REGEN)) { + Captions.NO_PERMISSION.send(player, Captions.PERMISSION_AREA_REGEN); return false; } final PlotArea area = player.getApplicablePlotArea(); if (area == null) { - C.NOT_IN_PLOT_WORLD.send(player); + Captions.NOT_IN_PLOT_WORLD.send(player); return false; } if (area.TYPE != 2) { @@ -422,11 +419,7 @@ import java.util.Set; @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"); - } - }); + }, () -> player.sendMessage("Regen complete")); return true; } case "goto": @@ -434,17 +427,17 @@ import java.util.Set; case "teleport": case "visit": case "tp": - if (!Permissions.hasPermission(player, C.PERMISSION_AREA_TP)) { - C.NO_PERMISSION.send(player, C.PERMISSION_AREA_TP); + if (!Permissions.hasPermission(player, Captions.PERMISSION_AREA_TP)) { + Captions.NO_PERMISSION.send(player, Captions.PERMISSION_AREA_TP); return false; } if (args.length != 2) { - C.COMMAND_SYNTAX.send(player, "/plot visit [area]"); + Captions.COMMAND_SYNTAX.send(player, "/plot visit [area]"); return false; } PlotArea area = PlotSquared.get().getPlotAreaByString(args[1]); if (area == null) { - C.NOT_VALID_PLOT_WORLD.send(player, args[1]); + Captions.NOT_VALID_PLOT_WORLD.send(player, args[1]); return false; } Location center; @@ -470,7 +463,7 @@ import java.util.Set; + "\n$1Stop the server and delete it from these locations."); return true; } - C.COMMAND_SYNTAX.send(player, getUsage()); + Captions.COMMAND_SYNTAX.send(player, getUsage()); return false; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Auto.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Auto.java index 33048e0fd..fa187877e 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Auto.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Auto.java @@ -2,11 +2,20 @@ 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.Captions; 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 com.github.intellectualsites.plotsquared.plot.object.Expression; +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.RunnableVal; +import com.github.intellectualsites.plotsquared.plot.util.ByteArrayUtilities; +import com.github.intellectualsites.plotsquared.plot.util.EconHandler; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; import javax.annotation.Nullable; import java.util.Set; @@ -21,36 +30,41 @@ public class Auto extends SubCommand { } 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) { + @Nullable Integer allowedPlots, int sizeX, int sizeZ) { + if (allowedPlots == null) { + allowedPlots = player.getAllowedPlots(); + } + int currentPlots; + if (Settings.Limit.GLOBAL) { + currentPlots = player.getPlotCount(); + } else { + currentPlots = player.getPlotCount(plotarea.worldname); + } + int diff = currentPlots - allowedPlots; + if (diff + sizeX * sizeZ > 0) { if (diff < 0) { - MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS_NUM, -diff + ""); + MainUtil.sendMessage(player, Captions.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) { + if (grantedPlots - diff < sizeX * sizeZ) { player.removePersistentMeta("grantedPlots"); - MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS); + MainUtil.sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS); return false; } else { - int left = grantedPlots - diff - size_x * size_z; + int left = grantedPlots - diff - sizeX * sizeZ; if (left == 0) { player.removePersistentMeta("grantedPlots"); } else { player.setPersistentMeta("grantedPlots", ByteArrayUtilities.integerToBytes(left)); } - MainUtil.sendMessage(player, C.REMOVED_GRANTED_PLOT, "" + left, + MainUtil.sendMessage(player, Captions.REMOVED_GRANTED_PLOT, "" + left, "" + (grantedPlots - left)); } } else { - MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS); + MainUtil.sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS); return false; } } @@ -63,15 +77,15 @@ public class Auto extends SubCommand { * @param player * @param area * @param start - * @param schem + * @param schematic */ public static void homeOrAuto(final PlotPlayer player, final PlotArea area, PlotId start, - final String schem) { + final String schematic) { Set plots = player.getPlots(); if (!plots.isEmpty()) { plots.iterator().next().teleportPlayer(player); } else { - autoClaimSafe(player, area, start, schem); + autoClaimSafe(player, area, start, schematic); } } @@ -81,11 +95,11 @@ public class Auto extends SubCommand { * @param player * @param area * @param start - * @param schem + * @param schematic */ public static void autoClaimSafe(final PlotPlayer player, final PlotArea area, PlotId start, - final String schem) { - autoClaimSafe(player, area, start, schem, null); + final String schematic) { + autoClaimSafe(player, area, start, schematic, null); } /** @@ -94,10 +108,10 @@ public class Auto extends SubCommand { * @param player * @param area * @param start - * @param schem + * @param schematic */ public static void autoClaimSafe(final PlotPlayer player, final PlotArea area, PlotId start, - final String schem, @Nullable final Integer allowed_plots) { + final String schematic, @Nullable final Integer allowedPlots) { player.setMeta(Auto.class.getName(), true); autoClaimFromDatabase(player, area, start, new RunnableVal() { @Override public void run(final Plot plot) { @@ -105,9 +119,9 @@ public class Auto extends SubCommand { @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); + MainUtil.sendMessage(player, Captions.NO_FREE_PLOTS); + } else if (checkAllowedPlots(player, area, allowedPlots, 1, 1)) { + plot.claim(player, true, schematic, false); if (area.AUTO_MERGE) { plot.autoMerge(-1, Integer.MAX_VALUE, player.getUUID(), true); } @@ -129,11 +143,8 @@ public class Auto extends SubCommand { } whenDone.value = plot; plot.owner = player.getUUID(); - DBFunc.createPlotSafe(plot, whenDone, new Runnable() { - @Override public void run() { - autoClaimFromDatabase(player, area, plot.getId(), whenDone); - } - }); + DBFunc.createPlotSafe(plot, whenDone, + () -> autoClaimFromDatabase(player, area, plot.getId(), whenDone)); } @Override public boolean onCommand(final PlotPlayer player, String[] args) { @@ -152,7 +163,7 @@ public class Auto extends SubCommand { } } if (plotarea == null) { - MainUtil.sendMessage(player, C.NOT_IN_PLOT_WORLD); + MainUtil.sendMessage(player, Captions.NOT_IN_PLOT_WORLD); return false; } } @@ -160,7 +171,7 @@ public class Auto extends SubCommand { int size_z = 1; String schematic = null; if (args.length > 0) { - if (Permissions.hasPermission(player, C.PERMISSION_AUTO_MEGA)) { + if (Permissions.hasPermission(player, Captions.PERMISSION_AUTO_MEGA)) { try { String[] split = args[0].split(",|;"); size_x = Integer.parseInt(split[0]); @@ -181,29 +192,31 @@ public class Auto extends SubCommand { } } else { schematic = args[0]; - // PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); + // PlayerFunctions.sendMessage(plr, Captions.NO_PERMISSION); // return false; } } if (size_x * size_z > Settings.Claim.MAX_AUTO_AREA) { - MainUtil.sendMessage(player, C.CANT_CLAIM_MORE_PLOTS_NUM, + MainUtil.sendMessage(player, Captions.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)) + 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); + sendMessage(player, Captions.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, Captions.PERMISSION_CLAIM_SCHEMATIC.f(schematic)) + && !Permissions + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_SCHEMATIC)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLAIM_SCHEMATIC.f(schematic)); return true; } } @@ -215,11 +228,11 @@ public class Auto extends SubCommand { cost = (size_x * size_z) * cost; if (cost > 0d) { if (EconHandler.manager.getMoney(player) < cost) { - sendMessage(player, C.CANNOT_AFFORD_PLOT, "" + cost); + sendMessage(player, Captions.CANNOT_AFFORD_PLOT, "" + cost); return true; } EconHandler.manager.withdrawMoney(player, cost); - sendMessage(player, C.REMOVED_BALANCE, cost + ""); + sendMessage(player, Captions.REMOVED_BALANCE, cost + ""); } } // TODO handle type 2 the same as normal worlds! @@ -228,7 +241,7 @@ public class Auto extends SubCommand { return true; } else { if (plotarea.TYPE == 2) { - MainUtil.sendMessage(player, C.NO_FREE_PLOTS); + MainUtil.sendMessage(player, Captions.NO_FREE_PLOTS); return false; } while (true) { @@ -243,8 +256,7 @@ public class Auto extends SubCommand { plot.claim(player, teleport, null); } } - if (!plotarea - .mergePlots(MainUtil.getPlotSelectionIds(start, end), true)) { + if (!plotarea.mergePlots(MainUtil.getPlotSelectionIds(start, end), true)) { return false; } break; 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 index 82a573949..b40167b4c 100644 --- 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 @@ -1,7 +1,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; @@ -17,21 +17,19 @@ import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; 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); + StringMan.join(WorldUtil.IMP.getBiomeList(), Captions.BLOCK_LIST_SEPARATER.s()); + Captions.NEED_BIOME.send(player); + MainUtil.sendMessage(player, Captions.SUBCOMMAND_SET_OPTIONS_HEADER.s() + biomes); return false; } if (plot.getRunning() > 0) { - MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); + MainUtil.sendMessage(player, Captions.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()); - } + plot.setBiome(value.toUpperCase(), () -> { + plot.removeRunning(); + MainUtil.sendMessage(player, Captions.BIOME_SET_TO.s() + value.toLowerCase()); }); return true; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Buy.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Buy.java index 5c6a88b93..dbfd37768 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Buy.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Buy.java @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; @@ -27,39 +27,40 @@ import java.util.concurrent.CompletableFuture; @Override public CompletableFuture execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, final RunnableVal2 whenDone) { - check(EconHandler.manager, C.ECON_DISABLED); + + check(EconHandler.manager, Captions.ECON_DISABLED); final Plot plot; if (args.length != 0) { - checkTrue(args.length == 1, C.COMMAND_SYNTAX, getUsage()); + checkTrue(args.length == 1, Captions.COMMAND_SYNTAX, getUsage()); plot = check(MainUtil.getPlotFromString(player, args[0], true), null); } else { - plot = check(player.getCurrentPlot(), C.NOT_IN_PLOT); + plot = check(player.getCurrentPlot(), Captions.NOT_IN_PLOT); } - checkTrue(plot.hasOwner(), C.PLOT_UNOWNED); - checkTrue(!plot.isOwner(player.getUUID()), C.CANNOT_BUY_OWN); + checkTrue(plot.hasOwner(), Captions.PLOT_UNOWNED); + checkTrue(!plot.isOwner(player.getUUID()), Captions.CANNOT_BUY_OWN); Set plots = plot.getConnectedPlots(); checkTrue(player.getPlotCount() + plots.size() <= player.getAllowedPlots(), - C.CANT_CLAIM_MORE_PLOTS); + Captions.CANT_CLAIM_MORE_PLOTS); Optional flag = plot.getFlag(Flags.PRICE); if (!flag.isPresent()) { - throw new CommandException(C.NOT_FOR_SALE); + throw new CommandException(Captions.NOT_FOR_SALE); } final double price = flag.get(); - checkTrue(player.getMoney() >= price, C.CANNOT_AFFORD_PLOT); + checkTrue(player.getMoney() >= price, Captions.CANNOT_AFFORD_PLOT); player.withdraw(price); // Failure // Success confirm.run(this, () -> { - C.REMOVED_BALANCE.send(player, price); + Captions.REMOVED_BALANCE.send(player, 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); + Captions.PLOT_SOLD.send(owner, plot.getId(), player.getName(), price); } plot.removeFlag(Flags.PRICE); plot.setOwner(player.getUUID()); - C.CLAIMED.send(player); + Captions.CLAIMED.send(player); whenDone.run(Buy.this, CommandResult.SUCCESS); }, () -> { player.deposit(price); 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 index 453a6a8ac..c2a3daf84 100644 --- 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 @@ -5,7 +5,7 @@ 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 { + requiredType = RequiredType.PLAYER) public class Chat extends SubCommand { @Override public boolean onCommand(PlotPlayer player, String[] args) { MainCommand.getInstance().toggle.chat(this, player, new String[0], null, null); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Claim.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Claim.java index 88f102967..b06e0b57b 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Claim.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Claim.java @@ -1,7 +1,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.object.*; @@ -23,7 +23,7 @@ public class Claim extends SubCommand { Location loc = player.getLocation(); final Plot plot = loc.getPlotAbs(); if (plot == null) { - return sendMessage(player, C.NOT_IN_PLOT); + return sendMessage(player, Captions.NOT_IN_PLOT); } int currentPlots = Settings.Limit.GLOBAL ? player.getPlotCount() : player.getPlotCount(loc.getWorld()); @@ -34,40 +34,43 @@ public class Claim extends SubCommand { ByteArrayUtilities.bytesToInteger(player.getPersistentMeta("grantedPlots")); if (grants <= 0) { player.removePersistentMeta("grantedPlots"); - return sendMessage(player, C.CANT_CLAIM_MORE_PLOTS); + return sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS); } } else { - return sendMessage(player, C.CANT_CLAIM_MORE_PLOTS); + return sendMessage(player, Captions.CANT_CLAIM_MORE_PLOTS); } } if (!plot.canClaim(player)) { - return sendMessage(player, C.PLOT_IS_CLAIMED); + return sendMessage(player, Captions.PLOT_IS_CLAIMED); } final PlotArea area = plot.getArea(); if (!schematic.isEmpty()) { if (area.SCHEMATIC_CLAIM_SPECIFY) { if (!area.SCHEMATICS.contains(schematic.toLowerCase())) { - return sendMessage(player, C.SCHEMATIC_INVALID, "non-existent: " + schematic); + return sendMessage(player, Captions.SCHEMATIC_INVALID, + "non-existent: " + 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); + if (!Permissions + .hasPermission(player, Captions.PERMISSION_CLAIM_SCHEMATIC.f(schematic)) + && !Permissions + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_SCHEMATIC)) { + return sendMessage(player, Captions.NO_SCHEMATIC_PERMISSION, schematic); } } } int border = area.getBorder(); if (border != Integer.MAX_VALUE && plot.getDistanceFromOrigin() > border) { - return !sendMessage(player, C.BORDER); + return !sendMessage(player, Captions.BORDER); } if ((EconHandler.manager != null) && area.USE_ECONOMY) { Expression costExr = area.PRICES.get("claim"); double cost = costExr.evaluate((double) currentPlots); if (cost > 0d) { if (EconHandler.manager.getMoney(player) < cost) { - return sendMessage(player, C.CANNOT_AFFORD_PLOT, "" + cost); + return sendMessage(player, Captions.CANNOT_AFFORD_PLOT, "" + cost); } EconHandler.manager.withdrawMoney(player, cost); - sendMessage(player, C.REMOVED_BALANCE, cost + ""); + sendMessage(player, Captions.REMOVED_BALANCE, cost + ""); } } if (grants > 0) { @@ -77,30 +80,22 @@ public class Claim extends SubCommand { player.setPersistentMeta("grantedPlots", ByteArrayUtilities.integerToBytes(grants - 1)); } - sendMessage(player, C.REMOVED_GRANTED_PLOT, "1", "" + (grants - 1)); + sendMessage(player, Captions.REMOVED_GRANTED_PLOT, "1", "" + (grants - 1)); } if (plot.canClaim(player)) { plot.owner = player.getUUID(); final String finalSchematic = schematic; - DBFunc.createPlotSafe(plot, new Runnable() { - @Override public void run() { - TaskManager.IMP.sync(new RunnableVal() { - @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); - } - } - }); + DBFunc.createPlotSafe(plot, () -> TaskManager.IMP.sync(new RunnableVal() { + @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); + } } - }, new Runnable() { - @Override public void run() { - sendMessage(player, C.PLOT_NOT_CLAIMED); - } - }); + }), () -> sendMessage(player, Captions.PLOT_NOT_CLAIMED)); return true; } else { - sendMessage(player, C.PLOT_NOT_CLAIMED); + sendMessage(player, Captions.PLOT_NOT_CLAIMED); } return false; } 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 index b4de09259..b45c52f65 100644 --- 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 @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.flag.FlagManager; import com.github.intellectualsites.plotsquared.plot.flag.Flags; @@ -30,13 +30,14 @@ import java.util.concurrent.CompletableFuture; @Override public CompletableFuture 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(args.length == 0, Captions.COMMAND_SYNTAX, getUsage()); + final Plot plot = check(player.getCurrentPlot(), Captions.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); + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_CLEAR), + Captions.NO_PLOT_PERMS); + checkTrue(plot.getRunning() == 0, Captions.WAIT_FOR_TIMER); checkTrue(!Settings.Done.RESTRICT_BUILDING || !Flags.DONE.isSet(plot) || Permissions - .hasPermission(player, C.PERMISSION_CONTINUE), C.DONE_ALREADY_DONE); + .hasPermission(player, Captions.PERMISSION_CONTINUE), Captions.DONE_ALREADY_DONE); confirm.run(this, () -> { final long start = System.currentTimeMillis(); boolean result = plot.clear(true, false, () -> { @@ -50,12 +51,12 @@ import java.util.concurrent.CompletableFuture; if (plot.getFlag(Flags.ANALYSIS).isPresent()) { FlagManager.removePlotFlag(plot, Flags.ANALYSIS); } - MainUtil.sendMessage(player, C.CLEARING_DONE, + MainUtil.sendMessage(player, Captions.CLEARING_DONE, "" + (System.currentTimeMillis() - start)); }); }); if (!result) { - MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); + MainUtil.sendMessage(player, Captions.WAIT_FOR_TIMER); } else { plot.addRunning(); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Cluster.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Cluster.java index c8360f696..32d7095a9 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Cluster.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Cluster.java @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.object.*; @@ -25,56 +25,59 @@ import java.util.UUID; // list, create, delete, resize, invite, kick, leave, helpers, tp, sethome if (args.length == 0) { // return arguments - MainUtil.sendMessage(player, C.CLUSTER_AVAILABLE_ARGS); + MainUtil.sendMessage(player, Captions.CLUSTER_AVAILABLE_ARGS); return false; } String sub = args[0].toLowerCase(); switch (sub) { case "l": case "list": { - if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_LIST)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_LIST); + if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_LIST)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_LIST); return false; } if (args.length != 1) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster list"); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot cluster list"); return false; } PlotArea area = player.getApplicablePlotArea(); if (area == null) { - C.NOT_IN_PLOT_WORLD.send(player); + Captions.NOT_IN_PLOT_WORLD.send(player); return false; } Set clusters = area.getClusters(); - MainUtil.sendMessage(player, C.CLUSTER_LIST_HEADING, clusters.size() + ""); + MainUtil.sendMessage(player, Captions.CLUSTER_LIST_HEADING, clusters.size() + ""); for (PlotCluster cluster : clusters) { // Ignore unmanaged clusters String name = "'" + cluster.getName() + "' : " + cluster.toString(); if (player.getUUID().equals(cluster.owner)) { - MainUtil.sendMessage(player, C.CLUSTER_LIST_ELEMENT, "&a" + name); + MainUtil.sendMessage(player, Captions.CLUSTER_LIST_ELEMENT, "&a" + name); } else if (cluster.helpers.contains(player.getUUID())) { - MainUtil.sendMessage(player, C.CLUSTER_LIST_ELEMENT, "&3" + name); + MainUtil.sendMessage(player, Captions.CLUSTER_LIST_ELEMENT, "&3" + name); } else if (cluster.invited.contains(player.getUUID())) { - MainUtil.sendMessage(player, C.CLUSTER_LIST_ELEMENT, "&9" + name); + MainUtil.sendMessage(player, Captions.CLUSTER_LIST_ELEMENT, "&9" + name); } else { - MainUtil.sendMessage(player, C.CLUSTER_LIST_ELEMENT, cluster.toString()); + MainUtil + .sendMessage(player, Captions.CLUSTER_LIST_ELEMENT, cluster.toString()); } } return true; } case "c": case "create": { - if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_CREATE)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_CREATE); + if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_CREATE)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_CREATE); return false; } PlotArea area = player.getApplicablePlotArea(); if (area == null) { - C.NOT_IN_PLOT_WORLD.send(player); + Captions.NOT_IN_PLOT_WORLD.send(player); return false; } if (args.length != 4) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot cluster create "); return false; } @@ -82,19 +85,22 @@ import java.util.UUID; player.getClusterCount() : player.getPlotCount(player.getLocation().getWorld()); if (currentClusters >= player.getAllowedPlots()) { - return sendMessage(player, C.CANT_CLAIM_MORE_CLUSTERS); + return sendMessage(player, Captions.CANT_CLAIM_MORE_CLUSTERS); } + PlotId pos1; + PlotId pos2; // check pos1 / pos2 - PlotId pos1 = PlotId.fromString(args[2]); - PlotId pos2 = PlotId.fromString(args[3]); - if (pos1 == null || pos2 == null) { - MainUtil.sendMessage(player, C.NOT_VALID_PLOT_ID); + try { + pos1 = PlotId.fromString(args[2]); + pos2 = PlotId.fromString(args[3]); + } catch (IllegalArgumentException ignored) { + MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_ID); return false; } // check if name is taken String name = args[1]; if (area.getCluster(name) != null) { - MainUtil.sendMessage(player, C.ALIAS_IS_TAKEN); + MainUtil.sendMessage(player, Captions.ALIAS_IS_TAKEN); return false; } if (pos2.x < pos1.x || pos2.y < pos1.y) { @@ -105,22 +111,23 @@ import java.util.UUID; //check if overlap PlotCluster cluster = area.getFirstIntersectingCluster(pos1, pos2); if (cluster != null) { - MainUtil.sendMessage(player, C.CLUSTER_INTERSECTION, cluster.getName()); + MainUtil.sendMessage(player, Captions.CLUSTER_INTERSECTION, cluster.getName()); return false; } // Check if it occupies existing plots if (!area.contains(pos1) || !area.contains(pos2)) { - C.CLUSTER_OUTSIDE.send(player, area); + Captions.CLUSTER_OUTSIDE.send(player, area); return false; } Set plots = area.getPlotSelectionOwned(pos1, pos2); if (!plots.isEmpty()) { - if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_CREATE_OTHER)) { + if (!Permissions + .hasPermission(player, Captions.PERMISSION_CLUSTER_CREATE_OTHER)) { 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, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_CREATE_OTHER); return false; } } @@ -134,11 +141,12 @@ import java.util.UUID; } 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, Captions.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, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_SIZE + "." + (current + cluster.getArea())); return false; } // create cluster @@ -148,72 +156,79 @@ import java.util.UUID; // Add any existing plots to the current cluster for (Plot plot : plots) { if (plot.hasOwner()) { - if (!cluster.isAdded(plot.owner)) { - cluster.invited.add(plot.owner); - DBFunc.setInvited(cluster, plot.owner); + if (!cluster.isAdded(plot.getOwner())) { + cluster.invited.add(plot.getOwner()); + DBFunc.setInvited(cluster, plot.getOwner()); } } } - MainUtil.sendMessage(player, C.CLUSTER_ADDED); + MainUtil.sendMessage(player, Captions.CLUSTER_ADDED); return true; } case "disband": case "del": case "delete": { - if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_DELETE)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_DELETE); + if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_DELETE)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_DELETE); return false; } if (args.length != 1 && args.length != 2) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster delete [name]"); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, + "/plot cluster delete [name]"); return false; } PlotArea area = player.getApplicablePlotArea(); if (area == null) { - C.NOT_IN_PLOT_WORLD.send(player); + Captions.NOT_IN_PLOT_WORLD.send(player); return false; } PlotCluster cluster; if (args.length == 2) { cluster = area.getCluster(args[1]); if (cluster == null) { - MainUtil.sendMessage(player, C.INVALID_CLUSTER, args[1]); + MainUtil.sendMessage(player, Captions.INVALID_CLUSTER, args[1]); return false; } } else { cluster = area.getCluster(player.getLocation()); if (cluster == null) { - MainUtil.sendMessage(player, C.NOT_IN_CLUSTER); + MainUtil.sendMessage(player, Captions.NOT_IN_CLUSTER); return false; } } 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); + if (!Permissions + .hasPermission(player, Captions.PERMISSION_CLUSTER_DELETE_OTHER)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_DELETE_OTHER); return false; } } DBFunc.delete(cluster); - MainUtil.sendMessage(player, C.CLUSTER_DELETED); + MainUtil.sendMessage(player, Captions.CLUSTER_DELETED); return true; } case "res": case "resize": { - if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_RESIZE)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_RESIZE); + if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_RESIZE)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_RESIZE); return false; } if (args.length != 3) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot cluster resize "); return false; } + PlotId pos1; + PlotId pos2; // check pos1 / pos2 - PlotId pos1 = PlotId.fromString(args[1]); - PlotId pos2 = PlotId.fromString(args[2]); - if (pos1 == null || pos2 == null) { - MainUtil.sendMessage(player, C.NOT_VALID_PLOT_ID); + try { + pos1 = PlotId.fromString(args[2]); + pos2 = PlotId.fromString(args[3]); + } catch (IllegalArgumentException ignored) { + MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_ID); return false; } if (pos2.x < pos1.x || pos2.y < pos1.y) { @@ -223,29 +238,30 @@ import java.util.UUID; // check if in cluster PlotArea area = player.getApplicablePlotArea(); if (area == null) { - C.NOT_IN_PLOT_WORLD.send(player); + Captions.NOT_IN_PLOT_WORLD.send(player); return false; } PlotCluster cluster = area.getCluster(player.getLocation()); if (cluster == null) { - MainUtil.sendMessage(player, C.NOT_IN_CLUSTER); + MainUtil.sendMessage(player, Captions.NOT_IN_CLUSTER); return false; } 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); + if (!Permissions + .hasPermission(player, Captions.PERMISSION_CLUSTER_RESIZE_OTHER)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_RESIZE_OTHER); return false; } } //check if overlap PlotCluster intersect = area.getFirstIntersectingCluster(pos1, pos2); if (intersect != null) { - MainUtil.sendMessage(player, C.CLUSTER_INTERSECTION, intersect.getName()); + MainUtil + .sendMessage(player, Captions.CLUSTER_INTERSECTION, intersect.getName()); return false; } - Set existing = - area.getPlotSelectionOwned(cluster.getP1(), cluster.getP2()); + Set existing = area.getPlotSelectionOwned(cluster.getP1(), cluster.getP2()); Set newPlots = area.getPlotSelectionOwned(pos1, pos2); // Set removed = (HashSet) existing.clone(); Set removed = new HashSet<>(existing); @@ -253,17 +269,19 @@ import java.util.UUID; 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); + if (!Permissions + .hasPermission(player, Captions.PERMISSION_CLUSTER_RESIZE_SHRINK)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.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); + if (!Permissions + .hasPermission(player, Captions.PERMISSION_CLUSTER_RESIZE_EXPAND)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_RESIZE_EXPAND); return false; } } @@ -275,50 +293,53 @@ import java.util.UUID; 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, Captions.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, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER.s() + "." + (current + cluster.getArea())); return false; } // resize cluster DBFunc.resizeCluster(cluster, pos1, pos2); - MainUtil.sendMessage(player, C.CLUSTER_RESIZED); + MainUtil.sendMessage(player, Captions.CLUSTER_RESIZED); return true; } case "add": case "inv": case "invite": { - if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_INVITE)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_INVITE); + if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_INVITE)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_INVITE); return false; } if (args.length != 2) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster invite "); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, + "/plot cluster invite "); return false; } // check if in cluster PlotArea area = player.getApplicablePlotArea(); if (area == null) { - C.NOT_IN_PLOT_WORLD.send(player); + Captions.NOT_IN_PLOT_WORLD.send(player); } PlotCluster cluster = area.getCluster(player.getLocation()); if (cluster == null) { - MainUtil.sendMessage(player, C.NOT_IN_CLUSTER); + MainUtil.sendMessage(player, Captions.NOT_IN_CLUSTER); return false; } 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); + if (!Permissions + .hasPermission(player, Captions.PERMISSION_CLUSTER_INVITE_OTHER)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_INVITE_OTHER); return false; } } // check uuid UUID uuid = UUIDHandler.getUUID(args[1], null); if (uuid == null) { - MainUtil.sendMessage(player, C.INVALID_PLAYER, args[2]); + MainUtil.sendMessage(player, Captions.INVALID_PLAYER, args[2]); return false; } if (!cluster.isAdded(uuid)) { @@ -327,49 +348,52 @@ import java.util.UUID; DBFunc.setInvited(cluster, uuid); PlotPlayer player2 = UUIDHandler.getPlayer(uuid); if (player2 != null) { - MainUtil.sendMessage(player2, C.CLUSTER_INVITED, cluster.getName()); + MainUtil.sendMessage(player2, Captions.CLUSTER_INVITED, cluster.getName()); } } - MainUtil.sendMessage(player, C.CLUSTER_ADDED_USER); + MainUtil.sendMessage(player, Captions.CLUSTER_ADDED_USER); return true; } case "k": case "remove": case "kick": { - if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_KICK)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_KICK); + if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_KICK)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_KICK); return false; } if (args.length != 2) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster kick "); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, + "/plot cluster kick "); return false; } PlotArea area = player.getApplicablePlotArea(); if (area == null) { - C.NOT_IN_PLOT_WORLD.send(player); + Captions.NOT_IN_PLOT_WORLD.send(player); } PlotCluster cluster = area.getCluster(player.getLocation()); if (cluster == null) { - MainUtil.sendMessage(player, C.NOT_IN_CLUSTER); + MainUtil.sendMessage(player, Captions.NOT_IN_CLUSTER); return false; } 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); + if (!Permissions + .hasPermission(player, Captions.PERMISSION_CLUSTER_KICK_OTHER)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_KICK_OTHER); return false; } } // check uuid UUID uuid = UUIDHandler.getUUID(args[1], null); if (uuid == null) { - MainUtil.sendMessage(player, C.INVALID_PLAYER, args[1]); + MainUtil.sendMessage(player, Captions.INVALID_PLAYER, args[1]); 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)) { - MainUtil.sendMessage(player, C.CANNOT_KICK_PLAYER, cluster.getName()); + MainUtil.sendMessage(player, Captions.CANNOT_KICK_PLAYER, cluster.getName()); return false; } if (cluster.helpers.contains(uuid)) { @@ -380,7 +404,7 @@ import java.util.UUID; DBFunc.removeInvited(cluster, uuid); PlotPlayer player2 = UUIDHandler.getPlayer(uuid); if (player2 != null) { - MainUtil.sendMessage(player2, C.CLUSTER_REMOVED, cluster.getName()); + MainUtil.sendMessage(player2, Captions.CLUSTER_REMOVED, cluster.getName()); } for (Plot plot : new ArrayList<>( PlotSquared.get().getPlots(player2.getLocation().getWorld(), uuid))) { @@ -389,44 +413,46 @@ import java.util.UUID; plot.unclaim(); } } - MainUtil.sendMessage(player2, C.CLUSTER_KICKED_USER); + MainUtil.sendMessage(player2, Captions.CLUSTER_KICKED_USER); return true; } case "quit": case "leave": { - if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_LEAVE)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_LEAVE); + if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_LEAVE)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_LEAVE); return false; } if (args.length != 1 && args.length != 2) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster leave [name]"); + MainUtil + .sendMessage(player, Captions.COMMAND_SYNTAX, "/plot cluster leave [name]"); return false; } PlotArea area = player.getApplicablePlotArea(); if (area == null) { - C.NOT_IN_PLOT_WORLD.send(player); + Captions.NOT_IN_PLOT_WORLD.send(player); } PlotCluster cluster; if (args.length == 2) { cluster = area.getCluster(args[1]); if (cluster == null) { - MainUtil.sendMessage(player, C.INVALID_CLUSTER, args[1]); + MainUtil.sendMessage(player, Captions.INVALID_CLUSTER, args[1]); return false; } } else { cluster = area.getCluster(player.getLocation()); if (cluster == null) { - MainUtil.sendMessage(player, C.NOT_IN_CLUSTER); + MainUtil.sendMessage(player, Captions.NOT_IN_CLUSTER); return false; } } UUID uuid = player.getUUID(); if (!cluster.isAdded(uuid)) { - MainUtil.sendMessage(player, C.CLUSTER_NOT_ADDED); + MainUtil.sendMessage(player, Captions.CLUSTER_NOT_ADDED); return false; } if (uuid.equals(cluster.owner)) { - MainUtil.sendMessage(player, C.CLUSTER_CANNOT_LEAVE); + MainUtil.sendMessage(player, Captions.CLUSTER_CANNOT_LEAVE); return false; } if (cluster.helpers.contains(uuid)) { @@ -435,12 +461,11 @@ import java.util.UUID; } cluster.invited.remove(uuid); DBFunc.removeInvited(cluster, uuid); - MainUtil.sendMessage(player, C.CLUSTER_REMOVED, cluster.getName()); + MainUtil.sendMessage(player, Captions.CLUSTER_REMOVED, cluster.getName()); 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(); plot.unclaim(); } } @@ -450,102 +475,107 @@ import java.util.UUID; case "admin": case "helper": case "helpers": { - if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_HELPERS)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_HELPERS); + if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_HELPERS)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_HELPERS); return false; } if (args.length != 3) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot cluster helpers "); return false; } PlotArea area = player.getApplicablePlotArea(); if (area == null) { - C.NOT_IN_PLOT_WORLD.send(player); + Captions.NOT_IN_PLOT_WORLD.send(player); } PlotCluster cluster = area.getCluster(player.getLocation()); if (cluster == null) { - MainUtil.sendMessage(player, C.NOT_IN_CLUSTER); + MainUtil.sendMessage(player, Captions.NOT_IN_CLUSTER); return false; } UUID uuid = UUIDHandler.getUUID(args[2], null); if (uuid == null) { - MainUtil.sendMessage(player, C.INVALID_PLAYER, args[2]); + MainUtil.sendMessage(player, Captions.INVALID_PLAYER, args[2]); return false; } if (args[1].equalsIgnoreCase("add")) { cluster.helpers.add(uuid); DBFunc.setHelper(cluster, uuid); - return MainUtil.sendMessage(player, C.CLUSTER_ADDED_HELPER); + return MainUtil.sendMessage(player, Captions.CLUSTER_ADDED_HELPER); } if (args[1].equalsIgnoreCase("remove")) { cluster.helpers.remove(uuid); DBFunc.removeHelper(cluster, uuid); - return MainUtil.sendMessage(player, C.CLUSTER_REMOVED_HELPER); + return MainUtil.sendMessage(player, Captions.CLUSTER_REMOVED_HELPER); } - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot cluster helpers "); return false; } case "spawn": case "home": case "tp": { - if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_TP)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_TP); + if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_TP)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_TP); return false; } if (args.length != 2) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster tp "); + MainUtil + .sendMessage(player, Captions.COMMAND_SYNTAX, "/plot cluster tp "); return false; } PlotArea area = player.getApplicablePlotArea(); if (area == null) { - C.NOT_IN_PLOT_WORLD.send(player); + Captions.NOT_IN_PLOT_WORLD.send(player); return false; } PlotCluster cluster = area.getCluster(args[1]); if (cluster == null) { - MainUtil.sendMessage(player, C.INVALID_CLUSTER, args[1]); + MainUtil.sendMessage(player, Captions.INVALID_CLUSTER, args[1]); return false; } 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); + if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_TP_OTHER)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_TP_OTHER); return false; } } player.teleport(cluster.getHome()); - return MainUtil.sendMessage(player, C.CLUSTER_TELEPORTING); + return MainUtil.sendMessage(player, Captions.CLUSTER_TELEPORTING); } case "i": case "info": case "show": case "information": { - if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_INFO)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_INFO); + if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_INFO)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_INFO); return false; } if (args.length != 1 && args.length != 2) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster info [name]"); + MainUtil + .sendMessage(player, Captions.COMMAND_SYNTAX, "/plot cluster info [name]"); return false; } PlotArea area = player.getApplicablePlotArea(); if (area == null) { - C.NOT_IN_PLOT_WORLD.send(player); + Captions.NOT_IN_PLOT_WORLD.send(player); } PlotCluster cluster; if (args.length == 2) { cluster = area.getCluster(args[1]); if (cluster == null) { - MainUtil.sendMessage(player, C.INVALID_CLUSTER, args[1]); + MainUtil.sendMessage(player, Captions.INVALID_CLUSTER, args[1]); return false; } } else { cluster = area.getCluster(player.getLocation()); if (cluster == null) { - MainUtil.sendMessage(player, C.NOT_IN_CLUSTER); + MainUtil.sendMessage(player, Captions.NOT_IN_CLUSTER); return false; } } @@ -558,7 +588,7 @@ import java.util.UUID; 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(); + String message = Captions.CLUSTER_INFO.s(); message = message.replaceAll("%id%", id); message = message.replaceAll("%owner%", owner); message = message.replaceAll("%name%", name); @@ -570,27 +600,29 @@ import java.util.UUID; case "sh": case "setspawn": case "sethome": - if (!Permissions.hasPermission(player, C.PERMISSION_CLUSTER_SETHOME)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_CLUSTER_SETHOME); + if (!Permissions.hasPermission(player, Captions.PERMISSION_CLUSTER_SETHOME)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_SETHOME); return false; } if (args.length != 1 && args.length != 2) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot cluster sethome"); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot cluster sethome"); return false; } PlotArea area = player.getApplicablePlotArea(); if (area == null) { - C.NOT_IN_PLOT_WORLD.send(player); + Captions.NOT_IN_PLOT_WORLD.send(player); } PlotCluster cluster = area.getCluster(player.getLocation()); if (cluster == null) { - MainUtil.sendMessage(player, C.NOT_IN_CLUSTER); + MainUtil.sendMessage(player, Captions.NOT_IN_CLUSTER); return false; } 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); + if (!Permissions + .hasPermission(player, Captions.PERMISSION_CLUSTER_SETHOME_OTHER)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_CLUSTER_SETHOME_OTHER); return false; } } @@ -600,9 +632,9 @@ import java.util.UUID; cluster.settings.setPosition(blockloc); DBFunc.setPosition(cluster, relative.getX() + "," + relative.getY() + "," + relative.getZ()); - return MainUtil.sendMessage(player, C.POSITION_SET); + return MainUtil.sendMessage(player, Captions.POSITION_SET); } - MainUtil.sendMessage(player, C.CLUSTER_AVAILABLE_ARGS); + MainUtil.sendMessage(player, Captions.CLUSTER_AVAILABLE_ARGS); return false; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/CommandCategory.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/CommandCategory.java index 4aeacf85c..bebf77907 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/CommandCategory.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/CommandCategory.java @@ -1,56 +1,58 @@ package com.github.intellectualsites.plotsquared.plot.commands; +import com.github.intellectualsites.plotsquared.plot.config.Captions; +import lombok.RequiredArgsConstructor; + /** * CommandCategory. */ -public enum CommandCategory { +@RequiredArgsConstructor public enum CommandCategory { /** * Claiming CommandConfig. * Such as: /plot claim */ - CLAIMING("Claiming"), /** + CLAIMING(Captions.COMMAND_CATEGORY_CLAIMING), + /** * Teleportation CommandConfig. * Such as: /plot visit */ - TELEPORT("Teleport"), /** + TELEPORT(Captions.COMMAND_CATEGORY_TELEPPORT), + /** * Protection. */ - SETTINGS("Protection"), /** + SETTINGS(Captions.COMMAND_CATEGORY_SETTINGS), + /** * Chat. */ - CHAT("Chat"), /** + CHAT(Captions.COMMAND_CATEGORY_CHAT), + /** * Web. */ - SCHEMATIC("Web"), /** + SCHEMATIC(Captions.COMMAND_CATEGORY_SCHEMATIC), + /** * Cosmetic. */ - APPEARANCE("Cosmetic"), /** + APPEARANCE(Captions.COMMAND_CATEGORY_APPEARANCE), + /** * Information CommandConfig. * Such as: /plot info */ - INFO("Info"), /** + INFO(Captions.COMMAND_CATEGORY_INFO), + /** * Debug CommandConfig. * Such as: /plot debug */ - DEBUG("Debug"), /** + DEBUG(Captions.COMMAND_CATEGORY_DEBUG), + /** * Administration commands. */ - ADMINISTRATION("Admin"); + ADMINISTRATION(Captions.COMMAND_CATEGORY_ADMINISTRATION); /** * The category name (Readable). */ - private final String name; - - /** - * Constructor. - * - * @param name readable name - */ - CommandCategory(String name) { - this.name = name; - } + private final Captions caption; @Override public String toString() { - return this.name; + return this.caption.s(); } } 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 index 775450517..048047bb6 100644 --- 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 @@ -1,7 +1,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotId; @@ -17,23 +17,29 @@ 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") + category = CommandCategory.CHAT, requiredType = RequiredType.PLAYER, 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, + sendMessage(player, Captions.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, + sendMessage(player, Captions.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(), "|")); return false; } Location loc = player.getLocation(); - PlotId id = PlotId.fromString(args[1]); + PlotId id; + try { + id = PlotId.fromString(args[1]); + } catch (IllegalArgumentException ignored) { + MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_ID); + return false; + } Plot plot = MainUtil.getPlotFromString(player, args[1], false); int index; if (plot == null) { @@ -41,14 +47,14 @@ public class Comment extends SubCommand { plot = loc.getPlotAbs(); } else { if (args.length < 4) { - sendMessage(player, C.COMMENT_SYNTAX, + sendMessage(player, Captions.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(), "|")); return false; } index = 2; } if (!inbox.canWrite(plot, player)) { - sendMessage(player, C.NO_PERM_INBOX, ""); + sendMessage(player, Captions.NO_PERM_INBOX, ""); return false; } String message = StringMan.join(Arrays.copyOfRange(args, index, args.length), " "); @@ -57,8 +63,8 @@ public class Comment extends SubCommand { System.currentTimeMillis()); boolean result = inbox.addComment(plot, comment); if (!result) { - sendMessage(player, C.NO_PLOT_INBOX, ""); - sendMessage(player, C.COMMENT_SYNTAX, + sendMessage(player, Captions.NO_PLOT_INBOX, ""); + sendMessage(player, Captions.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(), "|")); return false; } @@ -68,7 +74,7 @@ public class Comment extends SubCommand { MainUtil.sendMessage(pp, "/plot comment " + StringMan.join(args, " ")); } } - sendMessage(player, C.COMMENT_ADDED); + sendMessage(player, Captions.COMMENT_ADDED); return true; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Condense.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Condense.java index 040fd97b8..184e2289d 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Condense.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Condense.java @@ -11,7 +11,11 @@ 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.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; @@ -104,6 +108,7 @@ import java.util.concurrent.atomic.AtomicBoolean; return false; } MainUtil.sendMessage(player, "TASK STARTED..."); + Condense.TASK = true; Runnable run = new Runnable() { @Override public void run() { if (!Condense.TASK) { @@ -126,13 +131,11 @@ import java.util.concurrent.atomic.AtomicBoolean; } i++; final AtomicBoolean result = new AtomicBoolean(false); - result.set(origin.move(possible, new Runnable() { - @Override public void run() { - if (result.get()) { - MainUtil.sendMessage(player, - "Moving: " + origin + " -> " + possible); - TaskManager.runTaskLater(task, 1); - } + result.set(origin.move(possible, () -> { + if (result.get()) { + MainUtil.sendMessage(player, + "Moving: " + origin + " -> " + possible); + TaskManager.runTaskLater(task, 1); } }, false)); if (result.get()) { @@ -149,7 +152,6 @@ import java.util.concurrent.atomic.AtomicBoolean; } } }; - Condense.TASK = true; TaskManager.runTaskAsync(run); return true; } 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 index b33bd4dab..75a4709b8 100644 --- 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 @@ -1,7 +1,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.object.CmdInstance; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; @@ -16,13 +16,13 @@ import com.github.intellectualsites.plotsquared.plot.util.TaskManager; @Override public boolean onCommand(PlotPlayer player, String[] args) { CmdInstance command = CmdConfirm.getPending(player); if (command == null) { - MainUtil.sendMessage(player, C.FAILED_CONFIRM); + MainUtil.sendMessage(player, Captions.FAILED_CONFIRM); return false; } CmdConfirm.removePending(player); if ((System.currentTimeMillis() - command.timestamp) > Settings.Confirmation.CONFIRMATION_TIMEOUT_SECONDS * 1000) { - MainUtil.sendMessage(player, C.EXPIRED_CONFIRM); + MainUtil.sendMessage(player, Captions.EXPIRED_CONFIRM); return false; } TaskManager.runTask(command.command); 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 index 68bf8c786..4aec2d6d0 100644 --- 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 @@ -1,7 +1,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.object.Plot; @@ -17,29 +17,30 @@ import com.github.intellectualsites.plotsquared.plot.util.Permissions; @Override public boolean onCommand(PlotPlayer player, String[] args) { Plot plot = player.getCurrentPlot(); if ((plot == null) || !plot.hasOwner()) { - return !sendMessage(player, C.NOT_IN_PLOT); + return !sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot.isOwner(player.getUUID()) && !Permissions - .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_CONTINUE)) { - MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_CONTINUE)) { + MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } if (!plot.hasFlag(Flags.DONE)) { - MainUtil.sendMessage(player, C.DONE_NOT_DONE); + MainUtil.sendMessage(player, Captions.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); + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_ADMIN_COMMAND_CONTINUE); return false; } if (plot.getRunning() > 0) { - MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); + MainUtil.sendMessage(player, Captions.WAIT_FOR_TIMER); return false; } plot.removeFlag(Flags.DONE); - MainUtil.sendMessage(player, C.DONE_REMOVED); + MainUtil.sendMessage(player, Captions.DONE_REMOVED); return true; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Copy.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Copy.java index 8303ef042..dd95a8c2f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Copy.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Copy.java @@ -1,7 +1,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; @@ -16,15 +16,15 @@ import com.github.intellectualsites.plotsquared.plot.util.Permissions; Location loc = player.getLocation(); Plot plot1 = loc.getPlotAbs(); if (plot1 == null) { - return !MainUtil.sendMessage(player, C.NOT_IN_PLOT); + return !MainUtil.sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot1.isOwner(player.getUUID()) && !Permissions - .hasPermission(player, C.PERMISSION_ADMIN.s())) { - MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + .hasPermission(player, Captions.PERMISSION_ADMIN.s())) { + MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } if (args.length != 1) { - C.COMMAND_SYNTAX.send(player, getUsage()); + Captions.COMMAND_SYNTAX.send(player, getUsage()); return false; } Plot plot2 = MainUtil.getPlotFromString(player, args[0], true); @@ -32,22 +32,18 @@ import com.github.intellectualsites.plotsquared.plot.util.Permissions; return false; } if (plot1.equals(plot2)) { - MainUtil.sendMessage(player, C.NOT_VALID_PLOT_ID); - C.COMMAND_SYNTAX.send(player, getUsage()); + MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_ID); + Captions.COMMAND_SYNTAX.send(player, getUsage()); return false; } if (!plot1.getArea().isCompatible(plot2.getArea())) { - C.PLOTWORLD_INCOMPATIBLE.send(player); + Captions.PLOTWORLD_INCOMPATIBLE.send(player); return false; } - if (plot1.copy(plot2, new Runnable() { - @Override public void run() { - MainUtil.sendMessage(player, C.COPY_SUCCESS); - } - })) { + if (plot1.copy(plot2, () -> MainUtil.sendMessage(player, Captions.COPY_SUCCESS))) { return true; } else { - MainUtil.sendMessage(player, C.REQUIRES_UNOWNED); + MainUtil.sendMessage(player, Captions.REQUIRES_UNOWNED); return false; } } 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 index acc47a64e..26962781c 100644 --- 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 @@ -1,7 +1,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotWorld; import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; import com.github.intellectualsites.plotsquared.plot.object.Location; @@ -19,10 +19,10 @@ import com.github.intellectualsites.plotsquared.plot.util.MainUtil; Location loc = player.getLocation(); Plot plot = loc.getPlotAbs(); if (plot == null) { - return sendMessage(player, C.NOT_IN_PLOT); + return sendMessage(player, Captions.NOT_IN_PLOT); } if (!(loc.getPlotArea() instanceof HybridPlotWorld)) { - return sendMessage(player, C.NOT_IN_PLOT_WORLD); + return sendMessage(player, Captions.NOT_IN_PLOT_WORLD); } HybridUtils.manager.setupRoadSchematic(plot); MainUtil.sendMessage(player, diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Database.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Database.java index b760bc282..d908f2105 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Database.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Database.java @@ -30,25 +30,18 @@ import java.util.Map.Entry; public static void insertPlots(final SQLManager manager, final List plots, final PlotPlayer player) { - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - try { - ArrayList ps = new ArrayList<>(); - for (Plot p : plots) { - ps.add(p); - } - MainUtil.sendMessage(player, "&6Starting..."); - manager.createPlotsAndData(ps, new Runnable() { - @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"); - e.printStackTrace(); - } + TaskManager.runTaskAsync(() -> { + try { + ArrayList ps = new ArrayList<>(plots); + MainUtil.sendMessage(player, "&6Starting..."); + manager.createPlotsAndData(ps, () -> { + MainUtil.sendMessage(player, "&6Database conversion finished!"); + manager.close(); + }); + } catch (Exception e) { + MainUtil + .sendMessage(player, "Failed to insert plot objects, see stacktrace for info"); + e.printStackTrace(); } }); } @@ -94,8 +87,8 @@ import java.util.Map.Entry; HashMap> map = manager.getPlots(); plots = new ArrayList<>(); for (Entry> entry : map.entrySet()) { - String areaname = entry.getKey(); - PlotArea pa = PlotSquared.get().getPlotAreaByString(areaname); + String areaName = entry.getKey(); + PlotArea pa = PlotSquared.get().getPlotAreaByString(areaName); if (pa != null) { for (Entry entry2 : entry.getValue().entrySet()) { Plot plot = entry2.getValue(); @@ -130,20 +123,13 @@ import java.util.Map.Entry; plots.add(plot); } } else { - HashMap plotmap = - PlotSquared.get().plots_tmp.get(areaname); - if (plotmap == null) { - plotmap = new HashMap<>(); - PlotSquared.get().plots_tmp.put(areaname, plotmap); - } - plotmap.putAll(entry.getValue()); + HashMap plotMap = PlotSquared.get().plots_tmp + .computeIfAbsent(areaName, k -> new HashMap<>()); + plotMap.putAll(entry.getValue()); } } - DBFunc.createPlotsAndData(plots, new Runnable() { - @Override public void run() { - MainUtil.sendMessage(player, "&6Database conversion finished!"); - } - }); + DBFunc.createPlotsAndData(plots, + () -> MainUtil.sendMessage(player, "&6Database conversion finished!")); return true; case "mysql": if (args.length < 6) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Debug.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Debug.java index 28594982c..527b67819 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Debug.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Debug.java @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.StringMan; @@ -14,23 +14,23 @@ public class Debug extends SubCommand { @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()) { + for (Captions caption : Captions.values()) { msg.append(caption.s()).append("\n"); } MainUtil.sendMessage(player, msg.toString()); return true; } StringBuilder information = new StringBuilder(); - String header = C.DEBUG_HEADER.s(); - String line = C.DEBUG_LINE.s(); - String section = C.DEBUG_SECTION.s(); + String header = Captions.DEBUG_HEADER.s(); + String line = Captions.DEBUG_LINE.s(); + String section = Captions.DEBUG_SECTION.s(); information.append(header); information.append(getSection(section, "PlotArea")); 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, "Total Messages", Captions.values().length)); information.append(getLine(line, "View all captions", "/plot debug msg")); MainUtil.sendMessage(player, information.toString()); return true; 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 index cbfacfae6..8413eae22 100644 --- 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 @@ -1,7 +1,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import java.util.ArrayList; @@ -19,10 +19,10 @@ import java.util.UUID; if (unsafeAllowed.contains(player.getUUID())) { unsafeAllowed.remove(player.getUUID()); - sendMessage(player, C.DEBUGALLOWUNSAFE_OFF); + sendMessage(player, Captions.DEBUGALLOWUNSAFE_OFF); } else { unsafeAllowed.add(player.getUUID()); - sendMessage(player, C.DEBUGALLOWUNSAFE_ON); + sendMessage(player, Captions.DEBUGALLOWUNSAFE_ON); } return true; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugClaimTest.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugClaimTest.java index 01a344369..41a5eda80 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugClaimTest.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugClaimTest.java @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.object.*; import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; @@ -29,7 +29,7 @@ public class DebugClaimTest extends SubCommand { } PlotArea area = PlotSquared.get().getPlotAreaByString(args[0]); if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) { - C.NOT_VALID_PLOT_WORLD.send(player, args[0]); + Captions.NOT_VALID_PLOT_WORLD.send(player, args[0]); return false; } PlotId min, max; @@ -55,7 +55,7 @@ public class DebugClaimTest extends SubCommand { MainUtil.sendMessage(player, " - &cDB Already contains: " + plot.getId()); continue; } - Location loc = manager.getSignLoc(area, plot); + Location loc = manager.getSignLoc(plot); ChunkLoc chunk = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4); boolean result = ChunkManager.manager.loadChunk(area.worldname, chunk, false); if (!result) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugExec.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugExec.java index f0f4e148a..7e8e9cf34 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugExec.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugExec.java @@ -3,7 +3,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.flag.Flag; @@ -17,12 +17,21 @@ 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 javax.script.*; +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.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.sql.Timestamp; -import java.util.*; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; import java.util.concurrent.CompletableFuture; @CommandDeclaration(command = "debugexec", permission = "plots.admin", @@ -32,6 +41,8 @@ import java.util.concurrent.CompletableFuture; private Bindings scope; public DebugExec() { + init(); +/* try { if (PlotSquared.get() != null) { File file = new File(PlotSquared.get().IMP.getDirectory(), @@ -50,6 +61,7 @@ import java.util.concurrent.CompletableFuture; } catch (IOException | ScriptException ignored) { ignored.printStackTrace(); } +*/ } public ScriptEngine getEngine() { @@ -67,7 +79,15 @@ import java.util.concurrent.CompletableFuture; if (this.engine != null) { return; } - this.engine = new ScriptEngineManager(null).getEngineByName("nashorn"); + //create script engine manager + ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); + //create nashorn engine + this.engine = scriptEngineManager.getEngineByName("nashorn"); + try { + engine.eval("print('PlotSquared Scripting Test');"); + } catch (ScriptException e) { + e.printStackTrace(); + } if (this.engine == null) { this.engine = new ScriptEngineManager(null).getEngineByName("JavaScript"); } @@ -97,7 +117,6 @@ import java.util.concurrent.CompletableFuture; this.scope.put("WEManager", new WEManager()); } this.scope.put("TaskManager", TaskManager.IMP); - this.scope.put("TitleManager", AbstractTitle.TITLE_CLASS); this.scope.put("ConsolePlayer", ConsolePlayer.getConsole()); this.scope.put("SchematicHandler", SchematicHandler.manager); this.scope.put("ChunkManager", ChunkManager.manager); @@ -112,7 +131,7 @@ import java.util.concurrent.CompletableFuture; this.scope.put("MainCommand", MainCommand.getInstance()); // enums - for (Enum value : C.values()) { + for (Enum value : Captions.values()) { this.scope.put("C_" + value.name(), value); } } @@ -130,7 +149,7 @@ import java.util.concurrent.CompletableFuture; case "analyze": { Plot plot = player.getCurrentPlot(); if (plot == null) { - MainUtil.sendMessage(player, C.NOT_IN_PLOT); + MainUtil.sendMessage(player, Captions.NOT_IN_PLOT); return false; } PlotAnalysis analysis = plot.getComplexity(null); @@ -149,7 +168,7 @@ import java.util.concurrent.CompletableFuture; } case "calibrate-analysis": if (args.length != 2) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + MainUtil.sendMessage(player, Captions.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 " @@ -165,8 +184,8 @@ import java.util.concurrent.CompletableFuture; "$1 $2= $1The percentage of plots you want to clear as a number between 0 - 100"); return false; } - PlotAnalysis.calcOptimalModifiers( - () -> MainUtil.sendMessage(player, "$1Thank you for calibrating plot expiry"), threshold); + PlotAnalysis.calcOptimalModifiers(() -> MainUtil + .sendMessage(player, "$1Thank you for calibrating plot expiry"), threshold); return true; case "stop-expire": if (ExpireManager.IMP == null || !ExpireManager.IMP.cancelTask()) { @@ -175,7 +194,7 @@ import java.util.concurrent.CompletableFuture; return MainUtil.sendMessage(player, "Cancelled task."); case "remove-flag": if (args.length != 2) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot debugexec remove-flag "); return false; } @@ -195,7 +214,7 @@ import java.util.concurrent.CompletableFuture; } PlotArea area = PlotSquared.get().getPlotAreaByString(args[1]); if (area == null) { - MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD, args[1]); + MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_WORLD, args[1]); return false; } boolean result; @@ -275,7 +294,7 @@ import java.util.concurrent.CompletableFuture; DebugExec.this.engine.eval(cmd, DebugExec.this.scope); } catch (ScriptException e) { e.printStackTrace(); - MainUtil.sendMessage(player, C.COMMAND_WENT_WRONG); + MainUtil.sendMessage(player, Captions.COMMAND_WENT_WRONG); } return CompletableFuture.completedFuture(true); } @@ -283,8 +302,8 @@ import java.util.concurrent.CompletableFuture; return true; } catch (IOException e) { e.printStackTrace(); - MainUtil - .sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec addcmd "); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, + "/plot debugexec addcmd "); return false; } case "runasync": @@ -324,7 +343,8 @@ import java.util.concurrent.CompletableFuture; break; } default: - C.COMMAND_SYNTAX.send(player, "/plot debugexec list-scripts [#]"); + Captions.COMMAND_SYNTAX + .send(player, "/plot debugexec list-scripts [#]"); return false; } @@ -341,7 +361,7 @@ import java.util.concurrent.CompletableFuture; return true; case "allcmd": if (args.length < 3) { - C.COMMAND_SYNTAX + Captions.COMMAND_SYNTAX .send(player, "/plot debugexec allcmd "); return false; } @@ -381,7 +401,8 @@ import java.util.concurrent.CompletableFuture; break; case "all": if (args.length < 3) { - C.COMMAND_SYNTAX.send(player, "/plot debugexec all "); + Captions.COMMAND_SYNTAX + .send(player, "/plot debugexec all "); return false; } script = @@ -394,7 +415,7 @@ import java.util.concurrent.CompletableFuture; script = StringMan.join(args, " "); } if (!(player instanceof ConsolePlayer)) { - MainUtil.sendMessage(player, C.NOT_CONSOLE); + MainUtil.sendMessage(player, Captions.NOT_CONSOLE); return false; } init(); @@ -411,8 +432,8 @@ import java.util.concurrent.CompletableFuture; } catch (ScriptException e) { e.printStackTrace(); } - PlotSquared.log( - "> " + (System.currentTimeMillis() - start) + "ms -> " + result); + PlotSquared + .log("> " + (System.currentTimeMillis() - start) + "ms -> " + result); }); } else { long start = System.currentTimeMillis(); 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 index da1e27e61..ca848a6bb 100644 --- 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 @@ -3,7 +3,7 @@ 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.config.Captions; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.flag.Flag; import com.github.intellectualsites.plotsquared.plot.object.Plot; @@ -28,7 +28,7 @@ public class DebugFixFlags extends SubCommand { @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]); + MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_WORLD, args[0]); return false; } MainUtil.sendMessage(player, "&8--- &6Starting task &8 ---"); 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 index 8a4cfe613..6ce41e749 100644 --- 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 @@ -37,10 +37,20 @@ import java.util.concurrent.CompletableFuture; SinglePlotArea area = ((SinglePlotAreaManager) pam).getArea(); PlotId id = new PlotId(0, 0); File container = PlotSquared.imp().getWorldContainer(); + if (container.equals(new File("."))) { + player.sendMessage( + "World container must be configured to be a separate directory to your base files!"); + return; + } 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 (!WorldUtil.IMP.isWorld(name) && PlotId.fromStringOrNull(name) == null) { + UUID uuid; + if (name.length() > 16) { + uuid = UUID.fromString(name); + } else { + uuid = UUIDHandler.getUUID(name, null); + } if (uuid == null) { uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); 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 index 81275cac7..7fe7bfdd1 100644 --- 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 @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.util.IncendoPaster; @@ -18,25 +18,37 @@ import java.io.File; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; -import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; @CommandDeclaration(command = "debugpaste", aliases = "dp", usage = "/plot debugpaste", - description = "Upload settings.yml, worlds.yml, PlotSquared.use_THIS.yml and your latest.log to https://incendo.org", + description = "Upload settings.yml, worlds.yml, PlotSquared.use_THIS.yml and your latest.log to https://athion.net/ISPaster/paste", permission = "plots.debugpaste", category = CommandCategory.DEBUG) public class DebugPaste extends SubCommand { + private static String readFile(@NonNull final File file) throws IOException { + final List lines; + try (final BufferedReader reader = new BufferedReader(new FileReader(file))) { + lines = reader.lines().collect(Collectors.toList()); + } + final StringBuilder content = new StringBuilder(); + for (int i = Math.max(0, lines.size() - 1000); i < lines.size(); i++) { + content.append(lines.get(i)).append("\n"); + } + return content.toString(); + } + @Override public boolean onCommand(final PlotPlayer player, String[] args) { TaskManager.runTaskAsync(() -> { try { - final IncendoPaster incendoPaster = new IncendoPaster("plotsquared"); 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"); b.append("# Server Information\n"); - b.append("server.version: ").append(PlotSquared.get().IMP.getServerImplementation()).append("\n"); + b.append("server.version: ").append(PlotSquared.get().IMP.getServerImplementation()) + .append("\n"); b.append("online_mode: ").append(UUIDHandler.getUUIDWrapper()).append(';') .append(!Settings.UUID.OFFLINE).append('\n'); b.append("plugins:"); @@ -55,40 +67,42 @@ import java.util.List; 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.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("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"); b.append("\n# or via our Discord at https://discord.gg/ngZCzbU"); + final IncendoPaster incendoPaster = new IncendoPaster("plotsquared"); incendoPaster.addFile(new IncendoPaster.PasteFile("information", b.toString())); try { - final File logFile = new File(PlotSquared.get().IMP.getDirectory(), - "../../logs/latest.log"); + final File logFile = + new File(PlotSquared.get().IMP.getDirectory(), "../../logs/latest.log"); if (Files.size(logFile.toPath()) > 14_000_000) { throw new IOException("Too big..."); } - incendoPaster.addFile(new IncendoPaster.PasteFile("latest.log", readFile(logFile))); + incendoPaster + .addFile(new IncendoPaster.PasteFile("latest.log", readFile(logFile))); } catch (IOException ignored) { - MainUtil.sendMessage(player, - "&clatest.log is too big to be pasted, will ignore"); + MainUtil + .sendMessage(player, "&clatest.log is too big to be pasted, will ignore"); } try { - incendoPaster.addFile(new IncendoPaster.PasteFile("settings.yml", readFile(PlotSquared.get().configFile))); + incendoPaster.addFile(new IncendoPaster.PasteFile("settings.yml", + readFile(PlotSquared.get().configFile))); } catch (final IllegalArgumentException ignored) { MainUtil.sendMessage(player, "&cSkipping settings.yml because it's empty"); } try { - incendoPaster.addFile(new IncendoPaster.PasteFile("worlds.yml", readFile(PlotSquared.get().worldsFile))); + incendoPaster.addFile(new IncendoPaster.PasteFile("worlds.yml", + readFile(PlotSquared.get().worldsFile))); } catch (final IllegalArgumentException ignored) { MainUtil.sendMessage(player, "&cSkipping worlds.yml because it's empty"); } @@ -96,25 +110,30 @@ import java.util.List; incendoPaster.addFile(new IncendoPaster.PasteFile("PlotSquared.use_THIS.yml", readFile(PlotSquared.get().translationFile))); } catch (final IllegalArgumentException ignored) { - MainUtil.sendMessage(player, "&cSkipping PlotSquared.use_THIS.yml because it's empty"); + MainUtil.sendMessage(player, + "&cSkipping PlotSquared.use_THIS.yml because it's empty"); } try { final String rawResponse = incendoPaster.upload(); - final JsonObject jsonObject = new JsonParser().parse(rawResponse).getAsJsonObject(); + final JsonObject jsonObject = + new JsonParser().parse(rawResponse).getAsJsonObject(); if (jsonObject.has("created")) { final String pasteId = jsonObject.get("paste_id").getAsString(); - final String link = String.format("https://incendo.org/paste/view/%s", pasteId); - player.sendMessage( - C.DEBUG_REPORT_CREATED.s().replace("%url%", link)); + final String link = + String.format("https://athion.net/ISPaster/paste/view/%s", pasteId); + player + .sendMessage(Captions.DEBUG_REPORT_CREATED.s().replace("%url%", link)); } else { final String responseMessage = jsonObject.get("response").getAsString(); - MainUtil.sendMessage(player, String.format("&cFailed to create the debug paste: %s", responseMessage)); + MainUtil.sendMessage(player, String + .format("&cFailed to create the debug paste: %s", responseMessage)); } } catch (final Throwable throwable) { throwable.printStackTrace(); - MainUtil.sendMessage(player, "&cFailed to create the debug paste: " + throwable.getMessage()); + MainUtil.sendMessage(player, + "&cFailed to create the debug paste: " + throwable.getMessage()); } } catch (IOException e) { e.printStackTrace(); @@ -122,19 +141,4 @@ import java.util.List; }); return true; } - - private static String readFile(@NonNull final File file) throws IOException { - final StringBuilder content = new StringBuilder(); - final List lines = new ArrayList<>(); - try (final BufferedReader reader = new BufferedReader(new FileReader(file))) { - String line; - while ((line = reader.readLine()) != null) { - lines.add(line); - } - } - for (int i = Math.max(0, lines.size() - 1000); i < lines.size(); i++) { - content.append(lines.get(i)).append("\n"); - } - return content.toString(); - } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugRoadRegen.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugRoadRegen.java index 84489e88b..d6029186f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugRoadRegen.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugRoadRegen.java @@ -1,41 +1,109 @@ 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.Captions; 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.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; 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.MainUtil; -@CommandDeclaration(command = "debugroadregen", usage = "/plot debugroadregen", +import java.util.Arrays; + +@CommandDeclaration(command = "debugroadregen", usage = DebugRoadRegen.USAGE, requiredType = RequiredType.NONE, - description = "Regenerate all roads based on the road schematic", + description = "Regenerate roads in the plot or region the user is, based on the road schematic", category = CommandCategory.DEBUG, permission = "plots.debugroadregen") public class DebugRoadRegen extends SubCommand { + public static final String USAGE = "/plot debugroadregen "; @Override public boolean onCommand(PlotPlayer player, String[] args) { + if (args.length < 1) { + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, + DebugRoadRegen.USAGE); + return false; + } + String kind = args[0].toLowerCase(); + switch (kind) { + case "plot": + return regenPlot(player); + + case "region": + return regenRegion(player, Arrays.copyOfRange(args, 1, args.length)); + + default: + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, + DebugRoadRegen.USAGE); + return false; + } + } + + public boolean regenPlot(PlotPlayer player) { Location loc = player.getLocation(); - PlotArea plotArea = loc.getPlotArea(); - if (!(plotArea instanceof HybridPlotWorld)) { - return sendMessage(player, C.NOT_IN_PLOT_WORLD); + PlotArea area = loc.getPlotArea(); + if (area == null) { + return sendMessage(player, Captions.NOT_IN_PLOT_WORLD); } Plot plot = player.getCurrentPlot(); if (plot == null) { - C.NOT_IN_PLOT.send(player); + Captions.NOT_IN_PLOT.send(player); } else if (plot.isMerged()) { - C.REQUIRES_UNMERGED.send(player); + Captions.REQUIRES_UNMERGED.send(player); } else { - HybridPlotManager manager = (HybridPlotManager) plotArea.getPlotManager(); - manager.createRoadEast(plotArea, plot); - manager.createRoadSouth(plotArea, plot); - manager.createRoadSouthEast(plotArea, plot); + PlotManager manager = area.getPlotManager(); + manager.createRoadEast(plot); + manager.createRoadSouth(plot); + manager.createRoadSouthEast(plot); 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; } + + public boolean regenRegion(PlotPlayer player, String[] args) { + int height = 0; + if (args.length == 1) { + try { + height = Integer.parseInt(args[0]); + } catch (NumberFormatException ignored) { + MainUtil.sendMessage(player, Captions.NOT_VALID_NUMBER, "(0, 256)"); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, + DebugRoadRegen.USAGE); + return false; + } + } else if (args.length != 0) { + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, + DebugRoadRegen.USAGE); + return false; + } + + Location loc = player.getLocation(); + PlotArea area = loc.getPlotArea(); + if (area == null) { + return sendMessage(player, Captions.NOT_IN_PLOT_WORLD); + } + Plot plot = player.getCurrentPlot(); + PlotManager manager = area.getPlotManager(); + if (!(manager instanceof HybridPlotManager)) { + MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_WORLD); + return true; + } + 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, "&cTo regenerate all roads: /plot regenallroads"); + boolean result = HybridUtils.manager.scheduleSingleRegionRoadUpdate(plot, 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/DebugSaveTest.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/DebugSaveTest.java index fbbc3267c..0c544d096 100644 --- 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 @@ -16,14 +16,10 @@ import java.util.ArrayList; public class DebugSaveTest extends SubCommand { @Override public boolean onCommand(final PlotPlayer player, String[] args) { - ArrayList plots = new ArrayList(); - plots.addAll(PlotSquared.get().getPlots()); + ArrayList plots = new ArrayList<>(PlotSquared.get().getPlots()); MainUtil.sendMessage(player, "&6Starting `DEBUGSAVETEST`"); - DBFunc.createPlotsAndData(plots, new Runnable() { - @Override public void run() { - MainUtil.sendMessage(player, "&6Database sync finished!"); - } - }); + DBFunc.createPlotsAndData(plots, + () -> MainUtil.sendMessage(player, "&6Database sync finished!")); return true; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Delete.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Delete.java index ede1f14cd..16f10b7b0 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Delete.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Delete.java @@ -1,7 +1,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.object.*; import com.github.intellectualsites.plotsquared.plot.util.*; @@ -16,18 +16,17 @@ import com.github.intellectualsites.plotsquared.plot.util.*; // The syntax also works with any command: /plot @Override public boolean onCommand(final PlotPlayer player, String[] args) { - Location loc = player.getLocation(); final Plot plot = loc.getPlotAbs(); if (plot == null) { - return !sendMessage(player, C.NOT_IN_PLOT); + return !sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot.hasOwner()) { - return !sendMessage(player, C.PLOT_UNOWNED); + return !sendMessage(player, Captions.PLOT_UNOWNED); } if (!plot.isOwner(player.getUUID()) && !Permissions - .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DELETE)) { - return !sendMessage(player, C.NO_PLOT_PERMS); + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_DELETE)) { + return !sendMessage(player, Captions.NO_PLOT_PERMS); } final PlotArea plotArea = plot.getArea(); final java.util.Set plots = plot.getConnectedPlots(); @@ -36,7 +35,7 @@ import com.github.intellectualsites.plotsquared.plot.util.*; Runnable run = new Runnable() { @Override public void run() { if (plot.getRunning() > 0) { - MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); + MainUtil.sendMessage(player, Captions.WAIT_FOR_TIMER); return; } final long start = System.currentTimeMillis(); @@ -48,17 +47,17 @@ import com.github.intellectualsites.plotsquared.plot.util.*; double value = plots.size() * valueExr.evaluate((double) currentPlots); if (value > 0d) { EconHandler.manager.depositMoney(player, value); - sendMessage(player, C.ADDED_BALANCE, String.valueOf(value)); + sendMessage(player, Captions.ADDED_BALANCE, String.valueOf(value)); } } - MainUtil.sendMessage(player, C.DELETING_DONE, + MainUtil.sendMessage(player, Captions.DELETING_DONE, System.currentTimeMillis() - start); } }); if (result) { plot.addRunning(); } else { - MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); + MainUtil.sendMessage(player, Captions.WAIT_FOR_TIMER); } } }; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Deny.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Deny.java index e586f0656..fa6a1f96c 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Deny.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Deny.java @@ -3,20 +3,24 @@ 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.config.Captions; 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 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.PlotGameMode; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; -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) public class Deny + category = CommandCategory.SETTINGS, requiredType = RequiredType.PLAYER) public class Deny extends SubCommand { public Deny() { @@ -28,38 +32,36 @@ import java.util.UUID; Location location = player.getLocation(); Plot plot = location.getPlotAbs(); if (plot == null) { - return !sendMessage(player, C.NOT_IN_PLOT); + return !sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot.hasOwner()) { - MainUtil.sendMessage(player, C.PLOT_UNOWNED); + MainUtil.sendMessage(player, Captions.PLOT_UNOWNED); return false; } if (!plot.isOwner(player.getUUID()) && !Permissions - .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DENY)) { - MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_DENY)) { + MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return true; } Set uuids = MainUtil.getUUIDsFromString(args[0]); if (uuids.isEmpty()) { - MainUtil.sendMessage(player, C.INVALID_PLAYER, args[0]); + MainUtil.sendMessage(player, Captions.INVALID_PLAYER, args[0]); return false; } - Iterator iter = uuids.iterator(); - while (iter.hasNext()) { - UUID uuid = iter.next(); + for (UUID uuid : uuids) { 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)); + Permissions.hasPermission(player, Captions.PERMISSION_DENY_EVERYONE) || Permissions + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_DENY))) { + MainUtil.sendMessage(player, Captions.INVALID_PLAYER, MainUtil.getName(uuid)); continue; } if (plot.isOwner(uuid)) { - MainUtil.sendMessage(player, C.ALREADY_OWNER, MainUtil.getName(uuid)); + MainUtil.sendMessage(player, Captions.ALREADY_OWNER, MainUtil.getName(uuid)); return false; } if (plot.getDenied().contains(uuid)) { - MainUtil.sendMessage(player, C.ALREADY_ADDED, MainUtil.getName(uuid)); + MainUtil.sendMessage(player, Captions.ALREADY_ADDED, MainUtil.getName(uuid)); return false; } if (uuid != DBFunc.EVERYONE) { @@ -77,7 +79,7 @@ import java.util.UUID; } } if (!uuids.isEmpty()) { - MainUtil.sendMessage(player, C.DENIED_ADDED); + MainUtil.sendMessage(player, Captions.DENIED_ADDED); } return true; } @@ -97,13 +99,13 @@ import java.util.UUID; } Location loc = player.getLocation(); Location spawn = WorldUtil.IMP.getSpawn(loc.getWorld()); - MainUtil.sendMessage(player, C.YOU_GOT_DENIED); + MainUtil.sendMessage(player, Captions.YOU_GOT_DENIED); if (plot.equals(spawn.getPlot())) { 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()); + player.kick(Captions.YOU_GOT_DENIED.s()); } else { player.teleport(newSpawn); } 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 index 687eef002..d3b261ba8 100644 --- 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 @@ -1,7 +1,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.flag.FlagManager; import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.object.Plot; @@ -11,20 +11,20 @@ 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 { + requiredType = RequiredType.PLAYER) 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); + MainUtil.sendMessage(player, Captions.DESC_UNSET); return true; } boolean result = FlagManager.addPlotFlag(plot, Flags.DESCRIPTION, desc); if (!result) { - MainUtil.sendMessage(player, C.FLAG_NOT_ADDED); + MainUtil.sendMessage(player, Captions.FLAG_NOT_ADDED); return false; } - MainUtil.sendMessage(player, C.DESC_SET); + MainUtil.sendMessage(player, Captions.DESC_SET); return true; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Dislike.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Dislike.java new file mode 100644 index 000000000..372231481 --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Dislike.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.object.PlotPlayer; + +@CommandDeclaration(command = "dislike", permission = "plots.dislike", + description = "Dislike the plot", usage = "/plot dislike [next|purge]", + category = CommandCategory.INFO, requiredType = RequiredType.PLAYER) public class Dislike + extends SubCommand { + + @Override public boolean onCommand(PlotPlayer player, String[] args) { + return Like.handleLike(player, args, false); + } + +} 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 index a37c187cc..8ef920565 100644 --- 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 @@ -1,7 +1,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; @@ -22,23 +22,23 @@ import com.github.intellectualsites.plotsquared.plot.util.expiry.PlotAnalysis; Location loc = player.getLocation(); final Plot plot = loc.getPlotAbs(); if ((plot == null) || !plot.hasOwner()) { - return !sendMessage(player, C.NOT_IN_PLOT); + return !sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot.isOwner(player.getUUID()) && !Permissions - .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_DONE)) { - MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_DONE)) { + MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } if (plot.hasFlag(Flags.DONE)) { - MainUtil.sendMessage(player, C.DONE_ALREADY_DONE); + MainUtil.sendMessage(player, Captions.DONE_ALREADY_DONE); return false; } if (plot.getRunning() > 0) { - MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); + MainUtil.sendMessage(player, Captions.WAIT_FOR_TIMER); return false; } plot.addRunning(); - MainUtil.sendMessage(player, C.GENERATING_LINK); + MainUtil.sendMessage(player, Captions.GENERATING_LINK); final Settings.Auto_Clear doneRequirements = Settings.AUTO_CLEAR.get("done"); if (ExpireManager.IMP == null || doneRequirements == null) { finish(plot, player, true); @@ -60,9 +60,9 @@ import com.github.intellectualsites.plotsquared.plot.util.expiry.PlotAnalysis; if (success) { long flagValue = System.currentTimeMillis() / 1000; plot.setFlag(Flags.DONE, flagValue); - MainUtil.sendMessage(pp, C.DONE_SUCCESS); + MainUtil.sendMessage(pp, Captions.DONE_SUCCESS); } else { - MainUtil.sendMessage(pp, C.DONE_INSUFFICIENT_COMPLEXITY); + MainUtil.sendMessage(pp, Captions.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 index 7dd7b7acd..43560b81f 100644 --- 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 @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.object.Plot; @@ -21,34 +21,34 @@ import java.net.URL; @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); + return !sendMessage(player, Captions.NOT_IN_PLOT_WORLD); } final Plot plot = player.getCurrentPlot(); if (plot == null) { - return !sendMessage(player, C.NOT_IN_PLOT); + return !sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot.hasOwner()) { - MainUtil.sendMessage(player, C.PLOT_UNOWNED); + MainUtil.sendMessage(player, Captions.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); + && !Permissions.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_DOWNLOAD)) { + MainUtil.sendMessage(player, Captions.DONE_NOT_DONE); return false; } if ((!plot.isOwner(player.getUUID())) && !Permissions - .hasPermission(player, C.PERMISSION_ADMIN.s())) { - MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + .hasPermission(player, Captions.PERMISSION_ADMIN.s())) { + MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } if (plot.getRunning() > 0) { - MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); + MainUtil.sendMessage(player, Captions.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); + Captions.SCHEMATIC_TOO_LARGE.send(player); return false; } plot.addRunning(); @@ -58,7 +58,7 @@ import java.net.URL; SchematicHandler.manager.upload(value, null, null, new RunnableVal() { @Override public void run(URL url) { if (url == null) { - MainUtil.sendMessage(player, C.GENERATING_LINK_FAILED); + MainUtil.sendMessage(player, Captions.GENERATING_LINK_FAILED); return; } MainUtil.sendMessage(player, url.toString()); @@ -68,8 +68,8 @@ import java.net.URL; }); } 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); + if (!Permissions.hasPermission(player, Captions.PERMISSION_DOWNLOAD_WORLD)) { + Captions.NO_PERMISSION.send(player, Captions.PERMISSION_DOWNLOAD_WORLD); return false; } MainUtil.sendMessage(player, "&cNote: The `.mca` files are 512x512"); @@ -79,17 +79,17 @@ import java.net.URL; @Override public void run(URL url) { plot.removeRunning(); if (url == null) { - MainUtil.sendMessage(player, C.GENERATING_LINK_FAILED); + MainUtil.sendMessage(player, Captions.GENERATING_LINK_FAILED); return; } MainUtil.sendMessage(player, url.toString()); } }); } else { - C.COMMAND_SYNTAX.send(player, getUsage()); + Captions.COMMAND_SYNTAX.send(player, getUsage()); return false; } - MainUtil.sendMessage(player, C.GENERATING_LINK); + MainUtil.sendMessage(player, Captions.GENERATING_LINK); return true; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/FlagCmd.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/FlagCmd.java index d1e8c9d04..470d8d605 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/FlagCmd.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/FlagCmd.java @@ -2,14 +2,25 @@ 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.Captions; 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.flag.Flag; +import com.github.intellectualsites.plotsquared.plot.flag.FlagManager; +import com.github.intellectualsites.plotsquared.plot.flag.Flags; +import com.github.intellectualsites.plotsquared.plot.flag.IntegerFlag; +import com.github.intellectualsites.plotsquared.plot.flag.ListFlag; +import com.github.intellectualsites.plotsquared.plot.flag.PlotBlockListFlag; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; -import com.github.intellectualsites.plotsquared.plot.util.*; +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.PlotWeather; +import com.github.intellectualsites.plotsquared.plot.util.StringComparison; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; import java.util.*; @@ -21,7 +32,8 @@ import java.util.*; private boolean checkPermValue(PlotPlayer player, Flag flag, String key, String value) { key = key.toLowerCase(); value = value.toLowerCase(); - String perm = C.PERMISSION_SET_FLAG_KEY_VALUE.f(key.toLowerCase(), value.toLowerCase()); + String perm = + Captions.PERMISSION_SET_FLAG_KEY_VALUE.f(key.toLowerCase(), value.toLowerCase()); if (flag instanceof IntegerFlag && MathMan.isInteger(value)) { try { int numeric = Integer.parseInt(value); @@ -30,13 +42,39 @@ import java.util.*; int checkRange = PlotSquared.get().getPlatform().equalsIgnoreCase("bukkit") ? numeric : Settings.Limit.MAX_PLOTS; - return player.hasPermissionRange(perm, checkRange) >= numeric; + final boolean result = player.hasPermissionRange(perm, checkRange) >= numeric; + if (!result) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_SET_FLAG_KEY_VALUE + .f(key.toLowerCase(), value.toLowerCase())); + } + return result; } } catch (NumberFormatException ignore) { } + } else if (flag instanceof PlotBlockListFlag) { + final PlotBlockListFlag blockListFlag = (PlotBlockListFlag) flag; + final HashSet parsedBlocks = blockListFlag.parseValue(value); + for (final PlotBlock block : parsedBlocks) { + final String permission = Captions.PERMISSION_SET_FLAG_KEY_VALUE + .f(key.toLowerCase(), block.getRawId().toString().toLowerCase()); + final boolean result = Permissions.hasPermission(player, permission); + if (!result) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_SET_FLAG_KEY_VALUE + .f(key.toLowerCase(), value.toLowerCase())); + return false; + } + } + return true; } - return Permissions.hasPermission(player, perm); + final boolean result = Permissions.hasPermission(player, perm); + if (!result) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_SET_FLAG_KEY_VALUE.f(key.toLowerCase(), value.toLowerCase())); + } + return result; } @Override public boolean onCommand(PlotPlayer player, String[] args) { @@ -49,22 +87,24 @@ import java.util.*; * plot flag list */ if (args.length == 0) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag "); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, + "/plot flag "); return false; } Location loc = player.getLocation(); Plot plot = loc.getPlotAbs(); if (plot == null) { - MainUtil.sendMessage(player, C.NOT_IN_PLOT); + MainUtil.sendMessage(player, Captions.NOT_IN_PLOT); return false; } if (!plot.hasOwner()) { - sendMessage(player, C.PLOT_NOT_CLAIMED); + sendMessage(player, Captions.PLOT_NOT_CLAIMED); return false; } if (!plot.isOwner(player.getUUID()) && !Permissions - .hasPermission(player, C.PERMISSION_SET_FLAG_OTHER)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG_OTHER); + .hasPermission(player, Captions.PERMISSION_SET_FLAG_OTHER)) { + MainUtil + .sendMessage(player, Captions.NO_PERMISSION, Captions.PERMISSION_SET_FLAG_OTHER); return false; } Flag flag = null; @@ -77,47 +117,47 @@ import java.util.*; new StringComparison<>(args[1], Flags.getFlags()); String best = stringComparison.getBestMatch(); if (best != null) { - MainUtil.sendMessage(player, C.NOT_VALID_FLAG_SUGGESTED, best); + MainUtil.sendMessage(player, Captions.NOT_VALID_FLAG_SUGGESTED, best); suggested = true; } } catch (final Exception ignored) { /* Happens sometimes because of mean code */ } if (!suggested) { - MainUtil.sendMessage(player, C.NOT_VALID_FLAG); + MainUtil.sendMessage(player, Captions.NOT_VALID_FLAG); } return false; } } switch (args[0].toLowerCase()) { case "info": { - if (!Permissions.hasPermission(player, C.PERMISSION_SET_FLAG)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.flag.info"); + if (!Permissions.hasPermission(player, Captions.PERMISSION_SET_FLAG)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, "plots.flag.info"); return false; } if (args.length != 2) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag info "); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot flag info "); return false; } // flag key - MainUtil.sendMessage(player, C.FLAG_KEY, flag.getName()); + MainUtil.sendMessage(player, Captions.FLAG_KEY, flag.getName()); // flag type - MainUtil.sendMessage(player, C.FLAG_TYPE, flag.getClass().getSimpleName()); + MainUtil.sendMessage(player, Captions.FLAG_TYPE, flag.getClass().getSimpleName()); // Flag type description - MainUtil.sendMessage(player, C.FLAG_DESC, flag.getValueDescription()); + MainUtil.sendMessage(player, Captions.FLAG_DESC, flag.getValueDescription()); return true; } case "set": { - if (!Permissions.hasPermission(player, C.PERMISSION_SET_FLAG)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SET_FLAG); + if (!Permissions.hasPermission(player, Captions.PERMISSION_SET_FLAG)) { + MainUtil + .sendMessage(player, Captions.NO_PERMISSION, Captions.PERMISSION_SET_FLAG); return false; } if (args.length < 3) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag set "); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, + "/plot flag set "); return false; } 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())); return false; } Object parsed = flag.parseValue(value); @@ -127,33 +167,32 @@ import java.util.*; } boolean result = plot.setFlag(flag, parsed); if (!result) { - MainUtil.sendMessage(player, C.FLAG_NOT_ADDED); + MainUtil.sendMessage(player, Captions.FLAG_NOT_ADDED); return false; } - MainUtil.sendMessage(player, C.FLAG_ADDED); + MainUtil.sendMessage(player, Captions.FLAG_ADDED); return true; } case "remove": { - if (!Permissions.hasPermission(player, C.PERMISSION_FLAG_REMOVE)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_FLAG_REMOVE); + if (!Permissions.hasPermission(player, Captions.PERMISSION_FLAG_REMOVE)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_FLAG_REMOVE); return false; } if (args.length != 2 && args.length != 3) { - MainUtil - .sendMessage(player, C.COMMAND_SYNTAX, "/plot flag remove [values]"); + MainUtil.sendMessage(player, Captions.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, + Captions.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, Captions.NO_PERMISSION, + Captions.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)); return false; } } @@ -165,9 +204,19 @@ import java.util.*; if (flag1.isPresent()) { boolean o = flag1.get().removeAll((Collection) flag.parseValue(value)); if (o) { - MainUtil.sendMessage(player, C.FLAG_REMOVED); + if (flag1.get().isEmpty()) { + final boolean result = plot.removeFlag(flag); + if (result) { + MainUtil.sendMessage(player, Captions.FLAG_REMOVED); + } else { + MainUtil.sendMessage(player, Captions.FLAG_NOT_REMOVED); + } + return true; + } else { + MainUtil.sendMessage(player, Captions.FLAG_REMOVED); + } } else { - MainUtil.sendMessage(player, C.FLAG_NOT_REMOVED); + MainUtil.sendMessage(player, Captions.FLAG_NOT_REMOVED); return false; } } @@ -176,7 +225,7 @@ import java.util.*; } else { boolean result = plot.removeFlag(flag); if (!result) { - MainUtil.sendMessage(player, C.FLAG_NOT_REMOVED); + MainUtil.sendMessage(player, Captions.FLAG_NOT_REMOVED); return false; } } @@ -185,23 +234,22 @@ import java.util.*; } else if (flag == Flags.WEATHER) { player.setWeather(PlotWeather.RESET); } - MainUtil.sendMessage(player, C.FLAG_REMOVED); + MainUtil.sendMessage(player, Captions.FLAG_REMOVED); return true; } case "add": - if (!Permissions.hasPermission(player, C.PERMISSION_FLAG_ADD)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_FLAG_ADD); + if (!Permissions.hasPermission(player, Captions.PERMISSION_FLAG_ADD)) { + MainUtil + .sendMessage(player, Captions.NO_PERMISSION, Captions.PERMISSION_FLAG_ADD); return false; } if (args.length < 3) { - MainUtil - .sendMessage(player, C.COMMAND_SYNTAX, "/plot flag add "); + MainUtil.sendMessage(player, Captions.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)); return false; } } @@ -218,51 +266,52 @@ import java.util.*; if (flag1.isPresent()) { boolean o = flag1.get().addAll((Collection) parsed); if (o) { - MainUtil.sendMessage(player, C.FLAG_ADDED); + MainUtil.sendMessage(player, Captions.FLAG_ADDED); val = flag1.get(); } else { - MainUtil.sendMessage(player, C.FLAG_NOT_ADDED); + MainUtil.sendMessage(player, Captions.FLAG_NOT_ADDED); return false; } } } boolean result = plot.setFlag(flag, val); if (!result) { - MainUtil.sendMessage(player, C.FLAG_NOT_ADDED); + MainUtil.sendMessage(player, Captions.FLAG_NOT_ADDED); return false; } - MainUtil.sendMessage(player, C.FLAG_ADDED); + MainUtil.sendMessage(player, Captions.FLAG_ADDED); return true; case "list": - if (!Permissions.hasPermission(player, C.PERMISSION_FLAG_LIST)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_FLAG_LIST); + if (!Permissions.hasPermission(player, Captions.PERMISSION_FLAG_LIST)) { + MainUtil + .sendMessage(player, Captions.NO_PERMISSION, Captions.PERMISSION_FLAG_LIST); return false; } if (args.length > 1) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag list"); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot flag list"); return false; } HashMap> flags = new HashMap<>(); for (Flag flag1 : Flags.getFlags()) { String type = flag1.getClass().getSimpleName(); - if (!flags.containsKey(type)) { - flags.put(type, new ArrayList()); - } + flags.computeIfAbsent(type, k -> new ArrayList<>()); flags.get(type).add(flag1.getName()); } - String message = ""; + StringBuilder message = new StringBuilder(); String prefix = ""; for (Map.Entry> entry : flags.entrySet()) { String category = entry.getKey(); List flagNames = entry.getValue(); Collections.sort(flagNames); - message += prefix + "&6" + category + ": &7" + StringMan.join(flagNames, ", "); + message.append(prefix).append("&6").append(category).append(": &7") + .append(StringMan.join(flagNames, ", ")); prefix = "\n"; } - MainUtil.sendMessage(player, message); + MainUtil.sendMessage(player, message.toString()); return true; } - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag "); + MainUtil + .sendMessage(player, Captions.COMMAND_SYNTAX, "/plot flag "); return false; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/GenerateDocs.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/GenerateDocs.java index 5a69479b5..83161d73a 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/GenerateDocs.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/GenerateDocs.java @@ -1,7 +1,7 @@ package com.github.intellectualsites.plotsquared.plot.commands; import com.github.intellectualsites.plotsquared.commands.Command; -import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.util.StringMan; import java.io.File; @@ -142,7 +142,7 @@ public class GenerateDocs { Matcher m2 = p2.matcher(line); while (m2.find()) { - perms.add(C.valueOf("PERMISSION_" + m2.group(1)).s()); + perms.add(Captions.valueOf("PERMISSION_" + m2.group(1)).s()); } if (line.contains("Permissions.hasPermission(")) { String[] split = line.split("Permissions.hasPermission"); @@ -151,7 +151,7 @@ public class GenerateDocs { String perm = method.split("[,|)]")[1].trim(); if (!perm.equalsIgnoreCase(perm)) { if (perm.startsWith("C.")) { - perm = C.valueOf(perm.split("\\.")[1]).s(); + perm = Captions.valueOf(perm.split("\\.")[1]).s(); } else { continue; } @@ -181,7 +181,7 @@ public class GenerateDocs { String perm = method.split("[,|)]")[1].trim(); if (!perm.equalsIgnoreCase(perm)) { if (perm.startsWith("C.")) { - perm = C.valueOf(perm.split("\\.")[1]).s(); + perm = Captions.valueOf(perm.split("\\.")[1]).s(); } else { continue; } 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 index 18938f2ee..60ecbeab0 100644 --- 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 @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; @@ -27,33 +27,45 @@ import java.util.concurrent.CompletableFuture; @Override public CompletableFuture execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) throws CommandException { - checkTrue(args.length >= 1 && args.length <= 2, C.COMMAND_SYNTAX, getUsage()); + checkTrue(args.length >= 1 && args.length <= 2, Captions.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)); + if (!Permissions.hasPermission(player, Captions.PERMISSION_GRANT.f(arg0))) { + Captions.NO_PERMISSION.send(player, Captions.PERMISSION_GRANT.f(arg0)); return CompletableFuture.completedFuture(false); } if (args.length > 2) { break; } - final UUID uuid = - args.length == 2 ? UUIDHandler.getUUIDFromString(args[1]) : player.getUUID(); + final UUID uuid; + if (args.length == 2) { + uuid = UUIDHandler.getUUIDFromString(args[1]); + } else { + uuid = player.getUUID(); + } if (uuid == null) { - C.INVALID_PLAYER.send(player, args[1]); + Captions.INVALID_PLAYER.send(player, args[1]); return CompletableFuture.completedFuture(false); } 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); + int granted; + if (array == null) { + granted = 0; + } else { + granted = ByteArrayUtilities.bytesToInteger(array); + } + Captions.GRANTED_PLOTS.send(player, granted); } else { // add - int amount = - 1 + (array == null ? 0 : ByteArrayUtilities.bytesToInteger(array)); + int amount; + if (array == null) { + amount = 1; + } else { + amount = 1 + ByteArrayUtilities.bytesToInteger(array); + } boolean replace = array != null; String key = "grantedPlots"; byte[] rawData = ByteArrayUtilities.integerToBytes(amount); @@ -68,7 +80,7 @@ import java.util.concurrent.CompletableFuture; }); return CompletableFuture.completedFuture(true); } - C.COMMAND_SYNTAX.send(player, getUsage()); + Captions.COMMAND_SYNTAX.send(player, getUsage()); return CompletableFuture.completedFuture(true); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Help.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Help.java index a62d1ab6f..afd0ec320 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Help.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Help.java @@ -1,8 +1,9 @@ package com.github.intellectualsites.plotsquared.plot.commands; import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandCaller; import com.github.intellectualsites.plotsquared.commands.CommandDeclaration; -import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; @@ -20,7 +21,7 @@ public class Help extends Command { super(parent, true); } - @Override public boolean canExecute(PlotPlayer player, boolean message) { + @Override public boolean canExecute(CommandCaller player, boolean message) { return true; } @@ -50,7 +51,7 @@ public class Help extends Command { } return CompletableFuture.completedFuture(false); default: - C.COMMAND_SYNTAX.send(player, getUsage()); + Captions.COMMAND_SYNTAX.send(player, getUsage()); } return CompletableFuture.completedFuture(true); } @@ -76,10 +77,10 @@ public class Help extends Command { } if (cat == null && page == 0) { StringBuilder builder = new StringBuilder(); - builder.append(C.HELP_HEADER.s()); + builder.append(Captions.HELP_HEADER.s()); for (CommandCategory c : CommandCategory.values()) { builder.append("\n").append(StringMan - .replaceAll(C.HELP_INFO_ITEM.s(), "%category%", c.toString().toLowerCase(), + .replaceAll(Captions.HELP_INFO_ITEM.s(), "%category%", c.toString().toLowerCase(), "%category_desc%", c.toString())); } builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", "all") diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Inbox.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Inbox.java index 5c7cfc0ac..4a59850a9 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Inbox.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Inbox.java @@ -1,7 +1,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal; @@ -11,21 +11,19 @@ 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 java.util.ArrayList; import java.util.List; -import java.util.Optional; @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 + category = CommandCategory.CHAT, requiredType = RequiredType.PLAYER) public class Inbox extends SubCommand { public void displayComments(PlotPlayer player, List oldComments, int page) { if (oldComments == null || oldComments.isEmpty()) { - MainUtil.sendMessage(player, C.INBOX_EMPTY); + MainUtil.sendMessage(player, Captions.INBOX_EMPTY); return; } - PlotComment[] comments = oldComments.toArray(new PlotComment[oldComments.size()]); + PlotComment[] comments = oldComments.toArray(new PlotComment[0]); if (page < 0) { page = 0; } @@ -42,7 +40,7 @@ import java.util.Optional; } StringBuilder string = new StringBuilder(); string.append(StringMan - .replaceAll(C.COMMENT_LIST_HEADER_PAGED.s(), "%amount%", comments.length, "%cur", + .replaceAll(Captions.COMMENT_LIST_HEADER_PAGED.s(), "%amount%", comments.length, "%cur", page + 1, "%max", totalPages + 1, "%word", "all") + '\n'); // This might work xD @@ -64,15 +62,15 @@ import java.util.Optional; @Override public boolean onCommand(final PlotPlayer player, String[] args) { final Plot plot = player.getCurrentPlot(); if (plot == null) { - sendMessage(player, C.NOT_IN_PLOT); + sendMessage(player, Captions.NOT_IN_PLOT); return false; } if (!plot.hasOwner()) { - sendMessage(player, C.PLOT_UNOWNED); + sendMessage(player, Captions.PLOT_UNOWNED); return false; } if (args.length == 0) { - sendMessage(player, C.COMMAND_SYNTAX, + sendMessage(player, Captions.COMMAND_SYNTAX, "/plot inbox [inbox] [delete |clear|page]"); for (final CommentInbox inbox : CommentManager.inboxes.values()) { if (inbox.canRead(plot, player)) { @@ -95,16 +93,16 @@ import java.util.Optional; } else { color = ""; } - sendMessage(player, C.INBOX_ITEM, + sendMessage(player, Captions.INBOX_ITEM, color + inbox.toString() + " (" + total + '/' + unread + ')'); return; } } - sendMessage(player, C.INBOX_ITEM, inbox.toString()); + sendMessage(player, Captions.INBOX_ITEM, inbox.toString()); } })) { - sendMessage(player, C.INBOX_ITEM, inbox.toString()); + sendMessage(player, Captions.INBOX_ITEM, inbox.toString()); } } } @@ -112,7 +110,7 @@ import java.util.Optional; } final CommentInbox inbox = CommentManager.inboxes.get(args[0].toLowerCase()); if (inbox == null) { - sendMessage(player, C.INVALID_INBOX, + sendMessage(player, Captions.INVALID_INBOX, StringMan.join(CommentManager.inboxes.keySet(), ", ")); return false; } @@ -122,22 +120,22 @@ import java.util.Optional; switch (args[1].toLowerCase()) { case "delete": if (!inbox.canModify(plot, player)) { - sendMessage(player, C.NO_PERM_INBOX_MODIFY); + sendMessage(player, Captions.NO_PERM_INBOX_MODIFY); return false; } if (args.length != 3) { - sendMessage(player, C.COMMAND_SYNTAX, + sendMessage(player, Captions.COMMAND_SYNTAX, "/plot inbox " + inbox.toString() + " delete "); } final int index; try { index = Integer.parseInt(args[2]); if (index < 1) { - sendMessage(player, C.NOT_VALID_INBOX_INDEX, index + ""); + sendMessage(player, Captions.NOT_VALID_INBOX_INDEX, index + ""); return false; } } catch (NumberFormatException ignored) { - sendMessage(player, C.COMMAND_SYNTAX, + sendMessage(player, Captions.COMMAND_SYNTAX, "/plot inbox " + inbox.toString() + " delete "); return false; } @@ -145,36 +143,35 @@ import java.util.Optional; if (!inbox.getComments(plot, new RunnableVal>() { @Override public void run(List value) { if (index > value.size()) { - sendMessage(player, C.NOT_VALID_INBOX_INDEX, index + ""); + sendMessage(player, Captions.NOT_VALID_INBOX_INDEX, index + ""); return; } PlotComment comment = value.get(index - 1); inbox.removeComment(plot, comment); - plot.getSettings().removeComment(comment); - MainUtil.sendMessage(player, C.COMMENT_REMOVED, comment.comment); + plot.removeComment(comment); + MainUtil.sendMessage(player, Captions.COMMENT_REMOVED, comment.comment); } })) { - sendMessage(player, C.NOT_IN_PLOT); + sendMessage(player, Captions.NOT_IN_PLOT); return false; } return true; case "clear": if (!inbox.canModify(plot, player)) { - sendMessage(player, C.NO_PERM_INBOX_MODIFY); + sendMessage(player, Captions.NO_PERM_INBOX_MODIFY); } inbox.clearInbox(plot); - Optional> comments = - plot.getSettings().getComments(inbox.toString()); - if (comments.isPresent()) { - plot.getSettings().removeComments(comments.get()); + List comments = plot.getComments(inbox.toString()); + if (!comments.isEmpty()) { + plot.removeComments(comments); } - MainUtil.sendMessage(player, C.COMMENT_REMOVED, "*"); + MainUtil.sendMessage(player, Captions.COMMENT_REMOVED, "*"); return true; default: try { page = Integer.parseInt(args[1]); } catch (NumberFormatException ignored) { - sendMessage(player, C.COMMAND_SYNTAX, + sendMessage(player, Captions.COMMAND_SYNTAX, "/plot inbox [inbox] [delete |clear|page]"); return false; } @@ -183,7 +180,7 @@ import java.util.Optional; page = 1; } if (!inbox.canRead(plot, player)) { - sendMessage(player, C.NO_PERM_INBOX); + sendMessage(player, Captions.NO_PERM_INBOX); return false; } if (!inbox.getComments(plot, new RunnableVal>() { @@ -191,7 +188,7 @@ import java.util.Optional; displayComments(player, value, page); } })) { - sendMessage(player, C.PLOT_UNOWNED); + sendMessage(player, Captions.PLOT_UNOWNED); return false; } return true; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Info.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Info.java index 6241e1d51..51e5cd6c0 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Info.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Info.java @@ -1,8 +1,10 @@ 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.Captions; +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.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; @@ -10,8 +12,8 @@ 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) public class Info - extends SubCommand { + usage = "/plot info [-f, to force info]", category = CommandCategory.INFO) +public class Info extends SubCommand { @Override public boolean onCommand(final PlotPlayer player, String[] args) { Plot plot; @@ -31,6 +33,7 @@ import java.util.UUID; case "seen": case "owner": case "rating": + case "likes": plot = MainUtil.getPlotFromString(player, null, false); break; default: @@ -50,9 +53,10 @@ import java.util.UUID; plot = player.getCurrentPlot(); } if (plot == null) { - MainUtil.sendMessage(player, C.NOT_IN_PLOT.s()); + MainUtil.sendMessage(player, Captions.NOT_IN_PLOT.s()); return false; } + if (arg != null) { if (args.length == 1) { args = new String[0]; @@ -60,6 +64,26 @@ import java.util.UUID; args = new String[] {args[1]}; } } + + // hide-info flag + if (plot.getFlag(Flags.HIDE_INFO).orElse(false)) { + boolean allowed = false; + for (final String argument : args) { + if (argument.equalsIgnoreCase("-f")) { + if (!player.hasPermission(Captions.PERMISSION_AREA_INFO_FORCE.s())) { + Captions.NO_PERMISSION.send(player, Captions.PERMISSION_AREA_INFO_FORCE); + return true; + } + allowed = true; + break; + } + } + if (!allowed) { + Captions.PLOT_INFO_HIDDEN.send(player); + return true; + } + } + if (args.length == 1 && args[0].equalsIgnoreCase("inv")) { PlotInventory inv = new PlotInventory(player) { @Override public boolean onClick(int index) { @@ -69,7 +93,7 @@ import java.util.UUID; } }; UUID uuid = player.getUUID(); - String name = MainUtil.getName(plot.owner); + String name = MainUtil.getName(plot.getOwner()); inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cPlot Info", "&cID: &6" + plot.getId().toString(), "&cOwner: &6" + name, "&cAlias: &6" + plot.getAlias(), @@ -97,18 +121,24 @@ import java.util.UUID; 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, Captions.PLOT_INFO_UNCLAIMED, + plot.getId().x + ";" + plot.getId().y); return true; } - String info = C.PLOT_INFO.s(); + String info = Captions.PLOT_INFO.s(); boolean full; if (arg != null) { 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"); + if (Settings.Ratings.USE_LIKES) { + 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, " + " &alikes"); + } else { + 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"); + } return false; } full = true; @@ -118,7 +148,8 @@ import java.util.UUID; 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); + Captions.PLOT_INFO_HEADER.s() + '\n' + value + '\n' + Captions.PLOT_INFO_FOOTER + .s(), false); } }); return true; @@ -127,27 +158,29 @@ import java.util.UUID; private String getCaption(String string) { switch (string) { case "trusted": - return C.PLOT_INFO_TRUSTED.s(); + return Captions.PLOT_INFO_TRUSTED.s(); case "alias": - return C.PLOT_INFO_ALIAS.s(); + return Captions.PLOT_INFO_ALIAS.s(); case "biome": - return C.PLOT_INFO_BIOME.s(); + return Captions.PLOT_INFO_BIOME.s(); case "denied": - return C.PLOT_INFO_DENIED.s(); + return Captions.PLOT_INFO_DENIED.s(); case "flags": - return C.PLOT_INFO_FLAGS.s(); + return Captions.PLOT_INFO_FLAGS.s(); case "id": - return C.PLOT_INFO_ID.s(); + return Captions.PLOT_INFO_ID.s(); case "size": - return C.PLOT_INFO_SIZE.s(); + return Captions.PLOT_INFO_SIZE.s(); case "members": - return C.PLOT_INFO_MEMBERS.s(); + return Captions.PLOT_INFO_MEMBERS.s(); case "owner": - return C.PLOT_INFO_OWNER.s(); + return Captions.PLOT_INFO_OWNER.s(); case "rating": - return C.PLOT_INFO_RATING.s(); + return Captions.PLOT_INFO_RATING.s(); + case "likes": + return Captions.PLOT_INFO_LIKES.s(); case "seen": - return C.PLOT_INFO_SEEN.s(); + return Captions.PLOT_INFO_SEEN.s(); default: return null; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Kick.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Kick.java index fc16db715..b749eaba4 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Kick.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Kick.java @@ -3,7 +3,7 @@ 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.config.Captions; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; @@ -19,7 +19,7 @@ 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) public class Kick extends SubCommand { + requiredType = RequiredType.PLAYER) public class Kick extends SubCommand { public Kick() { super(Argument.PlayerName); @@ -29,16 +29,16 @@ import java.util.UUID; Location location = player.getLocation(); Plot plot = location.getPlot(); if (plot == null) { - return !sendMessage(player, C.NOT_IN_PLOT); + return !sendMessage(player, Captions.NOT_IN_PLOT); } if ((!plot.hasOwner() || !plot.isOwner(player.getUUID())) && !Permissions - .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_KICK)) { - MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_KICK)) { + MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } Set uuids = MainUtil.getUUIDsFromString(args[0]); if (uuids.isEmpty()) { - MainUtil.sendMessage(player, C.INVALID_PLAYER, args[0]); + MainUtil.sendMessage(player, Captions.INVALID_PLAYER, args[0]); return false; } Set players = new HashSet<>(); @@ -46,7 +46,7 @@ import java.util.UUID; if (uuid == DBFunc.EVERYONE) { for (PlotPlayer pp : plot.getPlayersInPlot()) { if (pp == player || Permissions - .hasPermission(pp, C.PERMISSION_ADMIN_ENTRY_DENIED)) { + .hasPermission(pp, Captions.PERMISSION_ADMIN_ENTRY_DENIED)) { continue; } players.add(pp); @@ -60,26 +60,26 @@ import java.util.UUID; } players.remove(player); // Don't ever kick the calling player if (players.isEmpty()) { - MainUtil.sendMessage(player, C.INVALID_PLAYER, args[0]); + MainUtil.sendMessage(player, Captions.INVALID_PLAYER, args[0]); return false; } for (PlotPlayer player2 : players) { if (!plot.equals(player2.getCurrentPlot())) { - MainUtil.sendMessage(player, C.INVALID_PLAYER, args[0]); + MainUtil.sendMessage(player, Captions.INVALID_PLAYER, args[0]); return false; } - if (Permissions.hasPermission(player2, C.PERMISSION_ADMIN_ENTRY_DENIED)) { - C.CANNOT_KICK_PLAYER.send(player, player2.getName()); + if (Permissions.hasPermission(player2, Captions.PERMISSION_ADMIN_ENTRY_DENIED)) { + Captions.CANNOT_KICK_PLAYER.send(player, player2.getName()); return false; } Location spawn = WorldUtil.IMP.getSpawn(location.getWorld()); - C.YOU_GOT_KICKED.send(player2); + Captions.YOU_GOT_KICKED.send(player2); if (plot.equals(spawn.getPlot())) { 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()); + player2.kick(Captions.YOU_GOT_KICKED.s()); } else { player2.plotkick(newSpawn); } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Leave.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Leave.java index cf49be592..cbc227bd3 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Leave.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Leave.java @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; @@ -24,12 +24,12 @@ import java.util.concurrent.CompletableFuture; @Override public CompletableFuture 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); - checkTrue(args.length == 0, C.COMMAND_SYNTAX, getUsage()); + final Plot plot = check(player.getCurrentPlot(), Captions.NOT_IN_PLOT); + checkTrue(plot.hasOwner(), Captions.PLOT_UNOWNED); + checkTrue(plot.isAdded(player.getUUID()), Captions.NO_PLOT_PERMS); + checkTrue(args.length == 0, Captions.COMMAND_SYNTAX, getUsage()); if (plot.isOwner(player.getUUID())) { - checkTrue(plot.hasOwner(), C.ALREADY_OWNER); + checkTrue(plot.hasOwner(), Captions.ALREADY_OWNER); // TODO setowner, other } else { UUID uuid = player.getUUID(); @@ -40,9 +40,9 @@ import java.util.concurrent.CompletableFuture; if (plot.removeMember(uuid)) { EventUtil.manager.callMember(player, plot, uuid, false); } - MainUtil.sendMessage(player, C.INVALID_PLAYER, args[0]); + MainUtil.sendMessage(player, Captions.INVALID_PLAYER, args[0]); } else { - MainUtil.sendMessage(player, C.REMOVED_PLAYERS, 1); + MainUtil.sendMessage(player, Captions.REMOVED_PLAYERS, 1); } } return CompletableFuture.completedFuture(true); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Like.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Like.java new file mode 100644 index 000000000..f839a9b1a --- /dev/null +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Like.java @@ -0,0 +1,147 @@ +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.Captions; +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.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.Rating; +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.TaskManager; + +import java.util.*; + +@CommandDeclaration(command = "like", permission = "plots.like", description = "Like the plot", + usage = "/plot like [next|purge]", category = CommandCategory.INFO, + requiredType = RequiredType.PLAYER) public class Like extends SubCommand { + + protected static boolean handleLike(final PlotPlayer player, String[] args, + final boolean like) { + final UUID uuid = player.getUUID(); + if (args.length == 1) { + switch (args[0].toLowerCase()) { + case "next": { + final List plots = new ArrayList<>(PlotSquared.get().getBasePlots()); + plots.sort((p1, p2) -> { + double v1 = getLikesPercentage(p1); + double v2 = getLikesPercentage(p2); + if (v1 == v2) { + return -0; + } + return v2 > v1 ? 1 : -1; + }); + for (final Plot plot : plots) { + if ((!Settings.Done.REQUIRED_FOR_RATINGS || plot.hasFlag(Flags.DONE)) + && plot.isBasePlot() && (!plot.getLikes().containsKey(uuid))) { + plot.teleportPlayer(player); + MainUtil.sendMessage(player, Captions.RATE_THIS); + return true; + } + } + MainUtil.sendMessage(player, Captions.FOUND_NO_PLOTS); + return true; + } + case "purge": { + final Plot plot = player.getCurrentPlot(); + if (plot == null) { + return !sendMessage(player, Captions.NOT_IN_PLOT); + } + if (!Permissions + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_RATE, true)) { + return false; + } + plot.clearRatings(); + Captions.RATINGS_PURGED.send(player); + return true; + } + } + } + final Plot plot = player.getCurrentPlot(); + if (plot == null) { + return !sendMessage(player, Captions.NOT_IN_PLOT); + } + if (!plot.hasOwner()) { + sendMessage(player, Captions.RATING_NOT_OWNED); + return false; + } + if (plot.isOwner(player.getUUID())) { + sendMessage(player, Captions.RATING_NOT_YOUR_OWN); + return false; + } + if (Settings.Done.REQUIRED_FOR_RATINGS && !plot.hasFlag(Flags.DONE)) { + sendMessage(player, Captions.RATING_NOT_DONE); + return false; + } + final Runnable run = () -> { + final Boolean oldRating = plot.getLikes().get(uuid); + if (oldRating != null) { + sendMessage(player, Captions.RATING_ALREADY_EXISTS, plot.getId().toString()); + return; + } + final int rating; + if (like) { + rating = 10; + } else { + rating = 1; + } + plot.addRating(uuid, new Rating(rating)); + final Rating result = EventUtil.manager.callRating(player, plot, new Rating(rating)); + if (result != null) { + plot.addRating(uuid, result); + if (like) { + sendMessage(player, Captions.RATING_LIKED, plot.getId().toString()); + } else { + sendMessage(player, Captions.RATING_DISLIKED, plot.getId().toString()); + } + } + }; + if (plot.getSettings().ratings == null) { + if (!Settings.Enabled_Components.RATING_CACHE) { + TaskManager.runTaskAsync(() -> { + plot.getSettings().ratings = DBFunc.getRatings(plot); + run.run(); + }); + return true; + } + plot.getSettings().ratings = new HashMap<>(); + } + run.run(); + return true; + } + + /** + * Get the likes to dislike ratio of a plot as a percentage (in decimal form) + * + * @return likes to dislike ratio, returns zero if the plot has no likes + */ + public static double getLikesPercentage(final Plot plot) { + if (!plot.hasRatings()) { + return 0; + } + final Collection reactions = plot.getLikes().values(); + double numLikes = 0, numDislikes = 0; + for (final boolean reaction : reactions) { + if (reaction) { + numLikes += 1; + } else { + numDislikes += 1; + } + } + if (numLikes == 0 && numDislikes == 0) { + return 0D; + } else if (numDislikes == 0) { + return 1.0D; + } + return numLikes / (numLikes + numDislikes); + } + + @Override public boolean onCommand(PlotPlayer player, String[] args) { + return handleLike(player, args, true); + } + +} diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/ListCmd.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/ListCmd.java index 9df74d30b..81834c353 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/ListCmd.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/ListCmd.java @@ -3,14 +3,24 @@ 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.config.Captions; import com.github.intellectualsites.plotsquared.plot.flag.Flags; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotMessage; +import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; +import com.github.intellectualsites.plotsquared.plot.object.Rating; +import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; import com.github.intellectualsites.plotsquared.plot.util.*; import com.github.intellectualsites.plotsquared.plot.util.expiry.ExpireManager; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; import java.util.Map.Entry; +import java.util.Optional; +import java.util.UUID; @CommandDeclaration(command = "list", aliases = {"l", "find", "search"}, description = "List plots", permission = "plots.list", category = CommandCategory.INFO, @@ -20,43 +30,43 @@ 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)) { + .hasPermission(player, Captions.PERMISSION_LIST_FOR_SALE)) { args.add("forsale"); } - if (Permissions.hasPermission(player, C.PERMISSION_LIST_MINE)) { + if (Permissions.hasPermission(player, Captions.PERMISSION_LIST_MINE)) { args.add("mine"); } - if (Permissions.hasPermission(player, C.PERMISSION_LIST_SHARED)) { + if (Permissions.hasPermission(player, Captions.PERMISSION_LIST_SHARED)) { args.add("shared"); } - if (Permissions.hasPermission(player, C.PERMISSION_LIST_WORLD)) { + if (Permissions.hasPermission(player, Captions.PERMISSION_LIST_WORLD)) { args.add("world"); } - if (Permissions.hasPermission(player, C.PERMISSION_LIST_TOP)) { + if (Permissions.hasPermission(player, Captions.PERMISSION_LIST_TOP)) { args.add("top"); } - if (Permissions.hasPermission(player, C.PERMISSION_LIST_ALL)) { + if (Permissions.hasPermission(player, Captions.PERMISSION_LIST_ALL)) { args.add("all"); } - if (Permissions.hasPermission(player, C.PERMISSION_LIST_UNOWNED)) { + if (Permissions.hasPermission(player, Captions.PERMISSION_LIST_UNOWNED)) { args.add("unowned"); } - if (Permissions.hasPermission(player, C.PERMISSION_LIST_UNKNOWN)) { + if (Permissions.hasPermission(player, Captions.PERMISSION_LIST_UNKNOWN)) { args.add("unknown"); } - if (Permissions.hasPermission(player, C.PERMISSION_LIST_PLAYER)) { + if (Permissions.hasPermission(player, Captions.PERMISSION_LIST_PLAYER)) { args.add(""); } - if (Permissions.hasPermission(player, C.PERMISSION_LIST_WORLD)) { + if (Permissions.hasPermission(player, Captions.PERMISSION_LIST_WORLD)) { args.add(""); } - if (Permissions.hasPermission(player, C.PERMISSION_LIST_DONE)) { + if (Permissions.hasPermission(player, Captions.PERMISSION_LIST_DONE)) { args.add("done"); } - if (Permissions.hasPermission(player, C.PERMISSION_LIST_EXPIRED)) { + if (Permissions.hasPermission(player, Captions.PERMISSION_LIST_EXPIRED)) { args.add("expired"); } - if (Permissions.hasPermission(player, C.PERMISSION_LIST_FUZZY)) { + if (Permissions.hasPermission(player, Captions.PERMISSION_LIST_FUZZY)) { args.add("fuzzy "); } return args.toArray(new String[args.size()]); @@ -64,7 +74,7 @@ public class ListCmd extends SubCommand { public void noArgs(PlotPlayer player) { MainUtil.sendMessage(player, - C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + Arrays.toString(getArgumentList(player))); + Captions.SUBCOMMAND_SET_OPTIONS_HEADER.s() + Arrays.toString(getArgumentList(player))); } @Override public boolean onCommand(PlotPlayer player, String[] args) { @@ -93,16 +103,18 @@ public class ListCmd extends SubCommand { boolean sort = true; switch (arg) { case "mine": - if (!Permissions.hasPermission(player, C.PERMISSION_LIST_MINE)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_MINE); + if (!Permissions.hasPermission(player, Captions.PERMISSION_LIST_MINE)) { + MainUtil + .sendMessage(player, Captions.NO_PERMISSION, Captions.PERMISSION_LIST_MINE); return false; } sort = false; plots = PlotSquared.get().sortPlotsByTemp(PlotSquared.get().getBasePlots(player)); break; case "shared": - if (!Permissions.hasPermission(player, C.PERMISSION_LIST_SHARED)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_SHARED); + if (!Permissions.hasPermission(player, Captions.PERMISSION_LIST_SHARED)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_LIST_SHARED); return false; } plots = new ArrayList<>(); @@ -114,20 +126,23 @@ public class ListCmd extends SubCommand { } break; case "world": - if (!Permissions.hasPermission(player, C.PERMISSION_LIST_WORLD)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_WORLD); + if (!Permissions.hasPermission(player, Captions.PERMISSION_LIST_WORLD)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_LIST_WORLD); 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)); + if (!Permissions + .hasPermission(player, Captions.PERMISSION_LIST_WORLD_NAME.f(world))) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_LIST_WORLD_NAME.f(world)); return false; } 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); + if (!Permissions.hasPermission(player, Captions.PERMISSION_LIST_EXPIRED)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_LIST_EXPIRED); return false; } plots = ExpireManager.IMP == null ? @@ -135,27 +150,31 @@ public class ListCmd extends SubCommand { new ArrayList<>(ExpireManager.IMP.getPendingExpired()); break; case "area": - if (!Permissions.hasPermission(player, C.PERMISSION_LIST_AREA)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_AREA); + if (!Permissions.hasPermission(player, Captions.PERMISSION_LIST_AREA)) { + MainUtil + .sendMessage(player, Captions.NO_PERMISSION, Captions.PERMISSION_LIST_AREA); 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)); + if (!Permissions + .hasPermission(player, Captions.PERMISSION_LIST_WORLD_NAME.f(world))) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_LIST_WORLD_NAME.f(world)); return false; } plots = area == null ? new ArrayList() : new ArrayList<>(area.getPlots()); break; case "all": - if (!Permissions.hasPermission(player, C.PERMISSION_LIST_ALL)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_ALL); + if (!Permissions.hasPermission(player, Captions.PERMISSION_LIST_ALL)) { + MainUtil + .sendMessage(player, Captions.NO_PERMISSION, Captions.PERMISSION_LIST_ALL); return false; } plots = new ArrayList<>(PlotSquared.get().getPlots()); break; case "done": - if (!Permissions.hasPermission(player, C.PERMISSION_LIST_DONE)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_DONE); + if (!Permissions.hasPermission(player, Captions.PERMISSION_LIST_DONE)) { + MainUtil + .sendMessage(player, Captions.NO_PERMISSION, Captions.PERMISSION_LIST_DONE); return false; } plots = new ArrayList<>(); @@ -165,60 +184,56 @@ public class ListCmd extends SubCommand { plots.add(plot); } } - Collections.sort(plots, new Comparator() { - @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)) { - if (MathMan.isInteger(vb)) { - return Integer.parseInt(vb) - Integer.parseInt(va); - } - return -1; + plots.sort((a, b) -> { + String va = "" + a.getFlags().get(Flags.DONE); + String vb = "" + b.getFlags().get(Flags.DONE); + if (MathMan.isInteger(va)) { + if (MathMan.isInteger(vb)) { + return Integer.parseInt(vb) - Integer.parseInt(va); } - return 1; + return -1; } + return 1; }); sort = false; break; case "top": - if (!Permissions.hasPermission(player, C.PERMISSION_LIST_TOP)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_TOP); + if (!Permissions.hasPermission(player, Captions.PERMISSION_LIST_TOP)) { + MainUtil + .sendMessage(player, Captions.NO_PERMISSION, Captions.PERMISSION_LIST_TOP); return false; } plots = new ArrayList<>(PlotSquared.get().getPlots()); - Collections.sort(plots, new Comparator() { - @Override public int compare(Plot p1, Plot p2) { - double v1 = 0; - int p1s = p1.getSettings().getRatings().size(); - int p2s = p2.getRatings().size(); - if (!p1.getSettings().getRatings().isEmpty()) { - for (Entry entry : p1.getRatings().entrySet()) { - double av = entry.getValue().getAverageRating(); - v1 += av * av; - } - v1 /= p1s; - v1 += p1s; - } - double v2 = 0; - if (!p2.getSettings().getRatings().isEmpty()) { - for (Entry entry : p2.getRatings().entrySet()) { - double av = entry.getValue().getAverageRating(); - v2 += av * av; - } - v2 /= p2s; - v2 += p2s; - } - if (v2 == v1 && v2 != 0) { - return p2s - p1s; - } - return (int) Math.signum(v2 - v1); + plots.sort((p1, p2) -> { + double v1 = 0; + int p1s = p1.getSettings().getRatings().size(); + int p2s = p2.getRatings().size(); + if (!p1.getSettings().getRatings().isEmpty()) { + v1 = p1.getRatings().values().stream().mapToDouble(Rating::getAverageRating) + .map(av -> av * av).sum(); + v1 /= p1s; + v1 += p1s; } + double v2 = 0; + if (!p2.getSettings().getRatings().isEmpty()) { + for (Entry entry : p2.getRatings().entrySet()) { + double av = entry.getValue().getAverageRating(); + v2 += av * av; + } + v2 /= p2s; + v2 += p2s; + } + if (v2 == v1 && v2 != 0) { + return p2s - p1s; + } + return (int) Math.signum(v2 - v1); }); sort = false; break; case "forsale": - if (!Permissions.hasPermission(player, C.PERMISSION_LIST_FORSALE)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_FORSALE); + if (!Permissions.hasPermission(player, Captions.PERMISSION_LIST_FOR_SALE)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_LIST_FOR_SALE); return false; } if (EconHandler.manager == null) { @@ -233,39 +248,42 @@ public class ListCmd extends SubCommand { } break; case "unowned": - if (!Permissions.hasPermission(player, C.PERMISSION_LIST_UNOWNED)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_UNOWNED); + if (!Permissions.hasPermission(player, Captions.PERMISSION_LIST_UNOWNED)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_LIST_UNOWNED); return false; } plots = new ArrayList<>(); for (Plot plot : PlotSquared.get().getPlots()) { - if (plot.owner == null) { + if (plot.getOwner() == null) { plots.add(plot); } } break; case "unknown": - if (!Permissions.hasPermission(player, C.PERMISSION_LIST_UNKNOWN)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_UNKNOWN); + if (!Permissions.hasPermission(player, Captions.PERMISSION_LIST_UNKNOWN)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_LIST_UNKNOWN); return false; } plots = new ArrayList<>(); for (Plot plot : PlotSquared.get().getPlots()) { - if (plot.owner == null) { + if (plot.getOwner() == null) { continue; } - if (UUIDHandler.getName(plot.owner) == null) { + if (UUIDHandler.getName(plot.getOwner()) == null) { plots.add(plot); } } break; case "fuzzy": - if (!Permissions.hasPermission(player, C.PERMISSION_LIST_FUZZY)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_FUZZY); + if (!Permissions.hasPermission(player, Captions.PERMISSION_LIST_FUZZY)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_LIST_FUZZY); return false; } if (args.length < (page == -1 ? 2 : 3)) { - C.COMMAND_SYNTAX.send(player, "/plot list fuzzy [#]"); + Captions.COMMAND_SYNTAX.send(player, "/plot list fuzzy [#]"); return false; } String term; @@ -279,14 +297,15 @@ public class ListCmd extends SubCommand { break; default: if (PlotSquared.get().hasPlotArea(args[0])) { - if (!Permissions.hasPermission(player, C.PERMISSION_LIST_WORLD)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_WORLD); + if (!Permissions.hasPermission(player, Captions.PERMISSION_LIST_WORLD)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.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])); + .hasPermission(player, Captions.PERMISSION_LIST_WORLD_NAME.f(args[0]))) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_LIST_WORLD_NAME.f(args[0])); return false; } plots = new ArrayList<>(PlotSquared.get().getPlots(args[0])); @@ -300,8 +319,9 @@ public class ListCmd extends SubCommand { } } if (uuid != null) { - if (!Permissions.hasPermission(player, C.PERMISSION_LIST_PLAYER)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_LIST_PLAYER); + if (!Permissions.hasPermission(player, Captions.PERMISSION_LIST_PLAYER)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_LIST_PLAYER); return false; } sort = false; @@ -311,14 +331,14 @@ public class ListCmd extends SubCommand { } if (plots == null) { - sendMessage(player, C.DID_YOU_MEAN, + sendMessage(player, Captions.DID_YOU_MEAN, new StringComparison<>(args[0], new String[] {"mine", "shared", "world", "all"}) .getBestMatch()); return false; } if (plots.isEmpty()) { - MainUtil.sendMessage(player, C.FOUND_NO_PLOTS); + MainUtil.sendMessage(player, Captions.FOUND_NO_PLOTS); return false; } displayPlots(player, plots, 12, page, area, args, sort); @@ -341,7 +361,7 @@ public class ListCmd extends SubCommand { new RunnableVal3() { @Override public void run(Integer i, Plot plot, PlotMessage message) { String color; - if (plot.owner == null) { + if (plot.getOwner() == null) { color = "$3"; } else if (plot.isOwner(player.getUUID())) { color = "$1"; @@ -352,18 +372,20 @@ public class ListCmd extends SubCommand { } else { color = "$1"; } - PlotMessage trusted = new PlotMessage().text(C.color(C.PLOT_INFO_TRUSTED.s() - .replaceAll("%trusted%", MainUtil.getPlayerList(plot.getTrusted())))) + PlotMessage trusted = new PlotMessage().text(Captions.color( + Captions.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())))) + PlotMessage members = new PlotMessage().text(Captions.color( + Captions.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(); + strFlags = Captions.NONE.s(); } - PlotMessage flags = new PlotMessage() - .text(C.color(C.PLOT_INFO_FLAGS.s().replaceAll("%flags%", strFlags))) + PlotMessage flags = new PlotMessage().text(Captions + .color(Captions.PLOT_INFO_FLAGS.s().replaceAll("%flags%", strFlags))) .color("$1"); message.text("[").color("$3").text(i + "") .command("/plot visit " + plot.getArea() + ";" + plot.getId()) @@ -391,7 +413,7 @@ public class ListCmd extends SubCommand { prefix = ", "; } } - }, "/plot list " + args[0], C.PLOT_LIST_HEADER_PAGED.s()); + }, "/plot list " + args[0], Captions.PLOT_LIST_HEADER_PAGED.s()); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Load.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Load.java index cc9106d28..d18332798 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Load.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Load.java @@ -2,9 +2,13 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; -import com.github.intellectualsites.plotsquared.plot.object.*; +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.RunnableVal; 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; @@ -22,23 +26,23 @@ import java.util.List; @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); + return !sendMessage(player, Captions.NOT_IN_PLOT_WORLD); } final Plot plot = player.getCurrentPlot(); if (plot == null) { - return !sendMessage(player, C.NOT_IN_PLOT); + return !sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot.hasOwner()) { - MainUtil.sendMessage(player, C.PLOT_UNOWNED); + MainUtil.sendMessage(player, Captions.PLOT_UNOWNED); return false; } if (!plot.isOwner(player.getUUID()) && !Permissions - .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_LOAD)) { - MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_LOAD)) { + MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } if (plot.getRunning() > 0) { - MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); + MainUtil.sendMessage(player, Captions.WAIT_FOR_TIMER); return false; } @@ -47,46 +51,46 @@ import java.util.List; List schematics = player.getMeta("plot_schematics"); if (schematics == null) { // No schematics found: - MainUtil.sendMessage(player, C.LOAD_NULL); + MainUtil.sendMessage(player, Captions.LOAD_NULL); return false; } - String schem; + String schematic; try { - schem = schematics.get(Integer.parseInt(args[0]) - 1); + 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, Captions.NOT_VALID_NUMBER, + "(1, " + schematics.size() + ')'); return false; } final URL url; try { - url = new URL(Settings.Web.URL + "saves/" + player.getUUID() + '/' + schem); + url = new URL(Settings.Web.URL + "saves/" + player.getUUID() + '/' + schematic); } catch (MalformedURLException e) { e.printStackTrace(); - MainUtil.sendMessage(player, C.LOAD_FAILED); + MainUtil.sendMessage(player, Captions.LOAD_FAILED); return false; } plot.addRunning(); - MainUtil.sendMessage(player, C.GENERATING_COMPONENT); + MainUtil.sendMessage(player, Captions.GENERATING_COMPONENT); TaskManager.runTaskAsync(() -> { - Schematic schematic = SchematicHandler.manager.getSchematic(url); - if (schematic == null) { + Schematic taskSchematic = SchematicHandler.manager.getSchematic(url); + if (taskSchematic == null) { plot.removeRunning(); - sendMessage(player, C.SCHEMATIC_INVALID, + sendMessage(player, Captions.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, + .paste(taskSchematic, 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); + sendMessage(player, Captions.SCHEMATIC_PASTE_SUCCESS); } else { - sendMessage(player, C.SCHEMATIC_PASTE_FAILED); + sendMessage(player, Captions.SCHEMATIC_PASTE_FAILED); } } }); @@ -94,7 +98,7 @@ import java.util.List; return true; } plot.removeRunning(); - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot load "); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot load "); return false; } @@ -107,7 +111,7 @@ import java.util.List; List schematics1 = SchematicHandler.manager.getSaves(player.getUUID()); plot.removeRunning(); if ((schematics1 == null) || schematics1.isEmpty()) { - MainUtil.sendMessage(player, C.LOAD_FAILED); + MainUtil.sendMessage(player, Captions.LOAD_FAILED); return; } player.setMeta("plot_schematics", schematics1); @@ -141,7 +145,7 @@ import java.util.List; e.printStackTrace(); } } - MainUtil.sendMessage(player, C.LOAD_LIST); + MainUtil.sendMessage(player, Captions.LOAD_LIST); } public String secToTime(long time) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/MainCommand.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/MainCommand.java index c50c5a221..31e599976 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/MainCommand.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/MainCommand.java @@ -1,9 +1,10 @@ package com.github.intellectualsites.plotsquared.plot.commands; import com.github.intellectualsites.plotsquared.commands.Command; +import com.github.intellectualsites.plotsquared.commands.CommandCaller; 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.Captions; +import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.object.*; import com.github.intellectualsites.plotsquared.plot.util.CmdConfirm; import com.github.intellectualsites.plotsquared.plot.util.EconHandler; @@ -69,7 +70,6 @@ public class MainCommand extends Command { new DebugPaste(); new Unlink(); new Kick(); - new Rate(); new DebugClaimTest(); new Inbox(); new Comment(); @@ -99,6 +99,14 @@ public class MainCommand extends Command { new SetHome(); new Cluster(); new DebugImportWorlds(); + + if (Settings.Ratings.USE_LIKES) { + new Like(); + new Dislike(); + } else { + new Rate(); + } + // Referenced commands instance.toggle = new Toggle(); instance.help = new Help(instance); @@ -131,10 +139,8 @@ 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; + 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) { @@ -181,13 +187,6 @@ public class MainCommand extends Command { return true; } - @Deprecated - /** - * @Deprecated legacy - */ public void addCommand(SubCommand command) { - PlotSquared.debug("Command registration is now done during instantiation"); - } - @Override public CompletableFuture execute(final PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { @@ -201,8 +200,8 @@ public class MainCommand extends Command { 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())) { + .equals(area) || Permissions.hasPermission(player, Captions.PERMISSION_ADMIN)) + && !newPlot.isDenied(player.getUUID())) { Location newLoc = newPlot.getCenter(); if (player.canTeleport(newLoc)) { // Save meta @@ -213,7 +212,7 @@ public class MainCommand extends Command { player.setMeta(PlotPlayer.META_LOCATION, newLoc); player.setMeta(PlotPlayer.META_LAST_PLOT, newPlot); } else { - C.BORDER.send(player); + Captions.BORDER.send(player); } // Trim command args = Arrays.copyOfRange(args, 1, args.length); @@ -243,7 +242,7 @@ public class MainCommand extends Command { }; args = Arrays.copyOfRange(args, 1, args.length); } else { - C.INVALID_COMMAND_FLAG.send(player); + Captions.INVALID_COMMAND_FLAG.send(player); return CompletableFuture.completedFuture(false); } } @@ -256,9 +255,9 @@ public class MainCommand extends Command { e.printStackTrace(); String message = e.getLocalizedMessage(); if (message != null) { - C.ERROR.send(player, message); + Captions.ERROR.send(player, message); } else { - C.ERROR.send(player); + Captions.ERROR.send(player); } } // Reset command scope // @@ -277,7 +276,7 @@ public class MainCommand extends Command { return CompletableFuture.completedFuture(true); } - @Override public boolean canExecute(PlotPlayer player, boolean message) { + @Override public boolean canExecute(CommandCaller player, boolean message) { return true; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Merge.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Merge.java index 42075f2d2..2e68b739c 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Merge.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Merge.java @@ -1,10 +1,19 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; -import com.github.intellectualsites.plotsquared.plot.object.*; -import com.github.intellectualsites.plotsquared.plot.util.*; +import com.github.intellectualsites.plotsquared.plot.object.Expression; +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.CmdConfirm; +import com.github.intellectualsites.plotsquared.plot.util.EconHandler; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; import java.util.UUID; @@ -43,35 +52,34 @@ public class Merge extends SubCommand { Location loc = player.getLocationFull(); final Plot plot = loc.getPlotAbs(); if (plot == null) { - return !sendMessage(player, C.NOT_IN_PLOT); + return !sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot.hasOwner()) { - MainUtil.sendMessage(player, C.PLOT_UNOWNED); + MainUtil.sendMessage(player, Captions.PLOT_UNOWNED); return false; } UUID uuid = player.getUUID(); if (!plot.isOwner(uuid)) { - if (!Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_MERGE)) { - MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + if (!Permissions.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_MERGE)) { + MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } else { uuid = plot.guessOwner(); } } final PlotArea plotArea = plot.getArea(); - Expression priceExr = - plotArea.PRICES.containsKey("merge") ? plotArea.PRICES.get("merge") : null; + Expression priceExr = plotArea.PRICES.getOrDefault("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) { - sendMessage(player, C.CANNOT_AFFORD_MERGE, String.valueOf(price)); + sendMessage(player, Captions.CANNOT_AFFORD_MERGE, String.valueOf(price)); return false; } 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)); + MainUtil.sendMessage(player, Captions.NO_PERMISSION, "plots.merge." + (size + 1)); return false; } int direction = -1; @@ -96,19 +104,21 @@ public class Merge extends SubCommand { if (args.length == 2) { terrain = "true".equalsIgnoreCase(args[1]); } - if(!terrain && !Permissions.hasPermission(player, C.PERMISSION_MERGE_KEEPROAD)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_MERGE_KEEPROAD.s()); + if (!terrain && !Permissions + .hasPermission(player, Captions.PERMISSION_MERGE_KEEP_ROAD)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_MERGE_KEEP_ROAD.s()); return true; } if (plot.autoMerge(-1, maxSize, uuid, terrain)) { if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d) { EconHandler.manager.withdrawMoney(player, price); - sendMessage(player, C.REMOVED_BALANCE, String.valueOf(price)); + sendMessage(player, Captions.REMOVED_BALANCE, String.valueOf(price)); } - MainUtil.sendMessage(player, C.SUCCESS_MERGE); + MainUtil.sendMessage(player, Captions.SUCCESS_MERGE); return true; } - MainUtil.sendMessage(player, C.NO_AVAILABLE_AUTOMERGE); + MainUtil.sendMessage(player, Captions.NO_AVAILABLE_AUTOMERGE); return false; } @@ -120,10 +130,10 @@ public class Merge extends SubCommand { } } if (direction == -1) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot merge <" + StringMan.join(values, "|") + "> [removeroads]"); - MainUtil - .sendMessage(player, C.DIRECTION.s().replaceAll("%dir%", direction(loc.getYaw()))); + MainUtil.sendMessage(player, + Captions.DIRECTION.s().replaceAll("%dir%", direction(loc.getYaw()))); return false; } final boolean terrain; @@ -132,26 +142,27 @@ public class Merge extends SubCommand { } else { terrain = true; } - if(!terrain && !Permissions.hasPermission(player, C.PERMISSION_MERGE_KEEPROAD)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_MERGE_KEEPROAD.s()); + if (!terrain && !Permissions.hasPermission(player, Captions.PERMISSION_MERGE_KEEP_ROAD)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_MERGE_KEEP_ROAD.s()); return true; } if (plot.autoMerge(direction, maxSize - size, uuid, terrain)) { if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d) { EconHandler.manager.withdrawMoney(player, price); - sendMessage(player, C.REMOVED_BALANCE, String.valueOf(price)); + sendMessage(player, Captions.REMOVED_BALANCE, String.valueOf(price)); } - MainUtil.sendMessage(player, C.SUCCESS_MERGE); + MainUtil.sendMessage(player, Captions.SUCCESS_MERGE); return true; } Plot adjacent = plot.getRelative(direction); if (adjacent == null || !adjacent.hasOwner() || adjacent.getMerged((direction + 2) % 4) || adjacent.isOwner(uuid)) { - MainUtil.sendMessage(player, C.NO_AVAILABLE_AUTOMERGE); + MainUtil.sendMessage(player, Captions.NO_AVAILABLE_AUTOMERGE); return false; } - if (!Permissions.hasPermission(player, C.PERMISSION_MERGE_OTHER)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_MERGE_OTHER); + if (!Permissions.hasPermission(player, Captions.PERMISSION_MERGE_OTHER)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, Captions.PERMISSION_MERGE_OTHER); return false; } java.util.Set uuids = adjacent.getOwners(); @@ -164,35 +175,35 @@ public class Merge extends SubCommand { isOnline = true; final int dir = direction; Runnable run = () -> { - MainUtil.sendMessage(accepter, C.MERGE_ACCEPTED); + MainUtil.sendMessage(accepter, Captions.MERGE_ACCEPTED); plot.autoMerge(dir, maxSize - size, owner, terrain); PlotPlayer plotPlayer = UUIDHandler.getPlayer(player.getUUID()); if (plotPlayer == null) { - sendMessage(accepter, C.MERGE_NOT_VALID); + sendMessage(accepter, Captions.MERGE_NOT_VALID); return; } if (EconHandler.manager != null && plotArea.USE_ECONOMY && price > 0d) { if (EconHandler.manager.getMoney(player) < price) { - sendMessage(player, C.CANNOT_AFFORD_MERGE, String.valueOf(price)); + sendMessage(player, Captions.CANNOT_AFFORD_MERGE, String.valueOf(price)); return; } EconHandler.manager.withdrawMoney(player, price); - sendMessage(player, C.REMOVED_BALANCE, String.valueOf(price)); + sendMessage(player, Captions.REMOVED_BALANCE, String.valueOf(price)); } - MainUtil.sendMessage(player, C.SUCCESS_MERGE); + MainUtil.sendMessage(player, Captions.SUCCESS_MERGE); }; if (hasConfirmation(player)) { CmdConfirm.addPending(accepter, - C.MERGE_REQUEST_CONFIRM.s().replaceAll("%s", player.getName()), run); + Captions.MERGE_REQUEST_CONFIRM.s().replaceAll("%s", player.getName()), run); } else { run.run(); } } if (!isOnline) { - MainUtil.sendMessage(player, C.NO_AVAILABLE_AUTOMERGE); + MainUtil.sendMessage(player, Captions.NO_AVAILABLE_AUTOMERGE); return false; } - MainUtil.sendMessage(player, C.MERGE_REQUESTED); + MainUtil.sendMessage(player, Captions.MERGE_REQUESTED); return true; } } 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 index f4f184cc1..8fbec1ecb 100644 --- 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 @@ -1,7 +1,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; @@ -18,10 +18,10 @@ import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; Location location = player.getLocation(); Plot plot = location.getPlot(); if (plot == null) { - return sendMessage(player, C.NOT_IN_PLOT); + return sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot.hasOwner()) { - return sendMessage(player, C.PLOT_UNOWNED); + return sendMessage(player, Captions.PLOT_UNOWNED); } player.teleport(plot.getCenter()); return true; diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Move.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Move.java index 289a3c4a6..e52ec1fcf 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Move.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Move.java @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotArea; @@ -12,17 +12,17 @@ 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) public class Move extends SubCommand { + requiredType = RequiredType.PLAYER) public class Move extends SubCommand { @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); + return !MainUtil.sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot1.isOwner(player.getUUID()) && !Permissions - .hasPermission(player, C.PERMISSION_ADMIN.s())) { - MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + .hasPermission(player, Captions.PERMISSION_ADMIN.s())) { + MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } boolean override = false; @@ -31,7 +31,7 @@ import com.github.intellectualsites.plotsquared.plot.util.Permissions; override = true; } if (args.length != 1) { - C.COMMAND_SYNTAX.send(player, getUsage()); + Captions.COMMAND_SYNTAX.send(player, getUsage()); return false; } PlotArea area = PlotSquared.get().getPlotAreaByString(args[0]); @@ -45,19 +45,19 @@ import com.github.intellectualsites.plotsquared.plot.util.Permissions; plot2 = area.getPlotAbs(plot1.getId()); } if (plot1.equals(plot2)) { - MainUtil.sendMessage(player, C.NOT_VALID_PLOT_ID); - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot copy "); + MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_ID); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot copy "); return false; } if (!plot1.getArea().isCompatible(plot2.getArea()) && (!override || !Permissions - .hasPermission(player, C.PERMISSION_ADMIN.s()))) { - C.PLOTWORLD_INCOMPATIBLE.send(player); + .hasPermission(player, Captions.PERMISSION_ADMIN.s()))) { + Captions.PLOTWORLD_INCOMPATIBLE.send(player); return false; } - if (plot1.move(plot2, () -> MainUtil.sendMessage(player, C.MOVE_SUCCESS), false)) { + if (plot1.move(plot2, () -> MainUtil.sendMessage(player, Captions.MOVE_SUCCESS), false)) { return true; } else { - MainUtil.sendMessage(player, C.REQUIRES_UNOWNED); + MainUtil.sendMessage(player, Captions.REQUIRES_UNOWNED); return false; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Music.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Music.java index 50b6f36d8..e773879ae 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Music.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Music.java @@ -1,7 +1,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.flag.Flags; import com.github.intellectualsites.plotsquared.plot.object.*; @@ -14,18 +14,19 @@ import java.util.Locale; category = CommandCategory.APPEARANCE, requiredType = RequiredType.PLAYER) public class Music extends SubCommand { - private static final Collection DISCS = Arrays.asList("music_disc_13", "music_disc_cat", - "music_disc_blocks", "music_disc_chirp", "music_disc_far", "music_disc_mall", "music_disc_mellohi", - "music_disc_stal", "music_disc_strad", "music_disc_ward", "music_disc_11", "music_disc_wait"); + private static final Collection DISCS = Arrays + .asList("music_disc_13", "music_disc_cat", "music_disc_blocks", "music_disc_chirp", + "music_disc_far", "music_disc_mall", "music_disc_mellohi", "music_disc_stal", + "music_disc_strad", "music_disc_ward", "music_disc_11", "music_disc_wait"); @Override public boolean onCommand(PlotPlayer player, String[] args) { Location loc = player.getLocation(); final Plot plot = loc.getPlotAbs(); if (plot == null) { - return !sendMessage(player, C.NOT_IN_PLOT); + return !sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot.isAdded(player.getUUID())) { - sendMessage(player, C.NO_PLOT_PERMS); + sendMessage(player, Captions.NO_PLOT_PERMS); return true; } PlotInventory inv = new PlotInventory(player, 2, "Plot Jukebox") { @@ -36,12 +37,12 @@ import java.util.Locale; } if (item.getPlotBlock().equalsAny(7, "bedrock")) { plot.removeFlag(Flags.MUSIC); - C.FLAG_REMOVED.send(player); + Captions.FLAG_REMOVED.send(player); } else if (item.name.toLowerCase(Locale.ENGLISH).contains("disc")) { plot.setFlag(Flags.MUSIC, item.getPlotBlock().getRawId()); - C.FLAG_ADDED.send(player); + Captions.FLAG_ADDED.send(player); } else { - C.FLAG_NOT_ADDED.send(player); + Captions.FLAG_NOT_ADDED.send(player); } return false; } 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 index e2278c4e2..d897fb3cf 100644 --- 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 @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; @@ -12,7 +12,8 @@ import com.github.intellectualsites.plotsquared.plot.util.StringMan; import java.util.concurrent.CompletableFuture; @CommandDeclaration(command = "near", aliases = "n", description = "Display nearby players", - usage = "/plot near", category = CommandCategory.INFO) public class Near extends Command { + usage = "/plot near", category = CommandCategory.INFO, requiredType = RequiredType.PLAYER) +public class Near extends Command { public Near() { super(MainCommand.getInstance(), true); } @@ -20,8 +21,8 @@ import java.util.concurrent.CompletableFuture; @Override public CompletableFuture 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(), ", ")); + final Plot plot = check(player.getCurrentPlot(), Captions.NOT_IN_PLOT); + Captions.PLOT_NEAR.send(player, StringMan.join(plot.getPlayersInPlot(), ", ")); return CompletableFuture.completedFuture(true); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Owner.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Owner.java index 4095c15c9..8247c0e83 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Owner.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Owner.java @@ -1,11 +1,15 @@ 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.Captions; 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 com.github.intellectualsites.plotsquared.plot.util.CmdConfirm; +import com.github.intellectualsites.plotsquared.plot.util.MainUtil; +import com.github.intellectualsites.plotsquared.plot.util.Permissions; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.github.intellectualsites.plotsquared.plot.util.UUIDHandler; import java.util.Set; import java.util.UUID; @@ -27,14 +31,14 @@ import java.util.UUID; } } else { uuid = UUIDHandler.getUUID(value, null); - name = UUIDHandler.getName(uuid); + name = uuid == null ? value : UUIDHandler.getName(uuid); 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)) { + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_SET_OWNER.s(), true)) { return false; } Set connected = plot.getConnectedPlots(); @@ -43,20 +47,20 @@ import java.util.UUID; current.unclaim(); current.removeSign(); } - MainUtil.sendMessage(player, C.SET_OWNER); + MainUtil.sendMessage(player, Captions.SET_OWNER); return true; } - C.INVALID_PLAYER.send(player, value); + Captions.INVALID_PLAYER.send(player, value); return false; } final PlotPlayer other = UUIDHandler.getPlayer(uuid); if (plot.isOwner(uuid)) { - C.ALREADY_OWNER.send(player, MainUtil.getName(uuid)); + Captions.ALREADY_OWNER.send(player, MainUtil.getName(uuid)); return false; } - if (!Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SETOWNER)) { + if (!Permissions.hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_SET_OWNER)) { if (other == null) { - C.INVALID_PLAYER_OFFLINE.send(player, value); + Captions.INVALID_PLAYER_OFFLINE.send(player, value); return false; } int size = plots.size(); @@ -64,7 +68,7 @@ import java.util.UUID; other.getPlotCount() : other.getPlotCount(plot.getWorldName())) + size; if (currentPlots > other.getAllowedPlots()) { - sendMessage(player, C.CANT_TRANSFER_MORE_PLOTS); + sendMessage(player, Captions.CANT_TRANSFER_MORE_PLOTS); return false; } } @@ -77,13 +81,14 @@ import java.util.UUID; if (removeDenied) plot.removeDenied(finalUUID); plot.setSign(finalName); - MainUtil.sendMessage(player, C.SET_OWNER); + MainUtil.sendMessage(player, Captions.SET_OWNER); if (other != null) { - MainUtil - .sendMessage(other, C.NOW_OWNER, plot.getArea() + ";" + plot.getId()); + MainUtil.sendMessage(other, Captions.NOW_OWNER, + plot.getArea() + ";" + plot.getId()); } - } else - MainUtil.sendMessage(player, C.SET_OWNER_CANCELLED); + } else { + MainUtil.sendMessage(player, Captions.SET_OWNER_CANCELLED); + } } }; if (hasConfirmation(player)) { diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Purge.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Purge.java index b8b38e298..0825b9610 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Purge.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Purge.java @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.listener.PlotListener; import com.github.intellectualsites.plotsquared.plot.object.Plot; @@ -38,7 +38,7 @@ import java.util.UUID; for (String arg : args) { String[] split = arg.split(":"); if (split.length != 2) { - C.COMMAND_SYNTAX.send(player, getUsage()); + Captions.COMMAND_SYNTAX.send(player, getUsage()); return false; } switch (split[0].toLowerCase()) { @@ -50,15 +50,16 @@ import java.util.UUID; case "a": area = PlotSquared.get().getPlotAreaByString(split[1]); if (area == null) { - C.NOT_VALID_PLOT_WORLD.send(player, split[1]); + Captions.NOT_VALID_PLOT_WORLD.send(player, split[1]); return false; } break; case "plotid": case "id": - id = PlotId.fromString(split[1]); - if (id == null) { - C.NOT_VALID_PLOT_ID.send(player, split[1]); + try { + id = PlotId.fromString(split[1]); + } catch (IllegalArgumentException ignored) { + Captions.NOT_VALID_PLOT_ID.send(player, split[1]); return false; } break; @@ -66,7 +67,7 @@ import java.util.UUID; case "o": owner = UUIDHandler.getUUID(split[1], null); if (owner == null) { - C.INVALID_PLAYER.send(player, split[1]); + Captions.INVALID_PLAYER.send(player, split[1]); return false; } break; @@ -74,7 +75,7 @@ import java.util.UUID; case "s": added = UUIDHandler.getUUID(split[1], null); if (added == null) { - C.INVALID_PLAYER.send(player, split[1]); + Captions.INVALID_PLAYER.send(player, split[1]); return false; } break; @@ -84,7 +85,7 @@ import java.util.UUID; unknown = Boolean.parseBoolean(split[1]); break; default: - C.COMMAND_SYNTAX.send(player, getUsage()); + Captions.COMMAND_SYNTAX.send(player, getUsage()); return false; } } @@ -108,9 +109,7 @@ import java.util.UUID; if (unknown && UUIDHandler.getName(plot.owner) != null) { continue; } - for (Plot current : plot.getConnectedPlots()) { - toDelete.add(current); - } + toDelete.addAll(plot.getConnectedPlots()); } if (PlotSquared.get().plots_tmp != null) { for (Entry> entry : PlotSquared.get().plots_tmp @@ -138,28 +137,26 @@ import java.util.UUID; } } if (toDelete.isEmpty()) { - C.FOUND_NO_PLOTS.send(player); + Captions.FOUND_NO_PLOTS.send(player); return false; } String cmd = "/plot purge " + StringMan.join(args, " ") + " (" + toDelete.size() + " plots)"; - Runnable run = new Runnable() { - @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) { - ids.add(plot.temp); - plot.getArea().removePlot(plot.getId()); - for (PlotPlayer pp : plot.getPlayersInPlot()) { - PlotListener.plotEntry(pp, plot); - } - plot.removeSign(); + Runnable run = () -> { + PlotSquared.debug("Calculating plots to purge, please wait..."); + HashSet ids = new HashSet<>(); + for (Plot plot : toDelete) { + if (plot.temp != Integer.MAX_VALUE) { + ids.add(plot.temp); + plot.getArea().removePlot(plot.getId()); + for (PlotPlayer pp : plot.getPlayersInPlot()) { + PlotListener.plotEntry(pp, plot); } + plot.removeSign(); } - DBFunc.purgeIds(ids); - C.PURGE_SUCCESS.send(player, ids.size() + "/" + toDelete.size()); } + DBFunc.purgeIds(ids); + Captions.PURGE_SUCCESS.send(player, ids.size() + "/" + toDelete.size()); }; if (hasConfirmation(player)) { CmdConfirm.addPending(player, cmd, run); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Rate.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Rate.java index 7141df96e..9c93925b6 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Rate.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Rate.java @@ -3,44 +3,44 @@ 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.Captions; 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.*; +import java.util.ArrayList; +import java.util.HashMap; 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) public class Rate extends SubCommand { + requiredType = RequiredType.PLAYER) public class Rate extends SubCommand { @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length == 1) { switch (args[0].toLowerCase()) { case "next": { ArrayList plots = new ArrayList<>(PlotSquared.get().getBasePlots()); - Collections.sort(plots, new Comparator() { - @Override public int compare(Plot p1, Plot p2) { - double v1 = 0; - if (!p1.getRatings().isEmpty()) { - for (Entry entry : p1.getRatings().entrySet()) { - v1 -= 11 - entry.getValue().getAverageRating(); - } + plots.sort((p1, p2) -> { + double v1 = 0; + if (!p1.getRatings().isEmpty()) { + for (Entry entry : p1.getRatings().entrySet()) { + v1 -= 11 - entry.getValue().getAverageRating(); } - double v2 = 0; - if (!p2.getRatings().isEmpty()) { - for (Entry entry : p2.getRatings().entrySet()) { - v2 -= 11 - entry.getValue().getAverageRating(); - } - } - if (v1 == v2) { - return -0; - } - return v2 > v1 ? 1 : -1; } + double v2 = 0; + if (!p2.getRatings().isEmpty()) { + for (Entry entry : p2.getRatings().entrySet()) { + v2 -= 11 - entry.getValue().getAverageRating(); + } + } + if (v1 == v2) { + return -0; + } + return v2 > v1 ? 1 : -1; }); UUID uuid = player.getUUID(); for (Plot p : plots) { @@ -48,48 +48,50 @@ import java.util.Map.Entry; .isBasePlot() && (!p.getRatings().containsKey(uuid)) && !p .isAdded(uuid)) { p.teleportPlayer(player); - MainUtil.sendMessage(player, C.RATE_THIS); + MainUtil.sendMessage(player, Captions.RATE_THIS); return true; } } - MainUtil.sendMessage(player, C.FOUND_NO_PLOTS); + MainUtil.sendMessage(player, Captions.FOUND_NO_PLOTS); return false; } case "purge": { final Plot plot = player.getCurrentPlot(); if (plot == null) { - return !sendMessage(player, C.NOT_IN_PLOT); + return !sendMessage(player, Captions.NOT_IN_PLOT); } - if (!Permissions.hasPermission(player, C.PERMISSION_ADMIN_COMMAND_RATE, true)) { + if (!Permissions + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_RATE, true)) { return false; } plot.clearRatings(); - C.RATINGS_PURGED.send(player); + Captions.RATINGS_PURGED.send(player); return true; } } } final Plot plot = player.getCurrentPlot(); if (plot == null) { - return !sendMessage(player, C.NOT_IN_PLOT); + return !sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot.hasOwner()) { - sendMessage(player, C.RATING_NOT_OWNED); + sendMessage(player, Captions.RATING_NOT_OWNED); return false; } if (plot.isOwner(player.getUUID())) { - sendMessage(player, C.RATING_NOT_YOUR_OWN); + sendMessage(player, Captions.RATING_NOT_YOUR_OWN); return false; } if (Settings.Done.REQUIRED_FOR_RATINGS && !plot.hasFlag(Flags.DONE)) { - sendMessage(player, C.RATING_NOT_DONE); + sendMessage(player, Captions.RATING_NOT_DONE); return false; } if (Settings.Ratings.CATEGORIES != null && !Settings.Ratings.CATEGORIES.isEmpty()) { final Runnable run = new Runnable() { @Override public void run() { if (plot.getRatings().containsKey(player.getUUID())) { - sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString()); + sendMessage(player, Captions.RATING_ALREADY_EXISTS, + plot.getId().toString()); return; } final MutableInt index = new MutableInt(0); @@ -105,14 +107,14 @@ import java.util.Map.Entry; EventUtil.manager.callRating(this.player, plot, new Rating(rV)); if (result != null) { plot.addRating(this.player.getUUID(), result); - sendMessage(this.player, C.RATING_APPLIED, + sendMessage(this.player, Captions.RATING_APPLIED, plot.getId().toString()); if (Permissions - .hasPermission(this.player, C.PERMISSION_COMMENT)) { + .hasPermission(this.player, Captions.PERMISSION_COMMENT)) { Command command = MainCommand.getInstance().getCommand(Comment.class); if (command != null) { - MainUtil.sendMessage(this.player, C.COMMENT_THIS, + MainUtil.sendMessage(this.player, Captions.COMMENT_THIS, command.getUsage()); } } @@ -137,11 +139,9 @@ import java.util.Map.Entry; }; if (plot.getSettings().ratings == null) { if (!Settings.Enabled_Components.RATING_CACHE) { - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - plot.getSettings().ratings = DBFunc.getRatings(plot); - run.run(); - } + TaskManager.runTaskAsync(() -> { + plot.getSettings().ratings = DBFunc.getRatings(plot); + run.run(); }); return true; } @@ -151,7 +151,7 @@ import java.util.Map.Entry; return true; } if (args.length < 1) { - sendMessage(player, C.RATING_NOT_VALID); + sendMessage(player, Captions.RATING_NOT_VALID); return true; } String arg = args[0]; @@ -159,34 +159,30 @@ import java.util.Map.Entry; if (MathMan.isInteger(arg) && arg.length() < 3 && !arg.isEmpty()) { rating = Integer.parseInt(arg); if (rating > 10 || rating < 1) { - sendMessage(player, C.RATING_NOT_VALID); + sendMessage(player, Captions.RATING_NOT_VALID); return false; } } else { - sendMessage(player, C.RATING_NOT_VALID); + sendMessage(player, Captions.RATING_NOT_VALID); return false; } final UUID uuid = player.getUUID(); - final Runnable run = new Runnable() { - @Override public void run() { - if (plot.getRatings().containsKey(uuid)) { - sendMessage(player, C.RATING_ALREADY_EXISTS, plot.getId().toString()); - return; - } - Rating result = EventUtil.manager.callRating(player, plot, new Rating(rating)); - if (result != null) { - plot.addRating(uuid, result); - sendMessage(player, C.RATING_APPLIED, plot.getId().toString()); - } + final Runnable run = () -> { + if (plot.getRatings().containsKey(uuid)) { + sendMessage(player, Captions.RATING_ALREADY_EXISTS, plot.getId().toString()); + return; + } + Rating result = EventUtil.manager.callRating(player, plot, new Rating(rating)); + if (result != null) { + plot.addRating(uuid, result); + sendMessage(player, Captions.RATING_APPLIED, plot.getId().toString()); } }; if (plot.getSettings().ratings == null) { if (!Settings.Enabled_Components.RATING_CACHE) { - TaskManager.runTaskAsync(new Runnable() { - @Override public void run() { - plot.getSettings().ratings = DBFunc.getRatings(plot); - run.run(); - } + TaskManager.runTaskAsync(() -> { + plot.getSettings().ratings = DBFunc.getRatings(plot); + run.run(); }); return true; } 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 index 9edf20a62..9fcdc811d 100644 --- 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 @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.generator.HybridPlotManager; import com.github.intellectualsites.plotsquared.plot.generator.HybridUtils; import com.github.intellectualsites.plotsquared.plot.object.PlotArea; @@ -22,24 +22,25 @@ import com.github.intellectualsites.plotsquared.plot.util.MainUtil; 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]"); + MainUtil.sendMessage(player, Captions.NOT_VALID_NUMBER, "(0, 256)"); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, + "/plot regenallroads [height]"); return false; } } else if (args.length != 1) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot regenallroads [height]"); + MainUtil.sendMessage(player, Captions.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]); + Captions.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); + MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_WORLD); return false; } //Set chunks = ChunkManager.manager.getChunkChunks(name); 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 index 0d3638fe3..321f91d24 100644 --- 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 @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.object.*; import com.github.intellectualsites.plotsquared.plot.util.ChunkManager; import com.github.intellectualsites.plotsquared.plot.util.block.LocalBlockQueue; @@ -20,7 +20,7 @@ import java.util.concurrent.CompletableFuture; RunnableVal2 whenDone) { final Plot plot = player.getCurrentPlot(); if (plot == null) { - C.NOT_IN_PLOT.send(player); + Captions.NOT_IN_PLOT.send(player); return CompletableFuture.completedFuture(false); } final LocalBlockQueue queue = plot.getArea().getQueue(false); @@ -30,7 +30,7 @@ import java.util.concurrent.CompletableFuture; } }, () -> { plot.refreshChunks(); - C.SET_BLOCK_ACTION_FINISHED.send(player); + Captions.SET_BLOCK_ACTION_FINISHED.send(player); }, 5); return CompletableFuture.completedFuture(true); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Reload.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Reload.java index 71ee2e840..db900e91e 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Reload.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Reload.java @@ -5,10 +5,8 @@ import com.github.intellectualsites.plotsquared.configuration.ConfigurationSecti 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.config.Captions; 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 java.io.IOException; @@ -23,61 +21,59 @@ import java.util.Objects; // The following won't affect world generation, as that has to be // loaded during startup unfortunately. 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; + Captions.load(PlotSquared.get().translationFile); + PlotSquared.get().forEachPlotArea(area -> { + ConfigurationSection worldSection = + PlotSquared.get().worlds.getConfigurationSection("worlds." + area.worldname); + if (worldSection == null) { + return; + } + if (area.TYPE != 2 || !worldSection.contains("areas")) { + area.saveConfiguration(worldSection); + area.loadDefaultConfiguration(worldSection); + } else { + 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) { + continue; + } + if (!clone.contains(key)) { + clone.set(key, areaSection.get(key)); + } } - if (area.TYPE != 2 || !worldSection.contains("areas")) { - area.saveConfiguration(worldSection); - area.loadDefaultConfiguration(worldSection); - } else { - 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) { - continue; - } - if (!clone.contains(key)) { - clone.set(key, areaSection.get(key)); - } + for (String key : worldSection.getKeys(true)) { + if (worldSection.get(key) instanceof MemorySection) { + continue; } - for (String key : worldSection.getKeys(true)) { - if (worldSection.get(key) instanceof MemorySection) { - continue; - } - if (!key.startsWith("areas") && !clone.contains(key)) { - clone.set(key, worldSection.get(key)); - } + if (!key.startsWith("areas") && !clone.contains(key)) { + clone.set(key, worldSection.get(key)); } - area.saveConfiguration(clone); - // netSections is the combination of - for (String key : clone.getKeys(true)) { - if (clone.get(key) instanceof MemorySection) { - continue; - } - if (!worldSection.contains(key)) { - worldSection.set(key, clone.get(key)); - } else { - Object value = worldSection.get(key); - if (Objects.equals(value, clone.get(key))) { - areaSection.set(key, clone.get(key)); - } - } - } - area.loadDefaultConfiguration(clone); } + area.saveConfiguration(clone); + // netSections is the combination of + for (String key : clone.getKeys(true)) { + if (clone.get(key) instanceof MemorySection) { + continue; + } + if (!worldSection.contains(key)) { + worldSection.set(key, clone.get(key)); + } else { + Object value = worldSection.get(key); + if (Objects.equals(value, clone.get(key))) { + areaSection.set(key, clone.get(key)); + } + } + } + area.loadDefaultConfiguration(clone); } }); PlotSquared.get().worlds.save(PlotSquared.get().worldsFile); - MainUtil.sendMessage(player, C.RELOADED_CONFIGS); + MainUtil.sendMessage(player, Captions.RELOADED_CONFIGS); } catch (IOException e) { e.printStackTrace(); - MainUtil.sendMessage(player, C.RELOAD_FAILED); + MainUtil.sendMessage(player, Captions.RELOAD_FAILED); } return true; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Remove.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Remove.java index bf027f20d..875eb6e4c 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Remove.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Remove.java @@ -2,7 +2,7 @@ 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.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.database.DBFunc; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; @@ -30,25 +30,25 @@ import java.util.UUID; Location location = player.getLocation(); Plot plot = location.getPlotAbs(); if (plot == null) { - return !sendMessage(player, C.NOT_IN_PLOT); + return !sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot.hasOwner()) { - MainUtil.sendMessage(player, C.PLOT_UNOWNED); + MainUtil.sendMessage(player, Captions.PLOT_UNOWNED); return false; } if (!plot.isOwner(player.getUUID()) && !Permissions - .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_REMOVE)) { - MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_REMOVE)) { + MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return true; } int count = 0; switch (args[0]) { case "unknown": { - ArrayList toRemove = new ArrayList<>(); HashSet all = new HashSet<>(); all.addAll(plot.getMembers()); all.addAll(plot.getTrusted()); all.addAll(plot.getDenied()); + ArrayList toRemove = new ArrayList<>(); for (UUID uuid : all) { if (UUIDHandler.getName(uuid) == null) { toRemove.add(uuid); @@ -98,10 +98,10 @@ import java.util.UUID; break; } if (count == 0) { - MainUtil.sendMessage(player, C.INVALID_PLAYER, args[0]); + MainUtil.sendMessage(player, Captions.INVALID_PLAYER, args[0]); return false; } else { - MainUtil.sendMessage(player, C.REMOVED_PLAYERS, count + ""); + MainUtil.sendMessage(player, Captions.REMOVED_PLAYERS, count + ""); } return true; } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/RequiredType.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/RequiredType.java index 3f13368de..2dc75f919 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/RequiredType.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/RequiredType.java @@ -6,11 +6,9 @@ public enum RequiredType { CONSOLE, PLAYER, NONE; public boolean allows(CommandCaller player) { - switch (this) { - case NONE: - return true; - default: - return this == player.getSuperCaller(); + if (this == RequiredType.NONE) { + return true; } + return this == player.getSuperCaller(); } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Save.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Save.java index aec9543ed..481acba53 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Save.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Save.java @@ -2,7 +2,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.object.*; import com.github.intellectualsites.plotsquared.plot.util.MainUtil; import com.github.intellectualsites.plotsquared.plot.util.Permissions; @@ -21,23 +21,23 @@ import java.util.UUID; @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); + return !sendMessage(player, Captions.NOT_IN_PLOT_WORLD); } final Plot plot = player.getCurrentPlot(); if (plot == null) { - return !sendMessage(player, C.NOT_IN_PLOT); + return !sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot.hasOwner()) { - MainUtil.sendMessage(player, C.PLOT_UNOWNED); + MainUtil.sendMessage(player, Captions.PLOT_UNOWNED); return false; } if (!plot.isOwner(player.getUUID()) && !Permissions - .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SAVE)) { - MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_SAVE)) { + MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } if (plot.getRunning() > 0) { - MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); + MainUtil.sendMessage(player, Captions.WAIT_FOR_TIMER); return false; } plot.addRunning(); @@ -58,13 +58,13 @@ import java.util.UUID; @Override public void run(URL url) { plot.removeRunning(); if (url == null) { - MainUtil.sendMessage(player, C.SAVE_FAILED); + MainUtil.sendMessage(player, Captions.SAVE_FAILED); return; } - MainUtil.sendMessage(player, C.SAVE_SUCCESS); + MainUtil.sendMessage(player, Captions.SAVE_SUCCESS); List schematics = player.getMeta("plot_schematics"); if (schematics != null) { - schematics.add(file + ".schematic"); + schematics.add(file + ".schem"); } } }); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SchematicCmd.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SchematicCmd.java index 110992543..24ccbe016 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SchematicCmd.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SchematicCmd.java @@ -2,11 +2,21 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.Settings; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.ConsolePlayer; +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.object.RunnableVal; import com.github.intellectualsites.plotsquared.plot.object.schematic.Schematic; -import com.github.intellectualsites.plotsquared.plot.util.*; +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.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.TaskManager; +import com.google.common.collect.Lists; import java.net.URL; import java.util.ArrayList; @@ -22,32 +32,33 @@ public class SchematicCmd extends SubCommand { @Override public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length < 1) { - sendMessage(player, C.SCHEMATIC_MISSING_ARG); + sendMessage(player, Captions.SCHEMATIC_MISSING_ARG); return true; } String arg = args[0].toLowerCase(); switch (arg) { case "paste": { - if (!Permissions.hasPermission(player, C.PERMISSION_SCHEMATIC_PASTE)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SCHEMATIC_PASTE); + if (!Permissions.hasPermission(player, Captions.PERMISSION_SCHEMATIC_PASTE)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_SCHEMATIC_PASTE); return false; } if (args.length < 2) { - sendMessage(player, C.SCHEMATIC_MISSING_ARG); + sendMessage(player, Captions.SCHEMATIC_MISSING_ARG); break; } Location loc = player.getLocation(); final Plot plot = loc.getPlotAbs(); if (plot == null) { - return !sendMessage(player, C.NOT_IN_PLOT); + return !sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot.hasOwner()) { - MainUtil.sendMessage(player, C.PLOT_UNOWNED); + MainUtil.sendMessage(player, Captions.PLOT_UNOWNED); return false; } if (!plot.isOwner(player.getUUID()) && !Permissions - .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC_PASTE)) { - MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_SCHEMATIC_PASTE)) { + MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } if (this.running) { @@ -66,7 +77,7 @@ public class SchematicCmd extends SubCommand { schematic = SchematicHandler.manager.getSchematic(url); } catch (Exception e) { e.printStackTrace(); - sendMessage(player, C.SCHEMATIC_INVALID, + sendMessage(player, Captions.SCHEMATIC_INVALID, "non-existent url: " + location); SchematicCmd.this.running = false; return; @@ -80,7 +91,7 @@ public class SchematicCmd extends SubCommand { } if (schematic == null) { SchematicCmd.this.running = false; - sendMessage(player, C.SCHEMATIC_INVALID, + sendMessage(player, Captions.SCHEMATIC_INVALID, "non-existent or not in gzip format"); return; } @@ -89,9 +100,9 @@ public class SchematicCmd extends SubCommand { @Override public void run(Boolean value) { SchematicCmd.this.running = false; if (value) { - sendMessage(player, C.SCHEMATIC_PASTE_SUCCESS); + sendMessage(player, Captions.SCHEMATIC_PASTE_SUCCESS); } else { - sendMessage(player, C.SCHEMATIC_PASTE_FAILED); + sendMessage(player, Captions.SCHEMATIC_PASTE_FAILED); } } }); @@ -101,39 +112,39 @@ public class SchematicCmd extends SubCommand { // TODO test // case "test": { // if (!Permissions.hasPermission(plr, "plots.schematic.test")) { - // MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.schematic.test"); + // MainUtil.sendMessage(plr, Captions.NO_PERMISSION, "plots.schematic.test"); // return false; // } // if (args.length < 2) { - // sendMessage(plr, C.SCHEMATIC_MISSING_ARG); + // sendMessage(plr, Captions.SCHEMATIC_MISSING_ARG); // return false; // } // final Location loc = plr.getLocation(); // final Plot plot = MainUtil.getPlot(loc); // if (plot == null) { - // sendMessage(plr, C.NOT_IN_PLOT); + // sendMessage(plr, Captions.NOT_IN_PLOT); // return false; // } // file = args[1]; // schematic = SchematicHandler.manager.getSchematic(file); // if (schematic == null) { - // sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent"); + // sendMessage(plr, Captions.SCHEMATIC_INVALID, "non-existent"); // return false; // } // final int l1 = schematic.getSchematicDimension().getX(); // final int l2 = schematic.getSchematicDimension().getZ(); // final int length = MainUtil.getPlotWidth(loc.getWorld(), plot.id); // if ((l1 < length) || (l2 < length)) { - // sendMessage(plr, C.SCHEMATIC_INVALID, String.format("Wrong size (x: %s, z: %d) vs %d ", l1, l2, length)); + // sendMessage(plr, Captions.SCHEMATIC_INVALID, String.format("Wrong size (x: %s, z: %d) vs %d ", l1, l2, length)); // break; // } - // sendMessage(plr, C.SCHEMATIC_VALID); + // sendMessage(plr, Captions.SCHEMATIC_VALID); // break; // } case "saveall": case "exportall": { if (!(player instanceof ConsolePlayer)) { - MainUtil.sendMessage(player, C.NOT_CONSOLE); + MainUtil.sendMessage(player, Captions.NOT_CONSOLE); return false; } if (args.length != 2) { @@ -143,7 +154,7 @@ public class SchematicCmd extends SubCommand { } PlotArea area = PlotSquared.get().getPlotAreaByString(args[1]); if (area == null) { - C.NOT_VALID_PLOT_WORLD.send(player, args[1]); + Captions.NOT_VALID_PLOT_WORLD.send(player, args[1]); return false; } Collection plots = area.getPlots(); @@ -167,8 +178,9 @@ public class SchematicCmd extends SubCommand { } case "export": case "save": - if (!Permissions.hasPermission(player, C.PERMISSION_SCHEMATIC_SAVE)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SCHEMATIC_SAVE); + if (!Permissions.hasPermission(player, Captions.PERMISSION_SCHEMATIC_SAVE)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_SCHEMATIC_SAVE); return false; } if (this.running) { @@ -178,20 +190,18 @@ public class SchematicCmd extends SubCommand { Location location = player.getLocation(); Plot plot = location.getPlotAbs(); if (plot == null) { - return !sendMessage(player, C.NOT_IN_PLOT); + return !sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot.hasOwner()) { - MainUtil.sendMessage(player, C.PLOT_UNOWNED); + MainUtil.sendMessage(player, Captions.PLOT_UNOWNED); return false; } if (!plot.isOwner(player.getUUID()) && !Permissions - .hasPermission(player, C.PERMISSION_ADMIN_COMMAND_SCHEMATIC_SAVE)) { - MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND_SCHEMATIC_SAVE)) { + MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } - location.getWorld(); - Collection plots = new ArrayList<>(); - plots.add(plot); + ArrayList plots = Lists.newArrayList(plot); boolean result = SchematicHandler.manager.exportAll(plots, null, null, () -> { MainUtil.sendMessage(player, "&aFinished export"); SchematicCmd.this.running = false; @@ -204,17 +214,18 @@ public class SchematicCmd extends SubCommand { } break; case "list": { - if (!Permissions.hasPermission(player, C.PERMISSION_SCHEMATIC_LIST)) { - MainUtil.sendMessage(player, C.NO_PERMISSION, C.PERMISSION_SCHEMATIC_LIST); + if (!Permissions.hasPermission(player, Captions.PERMISSION_SCHEMATIC_LIST)) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_SCHEMATIC_LIST); return false; } final String string = - StringMan.join(SchematicHandler.manager.getShematicNames(), "$2, $1"); - C.SCHEMATIC_LIST.send(player, string); + StringMan.join(SchematicHandler.manager.getSchematicNames(), "$2, $1"); + Captions.SCHEMATIC_LIST.send(player, string); } break; default: - sendMessage(player, C.SCHEMATIC_MISSING_ARG); + sendMessage(player, Captions.SCHEMATIC_MISSING_ARG); break; } return true; 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 index 95166aa4a..7b01f57e1 100644 --- 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 @@ -2,19 +2,30 @@ 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.Captions; 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.object.BlockBucket; +import com.github.intellectualsites.plotsquared.plot.object.Plot; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotBlock; +import com.github.intellectualsites.plotsquared.plot.object.PlotManager; +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.StringComparison; +import com.github.intellectualsites.plotsquared.plot.util.StringMan; +import com.github.intellectualsites.plotsquared.plot.util.WorldUtil; import com.github.intellectualsites.plotsquared.plot.util.block.GlobalBlockQueue; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; +import java.util.stream.Collectors; +import java.util.stream.IntStream; @CommandDeclaration(command = "set", description = "Set a plot value", aliases = {"s"}, usage = "/plot set ", permission = "plots.set", @@ -36,7 +47,7 @@ import java.util.HashSet; @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()); + String[] components = manager.getPlotComponents(plot.getId()); boolean allowUnsafe = DebugAllowUnsafe.unsafeAllowed.contains(player.getUUID()); String[] args = value.split(" "); @@ -45,34 +56,32 @@ import java.util.HashSet; 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)); + if (!Permissions.hasPermission(player, + Captions.PERMISSION_SET_COMPONENT.f(component))) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_SET_COMPONENT.f(component)); return false; } // PlotBlock[] blocks; BlockBucket bucket; try { if (args.length < 2) { - MainUtil.sendMessage(player, C.NEED_BLOCK); + MainUtil.sendMessage(player, Captions.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); + Captions.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, + MainUtil.sendMessage(player, Captions.DID_YOU_MEAN, found.toLowerCase()); } } @@ -82,29 +91,25 @@ import java.util.HashSet; if (!allowUnsafe) { for (final PlotBlock block : bucket.getBlocks()) { if (!block.isAir() && !WorldUtil.IMP.isBlockSolid(block)) { - C.NOT_ALLOWED_BLOCK.send(player, block.toString()); + Captions.NOT_ALLOWED_BLOCK.send(player, block.toString()); return false; } } } } catch (Exception ignored) { - MainUtil.sendMessage(player, C.NOT_VALID_BLOCK, material); + MainUtil.sendMessage(player, Captions.NOT_VALID_BLOCK, material); return false; } if (plot.getRunning() > 0) { - MainUtil.sendMessage(player, C.WAIT_FOR_TIMER); + MainUtil.sendMessage(player, Captions.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(); - } - }); + MainUtil.sendMessage(player, Captions.GENERATING_COMPONENT); + GlobalBlockQueue.IMP.addTask(plot::removeRunning); return true; } } @@ -114,15 +119,15 @@ import java.util.HashSet; } public boolean noArgs(PlotPlayer player) { - ArrayList newValues = new ArrayList<>(); - newValues.addAll(Arrays.asList("biome", "alias", "home", "flag")); + ArrayList newValues = + new ArrayList<>(Arrays.asList("biome", "alias", "home", "flag")); Plot plot = player.getCurrentPlot(); if (plot != null) { newValues.addAll( - Arrays.asList(plot.getManager().getPlotComponents(plot.getArea(), plot.getId()))); + Arrays.asList(plot.getManager().getPlotComponents(plot.getId()))); } - MainUtil.sendMessage(player, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringMan - .join(newValues, C.BLOCK_LIST_SEPARATER.formatted())); + MainUtil.sendMessage(player, Captions.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringMan + .join(newValues, Captions.BLOCK_LIST_SEPARATER.formatted())); return false; } @@ -141,25 +146,24 @@ import java.util.HashSet; // Additional checks Plot plot = player.getCurrentPlot(); if (plot == null) { - MainUtil.sendMessage(player, C.NOT_IN_PLOT); + MainUtil.sendMessage(player, Captions.NOT_IN_PLOT); return false; } // components HashSet components = new HashSet<>( - Arrays.asList(plot.getManager().getPlotComponents(plot.getArea(), plot.getId()))); + Arrays.asList(plot.getManager().getPlotComponents(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(); + String a = ""; if (args.length > 1) { - for (int x = 1; x < args.length; x++) { - a.append(" ").append(args[x]); - } + a = IntStream.range(1, args.length).mapToObj(x -> " " + args[x]) + .collect(Collectors.joining()); } - MainCommand.onCommand(player, ("flag set " + args[0] + a.toString()).split(" ")); + MainCommand.onCommand(player, ("flag set " + args[0] + a).split(" ")); return true; } return noArgs(player); diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SetCommand.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SetCommand.java index aaa1adfa2..bc64f0244 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SetCommand.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/SetCommand.java @@ -1,6 +1,6 @@ package com.github.intellectualsites.plotsquared.plot.commands; -import com.github.intellectualsites.plotsquared.plot.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; @@ -14,21 +14,23 @@ public abstract class SetCommand extends SubCommand { Location loc = player.getLocation(); Plot plot = loc.getPlotAbs(); if (plot == null) { - return !sendMessage(player, C.NOT_IN_PLOT); + return !sendMessage(player, Captions.NOT_IN_PLOT); } 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.PLOT_NOT_CLAIMED); + if (!Permissions + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND.f(getFullId()))) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_ADMIN_COMMAND.f(getFullId())); + MainUtil.sendMessage(player, Captions.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_PLOT_PERMS); + if (!Permissions + .hasPermission(player, Captions.PERMISSION_ADMIN_COMMAND.f(getFullId()))) { + MainUtil.sendMessage(player, Captions.NO_PERMISSION, + Captions.PERMISSION_ADMIN_COMMAND.f(getFullId())); + MainUtil.sendMessage(player, Captions.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 index fc92cc550..af0968a92 100644 --- 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 @@ -1,7 +1,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.object.BlockLoc; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; @@ -21,7 +21,7 @@ public class SetHome extends SetCommand { case "none": { Plot base = plot.getBasePlot(false); base.setHome(null); - return MainUtil.sendMessage(player, C.POSITION_UNSET); + return MainUtil.sendMessage(player, Captions.POSITION_UNSET); } case "": Plot base = plot.getBasePlot(false); @@ -31,9 +31,9 @@ public class SetHome extends SetCommand { 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); + return MainUtil.sendMessage(player, Captions.POSITION_SET); default: - MainUtil.sendMessage(player, C.HOME_ARGUMENT); + MainUtil.sendMessage(player, Captions.HOME_ARGUMENT); return false; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Setup.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Setup.java index facea4952..2b7e5ab7f 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Setup.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Setup.java @@ -2,11 +2,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.config.C; +import com.github.intellectualsites.plotsquared.plot.config.Captions; import com.github.intellectualsites.plotsquared.plot.config.Configuration; import com.github.intellectualsites.plotsquared.plot.config.ConfigurationNode; import com.github.intellectualsites.plotsquared.plot.generator.GeneratorWrapper; -import com.github.intellectualsites.plotsquared.plot.object.*; +import com.github.intellectualsites.plotsquared.plot.object.PlotArea; +import com.github.intellectualsites.plotsquared.plot.object.PlotId; +import com.github.intellectualsites.plotsquared.plot.object.PlotMessage; +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; @@ -43,7 +47,7 @@ import java.util.Map.Entry; object = new SetupObject(); player.setMeta("setup", object); SetupUtils.manager.updateGenerators(); - sendMessage(player, C.SETUP_INIT); + sendMessage(player, Captions.SETUP_INIT); displayGenerators(player); return false; } @@ -57,8 +61,9 @@ import java.util.Map.Entry; 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, Captions.SETUP_STEP, object.setup_index + 1, + node.getDescription(), node.getType().getType(), + String.valueOf(node.getDefaultValue())); return false; } else if (object.current > 0) { object.current--; @@ -75,7 +80,7 @@ import java.util.Map.Entry; .join(SetupUtils.generators.keySet(), prefix) .replaceAll(PlotSquared.imp().getPluginName(), "&2" + PlotSquared.imp().getPluginName())); - sendMessage(player, C.SETUP_INIT); + sendMessage(player, Captions.SETUP_INIT); return false; } object.setupGenerator = args[0]; @@ -129,8 +134,9 @@ import java.util.Map.Entry; 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, Captions.SETUP_STEP, object.setup_index + 1, + step.getDescription(), step.getType().getType(), + String.valueOf(step.getDefaultValue())); } else { if (gen.isFull()) { object.plotManager = object.setupGenerator; @@ -182,8 +188,9 @@ import java.util.Map.Entry; MainUtil.sendMessage(player, "&6What should be the minimum Plot Id?"); break; case 3: // min - object.min = PlotId.fromString(args[0]); - if (object.min == null) { + try { + object.min = PlotId.fromString(args[0]); + } catch (IllegalArgumentException ignored) { MainUtil.sendMessage(player, "&cYou must choose a valid minimum PlotId!"); return false; } @@ -192,8 +199,10 @@ import java.util.Map.Entry; break; case 4: // max - PlotId id = PlotId.fromString(args[0]); - if (id == null) { + PlotId id; + try { + id = PlotId.fromString(args[0]); + } catch (IllegalArgumentException ignored) { MainUtil.sendMessage(player, "&cYou must choose a valid maximum PlotId!"); return false; } @@ -228,8 +237,9 @@ import java.util.Map.Entry; .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, Captions.SETUP_STEP, object.setup_index + 1, + step.getDescription(), step.getType().getType(), + String.valueOf(step.getDefaultValue())); break; } case 6: // world setup @@ -241,8 +251,9 @@ import java.util.Map.Entry; } 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, Captions.SETUP_STEP, object.setup_index + 1, + step.getDescription(), step.getType().getType(), + String.valueOf(step.getDefaultValue())); return false; } @@ -250,10 +261,10 @@ import java.util.Map.Entry; try { valid = step.isValid(args[0]); } catch (final Configuration.UnsafeBlockException e) { - C.NOT_ALLOWED_BLOCK.send(player, e.getUnsafeBlock().toString()); + Captions.NOT_ALLOWED_BLOCK.send(player, e.getUnsafeBlock().toString()); } if (valid) { - sendMessage(player, C.SETUP_VALID_ARG, step.getConstant(), args[0]); + sendMessage(player, Captions.SETUP_VALID_ARG, step.getConstant(), args[0]); step.setValue(args[0]); object.setup_index++; if (object.setup_index == object.step.length) { @@ -261,13 +272,15 @@ import java.util.Map.Entry; 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, Captions.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, Captions.SETUP_INVALID_ARG, args[0], step.getConstant()); + sendMessage(player, Captions.SETUP_STEP, object.setup_index + 1, + step.getDescription(), step.getType().getType(), + String.valueOf(step.getDefaultValue())); return false; } case 7: @@ -299,7 +312,7 @@ import java.util.Map.Entry; player.sendMessage("&cAn error occurred. See console for more information"); e.printStackTrace(); } - sendMessage(player, C.SETUP_FINISHED, object.world); + sendMessage(player, Captions.SETUP_FINISHED, object.world); } return false; } @@ -336,7 +349,7 @@ import java.util.Map.Entry; return messages; } - @Override public boolean parseInut(String input) { + @Override public boolean parseInput(String input) { this.generator = input.toLowerCase(); return true; } @@ -376,7 +389,7 @@ import java.util.Map.Entry; return messages; } - @Override public boolean parseInut(String input) { + @Override public boolean parseInput(String input) { if (!WORLD_TYPES.keySet().contains(input.toLowerCase())) { return false; } @@ -407,7 +420,7 @@ import java.util.Map.Entry; public abstract Collection showDescriptionMessage(); - public abstract boolean parseInut(String input); + public abstract boolean parseInput(String input); public final PlotMessage getUsage() { return new PlotMessage("Usage: ").color("$1") 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 index f0055829d..458442ff2 100644 --- 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 @@ -2,7 +2,7 @@ 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.config.Captions; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal2; import com.github.intellectualsites.plotsquared.plot.object.RunnableVal3; @@ -25,6 +25,11 @@ public abstract class SubCommand extends Command { setRequiredArguments(arguments); } + public static boolean sendMessage(PlotPlayer player, Captions message, Object... args) { + message.send(player, args); + return true; + } + @Override public CompletableFuture execute(PlotPlayer player, String[] args, RunnableVal3 confirm, RunnableVal2 whenDone) { @@ -32,9 +37,4 @@ public abstract class SubCommand extends Command { } 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/github/intellectualsites/plotsquared/plot/commands/Swap.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Swap.java index 80a96dfb6..da709d2a3 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Swap.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Swap.java @@ -1,7 +1,7 @@ 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.Captions; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; @@ -9,22 +9,22 @@ 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) + aliases = {"switch"}, category = CommandCategory.CLAIMING, requiredType = RequiredType.PLAYER) public class Swap extends SubCommand { @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); + return !MainUtil.sendMessage(player, Captions.NOT_IN_PLOT); } if (!plot1.isOwner(player.getUUID()) && !Permissions - .hasPermission(player, C.PERMISSION_ADMIN.s())) { - MainUtil.sendMessage(player, C.NO_PLOT_PERMS); + .hasPermission(player, Captions.PERMISSION_ADMIN.s())) { + MainUtil.sendMessage(player, Captions.NO_PLOT_PERMS); return false; } if (args.length != 1) { - C.COMMAND_SYNTAX.send(player, getUsage()); + Captions.COMMAND_SYNTAX.send(player, getUsage()); return false; } Plot plot2 = MainUtil.getPlotFromString(player, args[0], true); @@ -32,22 +32,22 @@ public class Swap extends SubCommand { return false; } if (plot1.equals(plot2)) { - MainUtil.sendMessage(player, C.NOT_VALID_PLOT_ID); - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot copy "); + MainUtil.sendMessage(player, Captions.NOT_VALID_PLOT_ID); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot copy "); return false; } if (!plot1.getArea().isCompatible(plot2.getArea())) { - C.PLOTWORLD_INCOMPATIBLE.send(player); + Captions.PLOTWORLD_INCOMPATIBLE.send(player); return false; } if (plot1.move(plot2, new Runnable() { @Override public void run() { - MainUtil.sendMessage(player, C.SWAP_SUCCESS); + MainUtil.sendMessage(player, Captions.SWAP_SUCCESS); } }, true)) { return true; } else { - MainUtil.sendMessage(player, C.SWAP_OVERLAP); + MainUtil.sendMessage(player, Captions.SWAP_OVERLAP); return false; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Target.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Target.java index 03879463a..4dd37bdb0 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Target.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Target.java @@ -3,7 +3,7 @@ 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.config.Captions; import com.github.intellectualsites.plotsquared.plot.object.Location; import com.github.intellectualsites.plotsquared.plot.object.Plot; import com.github.intellectualsites.plotsquared.plot.object.PlotPlayer; @@ -22,7 +22,7 @@ import com.github.intellectualsites.plotsquared.plot.util.StringMan; @Override public boolean onCommand(PlotPlayer player, String[] args) { Location location = player.getLocation(); if (!location.isPlotArea()) { - MainUtil.sendMessage(player, C.NOT_IN_PLOT_WORLD); + MainUtil.sendMessage(player, Captions.NOT_IN_PLOT_WORLD); return false; } Plot target = null; @@ -36,14 +36,14 @@ import com.github.intellectualsites.plotsquared.plot.util.StringMan; } } if (target == null) { - MainUtil.sendMessage(player, C.FOUND_NO_PLOTS); + MainUtil.sendMessage(player, Captions.FOUND_NO_PLOTS); return false; } } else if ((target = MainUtil.getPlotFromString(player, args[0], true)) == null) { return false; } player.setCompassTarget(target.getCenter()); - MainUtil.sendMessage(player, C.COMPASS_TARGET); + MainUtil.sendMessage(player, Captions.COMPASS_TARGET); return true; } } diff --git a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Template.java b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Template.java index aed9c5ca6..eb96f78cc 100644 --- a/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Template.java +++ b/Core/src/main/java/com/github/intellectualsites/plotsquared/plot/commands/Template.java @@ -5,7 +5,7 @@ import com.github.intellectualsites.plotsquared.configuration.ConfigurationSecti 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.Captions; import com.github.intellectualsites.plotsquared.plot.config.ConfigurationNode; import com.github.intellectualsites.plotsquared.plot.config.Settings; import com.github.intellectualsites.plotsquared.plot.object.*; @@ -33,11 +33,11 @@ import java.util.zip.ZipOutputStream; if (!folder.exists()) { return false; } - File input = new File(folder + File.separator + template + ".template"); File output = PlotSquared.get().IMP.getDirectory(); if (!output.exists()) { output.mkdirs(); } + File input = new File(folder + File.separator + template + ".template"); try (ZipInputStream zis = new ZipInputStream(new FileInputStream(input))) { ZipEntry ze = zis.getNextEntry(); byte[] buffer = new byte[2048]; @@ -63,9 +63,6 @@ import java.util.zip.ZipOutputStream; zis.closeEntry(); } return true; - } catch (FileNotFoundException e) { - e.printStackTrace(); - return false; } catch (IOException e) { e.printStackTrace(); return false; @@ -107,15 +104,16 @@ import java.util.zip.ZipOutputStream; if (args.length != 2 && args.length != 3) { if (args.length == 1) { if (args[0].equalsIgnoreCase("export")) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot template export "); + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, + "/plot template export "); return true; } else if (args[0].equalsIgnoreCase("import")) { - MainUtil.sendMessage(player, C.COMMAND_SYNTAX, + MainUtil.sendMessage(player, Captions.COMMAND_SYNTAX, "/plot template import