diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java index 0ed26be89..d2f17c464 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/BukkitPlatform.java @@ -68,7 +68,6 @@ import com.plotsquared.bukkit.uuid.SquirrelIdUUIDService; import com.plotsquared.core.PlotPlatform; import com.plotsquared.core.PlotSquared; import com.plotsquared.core.backup.BackupManager; -import com.plotsquared.core.command.WE_Anywhere; import com.plotsquared.core.components.ComponentPresetManager; import com.plotsquared.core.configuration.ConfigurationNode; import com.plotsquared.core.configuration.ConfigurationSection; @@ -162,7 +161,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; -import static com.plotsquared.bukkit.util.JavaVersionCheck.checkJvm; import static com.plotsquared.core.util.PremiumVerification.getDownloadID; import static com.plotsquared.core.util.PremiumVerification.getResourceID; import static com.plotsquared.core.util.PremiumVerification.getUserID; @@ -321,9 +319,6 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl try { logger.info("{} hooked into WorldEdit", this.pluginName()); WorldEdit.getInstance().getEventBus().register(this.injector().getInstance(WESubscriber.class)); - if (Settings.Enabled_Components.COMMANDS) { - new WE_Anywhere(); - } } catch (Throwable e) { logger.error( "Incompatible version of WorldEdit, please upgrade: https://builds.enginehub.org/job/worldedit?branch=master"); @@ -542,10 +537,9 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } }, 100L, 100L); - // Check whether the server runs on 11 or greater - checkJvm(); // Check if we are in a safe environment ServerLib.checkUnsafeForks(); + // Check whether the server runs on 16 or greater ServerLib.checkJavaLTS(); } @@ -947,8 +941,7 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl if (Settings.Enabled_Components.KILL_ROAD_MOBS) { Location location = entity.getLocation(); if (BukkitUtil.adapt(location).isPlotRoad()) { - if (entity instanceof LivingEntity) { - LivingEntity livingEntity = (LivingEntity) entity; + if (entity instanceof LivingEntity livingEntity) { if ((Settings.Enabled_Components.KILL_OWNED_ROAD_MOBS || !livingEntity.isLeashed()) || !entity.hasMetadata("keep")) { Entity passenger = entity.getPassenger(); @@ -976,7 +969,6 @@ public final class BukkitPlatform extends JavaPlugin implements Listener, PlotPl } } } - continue; } } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/entity/ReplicatingEntityWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/entity/ReplicatingEntityWrapper.java index 5d1f369a9..30c1906c5 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/entity/ReplicatingEntityWrapper.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/entity/ReplicatingEntityWrapper.java @@ -189,8 +189,7 @@ public final class ReplicatingEntityWrapper extends EntityWrapper { AbstractHorse horse = (AbstractHorse) entity; this.horse = new HorseStats(); this.horse.jump = horse.getJumpStrength(); - if (horse instanceof ChestedHorse) { - ChestedHorse horse1 = (ChestedHorse) horse; + if (horse instanceof ChestedHorse horse1) { this.horse.chest = horse1.isCarryingChest(); } //todo these horse features need fixing diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java index ffbe892ec..af5de4247 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/BlockEventListener.java @@ -243,22 +243,13 @@ public class BlockEventListener implements Listener { default: if (Settings.Redstone.DETECT_INVALID_EDGE_PISTONS) { switch (block.getType()) { - case PISTON: - case STICKY_PISTON: + case PISTON, STICKY_PISTON -> { org.bukkit.block.data.Directional piston = (org.bukkit.block.data.Directional) block.getBlockData(); switch (piston.getFacing()) { - case EAST: - location = location.add(1, 0, 0); - break; - case SOUTH: - location = location.add(-1, 0, 0); - break; - case WEST: - location = location.add(0, 0, 1); - break; - case NORTH: - location = location.add(0, 0, -1); - break; + case EAST -> location = location.add(1, 0, 0); + case SOUTH -> location = location.add(-1, 0, 0); + case WEST -> location = location.add(0, 0, 1); + case NORTH -> location = location.add(0, 0, -1); } Plot newPlot = area.getOwnedPlotAbs(location); if (!plot.equals(newPlot)) { @@ -266,6 +257,7 @@ public class BlockEventListener implements Listener { plot.debug("Prevented piston update because of invalid edge piston detection"); return; } + } } } break; @@ -548,8 +540,7 @@ public class BlockEventListener implements Listener { } boolean allowed = plot.getFlag(flag); Entity entity = event.getEntity(); - if (entity instanceof Player) { - Player player = (Player) entity; + if (entity instanceof Player player) { BukkitPlayer plotPlayer = BukkitUtil.adapt(player); if (!plot.isAdded(plotPlayer.getUUID())) { if (allowed) { @@ -889,37 +880,7 @@ public class BlockEventListener implements Listener { public void onBlockDispense(BlockDispenseEvent event) { Material type = event.getItem().getType(); switch (type) { - case SHULKER_BOX: - case WHITE_SHULKER_BOX: - case ORANGE_SHULKER_BOX: - case MAGENTA_SHULKER_BOX: - case LIGHT_BLUE_SHULKER_BOX: - case YELLOW_SHULKER_BOX: - case LIME_SHULKER_BOX: - case PINK_SHULKER_BOX: - case GRAY_SHULKER_BOX: - case LIGHT_GRAY_SHULKER_BOX: - case CYAN_SHULKER_BOX: - case PURPLE_SHULKER_BOX: - case BLUE_SHULKER_BOX: - case BROWN_SHULKER_BOX: - case GREEN_SHULKER_BOX: - case RED_SHULKER_BOX: - case BLACK_SHULKER_BOX: - case CARVED_PUMPKIN: - case WITHER_SKELETON_SKULL: - case FLINT_AND_STEEL: - case BONE_MEAL: - case SHEARS: - case GLASS_BOTTLE: - case GLOWSTONE: - case COD_BUCKET: - case PUFFERFISH_BUCKET: - case SALMON_BUCKET: - case TROPICAL_FISH_BUCKET: - case BUCKET: - case WATER_BUCKET: - case LAVA_BUCKET: { + case SHULKER_BOX, WHITE_SHULKER_BOX, ORANGE_SHULKER_BOX, MAGENTA_SHULKER_BOX, LIGHT_BLUE_SHULKER_BOX, YELLOW_SHULKER_BOX, LIME_SHULKER_BOX, PINK_SHULKER_BOX, GRAY_SHULKER_BOX, LIGHT_GRAY_SHULKER_BOX, CYAN_SHULKER_BOX, PURPLE_SHULKER_BOX, BLUE_SHULKER_BOX, BROWN_SHULKER_BOX, GREEN_SHULKER_BOX, RED_SHULKER_BOX, BLACK_SHULKER_BOX, CARVED_PUMPKIN, WITHER_SKELETON_SKULL, FLINT_AND_STEEL, BONE_MEAL, SHEARS, GLASS_BOTTLE, GLOWSTONE, COD_BUCKET, PUFFERFISH_BUCKET, SALMON_BUCKET, TROPICAL_FISH_BUCKET, BUCKET, WATER_BUCKET, LAVA_BUCKET -> { if (event.getBlock().getType() == Material.DROPPER) { return; } @@ -1100,8 +1061,7 @@ public class BlockEventListener implements Listener { if (ignitingEntity instanceof Fireball) { Projectile fireball = (Projectile) ignitingEntity; Location location = null; - if (fireball.getShooter() instanceof Entity) { - Entity shooter = (Entity) fireball.getShooter(); + if (fireball.getShooter() instanceof Entity shooter) { location = BukkitUtil.adapt(shooter.getLocation()); } else if (fireball.getShooter() instanceof BlockProjectileSource) { Block shooter = diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ChunkListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ChunkListener.java index b3e507dce..983049ece 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ChunkListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/ChunkListener.java @@ -259,7 +259,7 @@ public class ChunkListener implements Listener { private void cleanChunk(final Chunk chunk) { TaskManager.index.incrementAndGet(); - final Integer currentIndex = TaskManager.index.get(); + final int currentIndex = TaskManager.index.get(); PlotSquaredTask task = TaskManager.runTaskRepeat(() -> { if (!chunk.isLoaded()) { Objects.requireNonNull(TaskManager.removeTask(currentIndex)).cancel(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java index 3c2988dae..11785e731 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/EntityEventListener.java @@ -111,8 +111,7 @@ public class EntityEventListener implements Listener { */ if (!BukkitEntityUtil.entityDamage(damager, victim, event.getCause())) { if (event.isCancelled()) { - if (victim instanceof Ageable) { - Ageable ageable = (Ageable) victim; + if (victim instanceof Ageable ageable) { if (ageable.getAge() == -24000) { ageable.setAge(0); ageable.setAdult(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java index ee1d4d91a..36074908c 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/PlayerEventListener.java @@ -436,8 +436,7 @@ public class PlayerEventListener extends PlotListener implements Listener { if (!vehicle.getPassengers().isEmpty()) { Entity passenger = vehicle.getPassengers().get(0); - if (passenger instanceof Player) { - final Player player = (Player) passenger; + if (passenger instanceof final Player player) { // reset if (moveTmp == null) { moveTmp = new PlayerMoveEvent(null, from, to); @@ -778,10 +777,9 @@ public class PlayerEventListener extends PlotListener implements Listener { } HumanEntity clicker = event.getWhoClicked(); - if (!(clicker instanceof Player)) { + if (!(clicker instanceof Player player)) { return; } - Player player = (Player) clicker; BukkitPlayer pp = BukkitUtil.adapt(player); final PlotInventory inventory = PlotInventory.getOpenPlotInventory(pp); if (inventory != null && event.getRawSlot() == event.getSlot()) { @@ -1029,7 +1027,6 @@ public class PlayerEventListener extends PlotListener implements Listener { Block block = event.getClickedBlock(); Location location = BukkitUtil.adapt(block.getLocation()); Action action = event.getAction(); - outer: switch (action) { case PHYSICAL: { eventType = PlayerBlockEventType.TRIGGER_PHYSICAL; @@ -1077,12 +1074,12 @@ public class PlayerEventListener extends PlotListener implements Listener { if (PaperLib.isPaper()) { if (MaterialTags.SPAWN_EGGS.isTagged(type) || Material.EGG.equals(type)) { eventType = PlayerBlockEventType.SPAWN_MOB; - break outer; + break; } } else { if (type.toString().toLowerCase().endsWith("egg")) { eventType = PlayerBlockEventType.SPAWN_MOB; - break outer; + break; } } if (type.isEdible()) { @@ -1090,34 +1087,13 @@ public class PlayerEventListener extends PlotListener implements Listener { return; } switch (type) { - case ACACIA_BOAT: - case BIRCH_BOAT: - case CHEST_MINECART: - case COMMAND_BLOCK_MINECART: - case DARK_OAK_BOAT: - case FURNACE_MINECART: - case HOPPER_MINECART: - case JUNGLE_BOAT: - case MINECART: - case OAK_BOAT: - case SPRUCE_BOAT: - case TNT_MINECART: - eventType = PlayerBlockEventType.PLACE_VEHICLE; - break outer; - case FIREWORK_ROCKET: - case FIREWORK_STAR: - eventType = PlayerBlockEventType.SPAWN_MOB; - break outer; - case BOOK: - case KNOWLEDGE_BOOK: - case WRITABLE_BOOK: - case WRITTEN_BOOK: - eventType = PlayerBlockEventType.READ; - break outer; - case ARMOR_STAND: + case ACACIA_BOAT, BIRCH_BOAT, CHEST_MINECART, COMMAND_BLOCK_MINECART, DARK_OAK_BOAT, FURNACE_MINECART, HOPPER_MINECART, JUNGLE_BOAT, MINECART, OAK_BOAT, SPRUCE_BOAT, TNT_MINECART -> eventType = PlayerBlockEventType.PLACE_VEHICLE; + case FIREWORK_ROCKET, FIREWORK_STAR -> eventType = PlayerBlockEventType.SPAWN_MOB; + case BOOK, KNOWLEDGE_BOOK, WRITABLE_BOOK, WRITTEN_BOOK -> eventType = PlayerBlockEventType.READ; + case ARMOR_STAND -> { location = BukkitUtil.adapt(block.getRelative(event.getBlockFace()).getLocation()); eventType = PlayerBlockEventType.PLACE_MISC; - break outer; + } } break; } @@ -1231,10 +1207,9 @@ public class PlayerEventListener extends PlotListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public void onInventoryClose(InventoryCloseEvent event) { HumanEntity closer = event.getPlayer(); - if (!(closer instanceof Player)) { + if (!(closer instanceof Player player)) { return; } - Player player = (Player) closer; PlotInventory.removePlotInventoryOpen(BukkitUtil.adapt(player)); } @@ -1359,8 +1334,7 @@ public class PlayerEventListener extends PlotListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onHangingBreakByEntity(HangingBreakByEntityEvent event) { Entity remover = event.getRemover(); - if (remover instanceof Player) { - Player p = (Player) remover; + if (remover instanceof Player p) { Location location = BukkitUtil.adapt(event.getEntity().getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { @@ -1398,10 +1372,8 @@ public class PlayerEventListener extends PlotListener implements Listener { + " could not break hanging entity because hanging-break = false"); } } - } else if (remover instanceof Projectile) { - Projectile p = (Projectile) remover; - if (p.getShooter() instanceof Player) { - Player shooter = (Player) p.getShooter(); + } else if (remover instanceof Projectile p) { + if (p.getShooter() instanceof Player shooter) { Location location = BukkitUtil.adapt(event.getEntity().getLocation()); PlotArea area = location.getPlotArea(); if (area == null) { @@ -1535,8 +1507,7 @@ public class PlayerEventListener extends PlotListener implements Listener { return; } Entity attacker = event.getAttacker(); - if (attacker instanceof Player) { - Player p = (Player) attacker; + if (attacker instanceof Player p) { BukkitPlayer pp = BukkitUtil.adapt(p); Plot plot = area.getPlot(location); if (plot == null) { @@ -1642,8 +1613,7 @@ public class PlayerEventListener extends PlotListener implements Listener { @EventHandler public void onItemPickup(EntityPickupItemEvent event) { LivingEntity ent = event.getEntity(); - if (ent instanceof Player) { - Player player = (Player) ent; + if (ent instanceof Player player) { BukkitPlayer pp = BukkitUtil.adapt(player); Location location = pp.getLocation(); PlotArea area = location.getPlotArea(); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/SingleWorldListener.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/SingleWorldListener.java index e056218d8..40abdb0ec 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/SingleWorldListener.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/SingleWorldListener.java @@ -45,7 +45,7 @@ import static com.plotsquared.core.util.ReflectionUtils.getRefClass; @SuppressWarnings("unused") public class SingleWorldListener implements Listener { - private Method methodGetHandleChunk; + private final Method methodGetHandleChunk; private Field mustSave; private boolean isTrueForNotSave = true; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/WorldEvents.java b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/WorldEvents.java index f8dd2f337..18ca43367 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/listener/WorldEvents.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/listener/WorldEvents.java @@ -53,8 +53,7 @@ public class WorldEvents implements Listener { public void onWorldInit(WorldInitEvent event) { World world = event.getWorld(); String name = world.getName(); - if (this.plotAreaManager instanceof SinglePlotAreaManager) { - final SinglePlotAreaManager single = (SinglePlotAreaManager) this.plotAreaManager; + if (this.plotAreaManager instanceof final SinglePlotAreaManager single) { if (single.isWorld(name)) { world.setKeepSpawnInMemory(false); return; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/managers/MultiverseWorldManager.java b/Bukkit/src/main/java/com/plotsquared/bukkit/managers/MultiverseWorldManager.java index 60e4f927d..97e4beac4 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/managers/MultiverseWorldManager.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/managers/MultiverseWorldManager.java @@ -34,7 +34,10 @@ import org.checkerframework.checker.nullness.qual.Nullable; /** * Multiverse specific manager that informs Multiverse of * world creation by executing a console command + * @deprecated Deprecated and scheduled for removal without replacement + * in favor of the build in setup wizard. */ +@Deprecated @Singleton public class MultiverseWorldManager extends BukkitWorldManager { diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java index f860af7c1..2f003418f 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/BukkitPermissionHandler.java @@ -52,8 +52,7 @@ public class BukkitPermissionHandler implements PermissionHandler { public Optional getPermissionProfile( @NonNull PlotPlayer playerPlotPlayer ) { - if (playerPlotPlayer instanceof BukkitPlayer) { - final BukkitPlayer bukkitPlayer = (BukkitPlayer) playerPlotPlayer; + if (playerPlotPlayer instanceof final BukkitPlayer bukkitPlayer) { return Optional.of(new BukkitPermissionProfile(bukkitPlayer.getPlatformPlayer())); } else if (playerPlotPlayer instanceof ConsolePlayer) { return Optional.of(ConsolePermissionProfile.INSTANCE); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java index cc2f433b7..e7f6401d1 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/permissions/VaultPermissionHandler.java @@ -65,8 +65,7 @@ public class VaultPermissionHandler implements PermissionHandler { public Optional getPermissionProfile( @NonNull PlotPlayer playerPlotPlayer ) { - if (playerPlotPlayer instanceof BukkitPlayer) { - final BukkitPlayer bukkitPlayer = (BukkitPlayer) playerPlotPlayer; + if (playerPlotPlayer instanceof final BukkitPlayer bukkitPlayer) { return Optional.of(new VaultPermissionProfile(bukkitPlayer.getPlatformPlayer())); } else if (playerPlotPlayer instanceof ConsolePlayer) { return Optional.of(ConsolePermissionProfile.INSTANCE); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java index 095533587..b5c2b47d7 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/player/BukkitPlayer.java @@ -263,32 +263,20 @@ public class BukkitPlayer extends PlotPlayer { @Override public void setWeather(final @NonNull PlotWeather weather) { switch (weather) { - case CLEAR: - this.player.setPlayerWeather(WeatherType.CLEAR); - break; - case RAIN: - this.player.setPlayerWeather(WeatherType.DOWNFALL); - break; - case RESET: - default: - this.player.resetPlayerWeather(); - break; + case CLEAR -> this.player.setPlayerWeather(WeatherType.CLEAR); + case RAIN -> this.player.setPlayerWeather(WeatherType.DOWNFALL); + default -> this.player.resetPlayerWeather(); } } @Override public com.sk89q.worldedit.world.gamemode.GameMode getGameMode() { - switch (this.player.getGameMode()) { - case ADVENTURE: - return ADVENTURE; - case CREATIVE: - return CREATIVE; - case SPECTATOR: - return SPECTATOR; - case SURVIVAL: - default: - return SURVIVAL; - } + return switch (this.player.getGameMode()) { + case ADVENTURE -> ADVENTURE; + case CREATIVE -> CREATIVE; + case SPECTATOR -> SPECTATOR; + default -> SURVIVAL; + }; } @Override @@ -372,14 +360,11 @@ public class BukkitPlayer extends PlotPlayer { } public PlayerTeleportEvent.TeleportCause getTeleportCause(final @NonNull TeleportCause cause) { - switch (cause) { - case COMMAND: - return PlayerTeleportEvent.TeleportCause.COMMAND; - case PLUGIN: - return PlayerTeleportEvent.TeleportCause.PLUGIN; - default: - return PlayerTeleportEvent.TeleportCause.UNKNOWN; - } + return switch (cause) { + case COMMAND -> PlayerTeleportEvent.TeleportCause.COMMAND; + case PLUGIN -> PlayerTeleportEvent.TeleportCause.PLUGIN; + default -> PlayerTeleportEvent.TeleportCause.UNKNOWN; + }; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/schematic/StateWrapper.java b/Bukkit/src/main/java/com/plotsquared/bukkit/schematic/StateWrapper.java index 1903d8e24..f109f4710 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/schematic/StateWrapper.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/schematic/StateWrapper.java @@ -177,19 +177,11 @@ public class StateWrapper { } org.bukkit.block.BlockState state = block.getState(); switch (getId()) { - case "chest": - case "beacon": - case "brewingstand": - case "dispenser": - case "dropper": - case "furnace": - case "hopper": - case "shulkerbox": - if (!(state instanceof Container)) { + case "chest", "beacon", "brewingstand", "dispenser", "dropper", "furnace", "hopper", "shulkerbox" -> { + if (!(state instanceof Container container)) { return false; } List itemsTag = this.tag.getListTag("Items").getValue(); - Container container = (Container) state; Inventory inv = container.getSnapshotInventory(); for (Tag itemTag : itemsTag) { CompoundTag itemComp = (CompoundTag) itemTag; @@ -206,9 +198,9 @@ public class StateWrapper { } container.update(true, false); return true; - case "sign": - if (state instanceof Sign) { - Sign sign = (Sign) state; + } + case "sign" -> { + if (state instanceof Sign sign) { sign.setLine(0, jsonToColourCode(tag.getString("Text1"))); sign.setLine(1, jsonToColourCode(tag.getString("Text2"))); sign.setLine(2, jsonToColourCode(tag.getString("Text3"))); @@ -217,6 +209,7 @@ public class StateWrapper { return true; } return false; + } } return false; } @@ -225,8 +218,7 @@ public class StateWrapper { if (this.tag != null) { return this.tag; } - if (this.state instanceof InventoryHolder) { - InventoryHolder inv = (InventoryHolder) this.state; + if (this.state instanceof InventoryHolder inv) { ItemStack[] contents = inv.getInventory().getContents(); Map values = new HashMap<>(); values.put("Items", new ListTag(CompoundTag.class, serializeInventory(contents))); diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEntityUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEntityUtil.java index f094a8334..76890c957 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEntityUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitEntityUtil.java @@ -144,8 +144,7 @@ public class BukkitEntityUtil { Player player; if (damager instanceof Player) { // attacker is player player = (Player) damager; - } else if (damager instanceof Projectile) { - Projectile projectile = (Projectile) damager; + } else if (damager instanceof Projectile projectile) { ProjectileSource shooter = projectile.getShooter(); if (shooter instanceof Player) { // shooter is player player = (Player) shooter; diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java index 9fed3dd1e..03c8da626 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitSetupUtils.java @@ -135,7 +135,7 @@ public class BukkitSetupUtils extends SetupUtils { PlotAreaType type = builder.plotAreaType(); String worldPath = "worlds." + builder.worldName(); switch (type) { - case PARTIAL: { + case PARTIAL -> { if (builder.areaName() != null) { if (!this.worldConfiguration.contains(worldPath)) { this.worldConfiguration.createSection(worldPath); @@ -177,9 +177,8 @@ public class BukkitSetupUtils extends SetupUtils { if (gen != null && gen.isFull()) { builder.generatorName(null); } - break; } - case AUGMENTED: { + case AUGMENTED -> { if (!builder.plotManager().endsWith(":single")) { if (!this.worldConfiguration.contains(worldPath)) { this.worldConfiguration.createSection(worldPath); @@ -207,9 +206,8 @@ public class BukkitSetupUtils extends SetupUtils { if (gen != null && gen.isFull()) { builder.generatorName(null); } - break; } - case NORMAL: { + case NORMAL -> { if (steps.length != 0) { if (!this.worldConfiguration.contains(worldPath)) { this.worldConfiguration.createSection(worldPath); @@ -220,7 +218,6 @@ public class BukkitSetupUtils extends SetupUtils { worldSection.set(step.getConstant(), step.getValue()); } } - break; } } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java index 9934e21b8..0efe0a914 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitUtil.java @@ -297,8 +297,7 @@ public class BukkitUtil extends WorldUtil { ); try { return TaskManager.getPlatformImplementation().sync(() -> { - if (block.getState() instanceof Sign) { - Sign sign = (Sign) block.getState(); + if (block.getState() instanceof Sign sign) { return sign.getLines(); } return new String[0]; @@ -364,8 +363,7 @@ public class BukkitUtil extends WorldUtil { block.setBlockData(sign, false); } final org.bukkit.block.BlockState blockstate = block.getState(); - if (blockstate instanceof Sign) { - final Sign sign = (Sign) blockstate; + if (blockstate instanceof final Sign sign) { for (int i = 0; i < lines.length; i++) { sign.setLine(i, LEGACY_COMPONENT_SERIALIZER .serialize(MINI_MESSAGE.parse(lines[i].getComponent(LocaleHolder.console()), replacements))); @@ -454,23 +452,20 @@ public class BukkitUtil extends WorldUtil { public @NonNull Set getTypesInCategory(final @NonNull String category) { final Collection> allowedInterfaces = new HashSet<>(); switch (category) { - case "animal": { + case "animal" -> { allowedInterfaces.add(IronGolem.class); allowedInterfaces.add(Snowman.class); allowedInterfaces.add(Animals.class); allowedInterfaces.add(WaterMob.class); allowedInterfaces.add(Ambient.class); } - break; - case "tameable": { + case "tameable" -> { allowedInterfaces.add(Tameable.class); } - break; - case "vehicle": { + case "vehicle" -> { allowedInterfaces.add(Vehicle.class); } - break; - case "hostile": { + case "hostile" -> { allowedInterfaces.add(Shulker.class); allowedInterfaces.add(Monster.class); allowedInterfaces.add(Boss.class); @@ -479,20 +474,16 @@ public class BukkitUtil extends WorldUtil { allowedInterfaces.add(Phantom.class); allowedInterfaces.add(EnderCrystal.class); } - break; - case "hanging": { + case "hanging" -> { allowedInterfaces.add(Hanging.class); } - break; - case "villager": { + case "villager" -> { allowedInterfaces.add(NPC.class); } - break; - case "projectile": { + case "projectile" -> { allowedInterfaces.add(Projectile.class); } - break; - case "other": { + case "other" -> { allowedInterfaces.add(ArmorStand.class); allowedInterfaces.add(FallingBlock.class); allowedInterfaces.add(Item.class); @@ -504,15 +495,12 @@ public class BukkitUtil extends WorldUtil { allowedInterfaces.add(EnderSignal.class); allowedInterfaces.add(Firework.class); } - break; - case "player": { + case "player" -> { allowedInterfaces.add(Player.class); } - break; - default: { + default -> { logger.error("Unknown entity category requested: {}", category); } - break; } final Set types = new HashSet<>(); outer: diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitWorld.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitWorld.java index 8a2e9edcb..7dff7340f 100644 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitWorld.java +++ b/Bukkit/src/main/java/com/plotsquared/bukkit/util/BukkitWorld.java @@ -87,10 +87,9 @@ public class BukkitWorld implements World { if (o == this) { return true; } - if (!(o instanceof BukkitWorld)) { + if (!(o instanceof final BukkitWorld other)) { return false; } - final BukkitWorld other = (BukkitWorld) o; if (!other.canEqual(this)) { return false; } diff --git a/Bukkit/src/main/java/com/plotsquared/bukkit/util/JavaVersionCheck.java b/Bukkit/src/main/java/com/plotsquared/bukkit/util/JavaVersionCheck.java deleted file mode 100644 index c09fc19ea..000000000 --- a/Bukkit/src/main/java/com/plotsquared/bukkit/util/JavaVersionCheck.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * _____ _ _ _____ _ - * | __ \| | | | / ____| | | - * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | - * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | - * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | - * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| - * | | - * |_| - * PlotSquared plot management system for Minecraft - * Copyright (C) 2021 IntellectualSites - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.plotsquared.bukkit.util; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class JavaVersionCheck { - - private static final Logger logger = LoggerFactory.getLogger("P2/" + JavaVersionCheck.class.getSimpleName()); - - private static int checkJavaVersion() { - String javaVersion = System.getProperty("java.version"); - final Matcher matcher = Pattern.compile("(?:1\\.)?(\\d+)").matcher(javaVersion); - if (!matcher.find()) { - logger.error("Failed to determine Java version; Could not parse: {}", javaVersion); - return -1; - } - - final String version = matcher.group(1); - try { - return Integer.parseInt(version); - } catch (final NumberFormatException e) { - logger.error("Failed to determine Java version; Could not parse {} from {}", version, javaVersion, e); - return -1; - } - } - - public static void checkJvm() { - if (checkJavaVersion() < 11) { - logger.error("************************************************************"); - logger.error("* WARNING - YOU ARE RUNNING AN OUTDATED VERSION OF JAVA."); - logger.error("* PLOTSQUARED WILL STOP BEING COMPATIBLE WITH THIS VERSION OF"); - logger.error("* JAVA WHEN MINECRAFT 1.17 IS RELEASED."); - logger.error("*"); - logger.error("* Please update the version of Java to 11. When Minecraft 1.17"); - logger.error("* is released, support for versions of Java prior to 11 will"); - logger.error("* be dropped."); - logger.error("*"); - logger.error("* Current Java version: {}", System.getProperty("java.version")); - logger.error("************************************************************"); - } - } - -} diff --git a/Core/src/main/java/com/plotsquared/core/PlotPlatform.java b/Core/src/main/java/com/plotsquared/core/PlotPlatform.java index 7a61f8c89..c1424f99d 100644 --- a/Core/src/main/java/com/plotsquared/core/PlotPlatform.java +++ b/Core/src/main/java/com/plotsquared/core/PlotPlatform.java @@ -233,7 +233,7 @@ public interface PlotPlatform

extends LocaleHolder { } /** - * Get the {@link SetupUtils} implementation for the platform + * Get the {@link SetupUtils} implementation for the platform * * @return Setup utils */ diff --git a/Core/src/main/java/com/plotsquared/core/PlotSquared.java b/Core/src/main/java/com/plotsquared/core/PlotSquared.java index eaa2da7c4..67d52c72e 100644 --- a/Core/src/main/java/com/plotsquared/core/PlotSquared.java +++ b/Core/src/main/java/com/plotsquared/core/PlotSquared.java @@ -1077,22 +1077,15 @@ public class PlotSquared { try { String base = "worlds." + world + "."; switch (key) { - case "s": - case "size": - this.worldConfiguration.set( - base + "plot.size", - ConfigurationUtil.INTEGER.parseString(value).shortValue() - ); - break; - case "g": - case "gap": - this.worldConfiguration.set( - base + "road.width", - ConfigurationUtil.INTEGER.parseString(value).shortValue() - ); - break; - case "h": - case "height": + case "s", "size" -> this.worldConfiguration.set( + base + "plot.size", + ConfigurationUtil.INTEGER.parseString(value).shortValue() + ); + case "g", "gap" -> this.worldConfiguration.set( + base + "road.width", + ConfigurationUtil.INTEGER.parseString(value).shortValue() + ); + case "h", "height" -> { this.worldConfiguration.set( base + "road.height", ConfigurationUtil.INTEGER.parseString(value).shortValue() @@ -1105,38 +1098,27 @@ public class PlotSquared { base + "wall.height", ConfigurationUtil.INTEGER.parseString(value).shortValue() ); - break; - case "f": - case "floor": - this.worldConfiguration.set( - base + "plot.floor", - ConfigurationUtil.BLOCK_BUCKET.parseString(value).toString() - ); - break; - case "m": - case "main": - this.worldConfiguration.set( - base + "plot.filling", - ConfigurationUtil.BLOCK_BUCKET.parseString(value).toString() - ); - break; - case "w": - case "wall": - this.worldConfiguration.set( - base + "wall.filling", - ConfigurationUtil.BLOCK_BUCKET.parseString(value).toString() - ); - break; - case "b": - case "border": - this.worldConfiguration.set( - base + "wall.block", - ConfigurationUtil.BLOCK_BUCKET.parseString(value).toString() - ); - break; - default: + } + case "f", "floor" -> this.worldConfiguration.set( + base + "plot.floor", + ConfigurationUtil.BLOCK_BUCKET.parseString(value).toString() + ); + case "m", "main" -> this.worldConfiguration.set( + base + "plot.filling", + ConfigurationUtil.BLOCK_BUCKET.parseString(value).toString() + ); + case "w", "wall" -> this.worldConfiguration.set( + base + "wall.filling", + ConfigurationUtil.BLOCK_BUCKET.parseString(value).toString() + ); + case "b", "border" -> this.worldConfiguration.set( + base + "wall.block", + ConfigurationUtil.BLOCK_BUCKET.parseString(value).toString() + ); + default -> { logger.error("Key not found: {}", element); return false; + } } } catch (Exception e) { logger.error("Invalid value '{}' for arg '{}'", value, element); diff --git a/Core/src/main/java/com/plotsquared/core/collection/FlatRandomCollection.java b/Core/src/main/java/com/plotsquared/core/collection/FlatRandomCollection.java index 486690d68..7fe04d869 100644 --- a/Core/src/main/java/com/plotsquared/core/collection/FlatRandomCollection.java +++ b/Core/src/main/java/com/plotsquared/core/collection/FlatRandomCollection.java @@ -33,7 +33,7 @@ import java.util.Random; public class FlatRandomCollection extends RandomCollection { - private T[] values; + private final T[] values; public FlatRandomCollection(Map weights, Random random) { super(weights, random); diff --git a/Core/src/main/java/com/plotsquared/core/command/Alias.java b/Core/src/main/java/com/plotsquared/core/command/Alias.java index 1e99da8c3..8d0aee292 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Alias.java +++ b/Core/src/main/java/com/plotsquared/core/command/Alias.java @@ -82,12 +82,11 @@ public class Alias extends SubCommand { boolean permission; boolean admin; switch (args[0].toLowerCase()) { - case "set": + case "set" -> { if (args.length != 2) { sendUsage(player); return false; } - permission = isPermitted(player, Permission.PERMISSION_ALIAS_SET); admin = isPermitted(player, Permission.PERMISSION_ADMIN_ALIAS_SET); if (!admin && !owner) { @@ -103,9 +102,8 @@ public class Alias extends SubCommand { Template.of("node", String.valueOf(Permission.PERMISSION_ALIAS_SET)) ); } - - break; - case "remove": + } + case "remove" -> { permission = isPermitted(player, Permission.PERMISSION_ALIAS_REMOVE); admin = isPermitted(player, Permission.PERMISSION_ADMIN_ALIAS_REMOVE); if (!admin && !owner) { @@ -120,10 +118,11 @@ public class Alias extends SubCommand { Template.of("node", String.valueOf(Permission.PERMISSION_ALIAS_REMOVE)) ); } - break; - default: + } + default -> { sendUsage(player); result = false; + } } return result; diff --git a/Core/src/main/java/com/plotsquared/core/command/Area.java b/Core/src/main/java/com/plotsquared/core/command/Area.java index a63a1a7ea..dec90632b 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Area.java +++ b/Core/src/main/java/com/plotsquared/core/command/Area.java @@ -109,7 +109,6 @@ public class Area extends SubCommand { private final HybridPlotWorldFactory hybridPlotWorldFactory; private final SetupUtils setupUtils; private final WorldUtil worldUtil; - private final RegionManager regionManager; private final GlobalBlockQueue blockQueue; private final Map> metaData = new HashMap<>(); @@ -122,7 +121,6 @@ public class Area extends SubCommand { final @NonNull HybridPlotWorldFactory hybridPlotWorldFactory, final @NonNull SetupUtils setupUtils, final @NonNull WorldUtil worldUtil, - final @NonNull RegionManager regionManager, final @NonNull GlobalBlockQueue blockQueue ) { this.plotAreaManager = plotAreaManager; @@ -131,7 +129,6 @@ public class Area extends SubCommand { this.hybridPlotWorldFactory = hybridPlotWorldFactory; this.setupUtils = setupUtils; this.worldUtil = worldUtil; - this.regionManager = regionManager; this.blockQueue = blockQueue; } @@ -142,7 +139,7 @@ public class Area extends SubCommand { return false; } switch (args[0].toLowerCase()) { - case "single": + case "single" -> { if (player instanceof ConsolePlayer) { player.sendMessage(RequiredType.CONSOLE.getErrorMessage()); return false; @@ -195,14 +192,16 @@ public class Area extends SubCommand { final BlockVector3 playerSelectionMax = playerSelectedRegion.getMaximumPoint(); // Create a new selection that spans the entire vertical range of the world final CuboidRegion selectedRegion = - new CuboidRegion(playerSelectedRegion.getWorld(), + new CuboidRegion( + playerSelectedRegion.getWorld(), BlockVector3.at(playerSelectionMin.getX(), 0, playerSelectionMin.getZ()), BlockVector3.at(playerSelectionMax.getX(), 255, playerSelectionMax.getZ()) ); // There's only one plot in the area... final PlotId plotId = PlotId.of(1, 1); final HybridPlotWorld hybridPlotWorld = this.hybridPlotWorldFactory - .create(player.getLocation().getWorldName(), + .create( + player.getLocation().getWorldName(), args[1], Objects.requireNonNull(PlotSquared.platform()).defaultGenerator(), plotId, @@ -292,9 +291,8 @@ public class Area extends SubCommand { }; singleRun.run(); return true; - case "c": - case "setup": - case "create": + } + case "c", "setup", "create" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_AREA_CREATE)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -311,7 +309,7 @@ public class Area extends SubCommand { return false; case 2: switch (args[1].toLowerCase()) { - case "pos1": { // Set position 1 + case "pos1" -> { // Set position 1 HybridPlotWorld area = (HybridPlotWorld) metaData.computeIfAbsent( player.getUUID(), missingUUID -> new HashMap<>() @@ -329,7 +327,8 @@ public class Area extends SubCommand { "area_pos1", location ); - player.sendMessage(TranslatableCaption.of("set.set_attribute"), + player.sendMessage( + TranslatableCaption.of("set.set_attribute"), Template.of("attribute", "area_pos1"), Template.of("value", location.getX() + "," + location.getZ()) ); @@ -339,7 +338,7 @@ public class Area extends SubCommand { ); return true; } - case "pos2": // Set position 2 and finish creation for type=2 (partial) + case "pos2" -> { // Set position 2 and finish creation for type=2 (partial) final HybridPlotWorld area = (HybridPlotWorld) metaData.computeIfAbsent( player.getUUID(), @@ -424,6 +423,7 @@ public class Area extends SubCommand { run.run(); } return true; + } } default: // Start creation String[] split = args[1].split(":"); @@ -468,56 +468,42 @@ public class Area extends SubCommand { return false; } switch (pair[0].toLowerCase()) { - case "s": - case "size": + case "s", "size" -> { pa.PLOT_WIDTH = Integer.parseInt(pair[1]); pa.SIZE = (short) (pa.PLOT_WIDTH + pa.ROAD_WIDTH); - break; - case "g": - case "gap": + } + case "g", "gap" -> { pa.ROAD_WIDTH = Integer.parseInt(pair[1]); pa.SIZE = (short) (pa.PLOT_WIDTH + pa.ROAD_WIDTH); - break; - case "h": - case "height": + } + case "h", "height" -> { int value = Integer.parseInt(pair[1]); pa.PLOT_HEIGHT = value; pa.ROAD_HEIGHT = value; pa.WALL_HEIGHT = value; - break; - case "f": - case "floor": - pa.TOP_BLOCK = ConfigurationUtil.BLOCK_BUCKET.parseString(pair[1]); - break; - case "m": - case "main": - pa.MAIN_BLOCK = ConfigurationUtil.BLOCK_BUCKET.parseString(pair[1]); - break; - case "w": - case "wall": - pa.WALL_FILLING = ConfigurationUtil.BLOCK_BUCKET.parseString(pair[1]); - break; - case "b": - case "border": - pa.WALL_BLOCK = ConfigurationUtil.BLOCK_BUCKET.parseString(pair[1]); - break; - case "terrain": + } + case "f", "floor" -> pa.TOP_BLOCK = ConfigurationUtil.BLOCK_BUCKET.parseString(pair[1]); + case "m", "main" -> pa.MAIN_BLOCK = ConfigurationUtil.BLOCK_BUCKET.parseString(pair[1]); + case "w", "wall" -> pa.WALL_FILLING = ConfigurationUtil.BLOCK_BUCKET.parseString(pair[1]); + case "b", "border" -> pa.WALL_BLOCK = ConfigurationUtil.BLOCK_BUCKET.parseString(pair[1]); + case "terrain" -> { pa.setTerrain(PlotAreaTerrainType.fromString(pair[1]) .orElseThrow(() -> new IllegalArgumentException(pair[1] + " is not a valid terrain."))); builder.terrainType(pa.getTerrain()); - break; - case "type": + } + case "type" -> { pa.setType(PlotAreaType.fromString(pair[1]) .orElseThrow(() -> new IllegalArgumentException(pair[1] + " is not a valid type."))); builder.plotAreaType(pa.getType()); - break; - default: + } + default -> { player.sendMessage( TranslatableCaption.of("commandconfig.command_syntax_extended"), Template.of("value1", getCommandString()), Template.of("value2", " create [world[:id]] [=]...") ); return false; + } } } if (pa.getType() != PlotAreaType.PARTIAL) { @@ -566,7 +552,8 @@ public class Area extends SubCommand { TranslatableCaption.of("commandconfig.command_syntax"), Template.of("value", getUsage()) ); - player.sendMessage(TranslatableCaption.of("commandconfig.command_syntax_extended"), + player.sendMessage( + TranslatableCaption.of("commandconfig.command_syntax_extended"), Template.of("value1", getCommandString()), Template.of("value2", " create [world[:id]] [=]...") ); @@ -590,8 +577,8 @@ public class Area extends SubCommand { break; } return true; - case "i": - case "info": { + } + case "i", "info" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_AREA_INFO)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -601,18 +588,16 @@ public class Area extends SubCommand { } PlotArea area; switch (args.length) { - case 1: - area = player.getApplicablePlotArea(); - break; - case 2: - area = this.plotAreaManager.getPlotAreaByString(args[1]); - break; - default: - player.sendMessage(TranslatableCaption.of("commandconfig.command_syntax_extended"), + case 1 -> area = player.getApplicablePlotArea(); + case 2 -> area = this.plotAreaManager.getPlotAreaByString(args[1]); + default -> { + player.sendMessage( + TranslatableCaption.of("commandconfig.command_syntax_extended"), Template.of("value1", getCommandString()), Template.of("value2", " info [area]") ); return false; + } } if (area == null) { if (args.length == 2) { @@ -656,7 +641,8 @@ public class Area extends SubCommand { "footer", TranslatableCaption.of("info.plot_info_footer").getComponent(player) ); - player.sendMessage(TranslatableCaption.of("info.area_info_format"), + player.sendMessage( + TranslatableCaption.of("info.area_info_format"), headerTemplate, nameTemplate, typeTemplate, @@ -670,8 +656,7 @@ public class Area extends SubCommand { ); return true; } - case "l": - case "list": + case "l", "list" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_AREA_LIST)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -690,7 +675,8 @@ public class Area extends SubCommand { break; } default: - player.sendMessage(TranslatableCaption.of("commandconfig.command_syntax_extended"), + player.sendMessage( + TranslatableCaption.of("commandconfig.command_syntax_extended"), Template.of("value1", getCommandString()), Template.of("value2", " list [#]") ); @@ -724,7 +710,8 @@ public class Area extends SubCommand { Template regionTemplate = Template.of("region", region); Template generatorTemplate = Template.of("generator", generator); String tooltip = MINI_MESSAGE.serialize(MINI_MESSAGE - .parse(TranslatableCaption.of("info.area_list_tooltip").getComponent(player), + .parse( + TranslatableCaption.of("info.area_list_tooltip").getComponent(player), claimedTemplate, usageTemplate, clustersTemplate, @@ -739,7 +726,8 @@ public class Area extends SubCommand { Template typeTemplate = Template.of("area_type", area.getType().name()); Template terrainTemplate = Template.of("area_terrain", area.getTerrain().name()); caption.set(TranslatableCaption.of("info.area_list_item")); - caption.setTemplates(tooltipTemplate, + caption.setTemplates( + tooltipTemplate, visitcmdTemplate, numberTemplate, nameTemplate, @@ -750,10 +738,8 @@ public class Area extends SubCommand { } }, "/plot area list", TranslatableCaption.of("list.area_list_header_paged")); return true; - case "regen": - case "clear": - case "reset": - case "regenerate": { + } + case "regen", "clear", "reset", "regenerate" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_AREA_REGEN)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -786,11 +772,7 @@ public class Area extends SubCommand { queue.enqueue(); return true; } - case "goto": - case "v": - case "teleport": - case "visit": - case "tp": + case "goto", "v", "teleport", "visit", "tp" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_AREA_TP)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -833,10 +815,11 @@ public class Area extends SubCommand { ); } return true; - case "delete": - case "remove": + } + case "delete", "remove" -> { player.sendMessage(TranslatableCaption.of("single.worldcreation_location")); return true; + } } sendUsage(player); return false; diff --git a/Core/src/main/java/com/plotsquared/core/command/Argument.java b/Core/src/main/java/com/plotsquared/core/command/Argument.java index 1030aea0e..dd8e8c911 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Argument.java +++ b/Core/src/main/java/com/plotsquared/core/command/Argument.java @@ -29,7 +29,7 @@ import com.plotsquared.core.plot.PlotId; public abstract class Argument { - public static final Argument Integer = new Argument("int", 16) { + public static final Argument Integer = new Argument<>("int", 16) { @Override public Integer parse(String in) { Integer value = null; @@ -40,7 +40,7 @@ public abstract class Argument { return value; } }; - public static final Argument Boolean = new Argument("boolean", true) { + public static final Argument Boolean = new Argument<>("boolean", true) { @Override public Boolean parse(String in) { Boolean value = null; @@ -54,21 +54,21 @@ public abstract class Argument { return value; } }; - public static final Argument String = new Argument("String", "Example") { + public static final Argument String = new Argument<>("String", "Example") { @Override public String parse(String in) { return in; } }; public static final Argument PlayerName = - new Argument("PlayerName", "") { + new Argument<>("PlayerName", "") { @Override public String parse(String in) { return in.length() <= 16 ? in : null; } }; public static final Argument PlotID = - new Argument("PlotID", PlotId.of(-6, 3)) { + new Argument<>("PlotID", PlotId.of(-6, 3)) { @Override public PlotId parse(String in) { return PlotId.fromString(in); diff --git a/Core/src/main/java/com/plotsquared/core/command/Auto.java b/Core/src/main/java/com/plotsquared/core/command/Auto.java index 5780a817a..d162a7bbf 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Auto.java +++ b/Core/src/main/java/com/plotsquared/core/command/Auto.java @@ -162,7 +162,7 @@ public class Auto extends SubCommand { } plot.setOwnerAbs(player.getUUID()); - final RunnableVal runnableVal = new RunnableVal() { + final RunnableVal runnableVal = new RunnableVal<>() { { this.value = plot; } @@ -217,20 +217,21 @@ public class Auto extends SubCommand { try { String[] split = args[0].split(",|;"); switch (split.length) { - case 1: + case 1 -> { size_x = 1; size_z = 1; - break; - case 2: + } + case 2 -> { size_x = Integer.parseInt(split[0]); size_z = Integer.parseInt(split[1]); - break; - default: + } + default -> { player.sendMessage( TranslatableCaption.of("commandconfig.command_syntax"), Template.of("value", getUsage()) ); return true; + } } if (size_x < 1 || size_z < 1) { player.sendMessage(TranslatableCaption.of("error.plot_size")); diff --git a/Core/src/main/java/com/plotsquared/core/command/Chat.java b/Core/src/main/java/com/plotsquared/core/command/Chat.java index c267d77d2..9c9ad5876 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Chat.java +++ b/Core/src/main/java/com/plotsquared/core/command/Chat.java @@ -34,6 +34,7 @@ import com.plotsquared.core.plot.PlotArea; permission = "plots.chat", category = CommandCategory.CHAT, requiredType = RequiredType.PLAYER) +@Deprecated public class Chat extends SubCommand { @Override diff --git a/Core/src/main/java/com/plotsquared/core/command/Condense.java b/Core/src/main/java/com/plotsquared/core/command/Condense.java index e758d3c0b..d195895dd 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Condense.java +++ b/Core/src/main/java/com/plotsquared/core/command/Condense.java @@ -84,7 +84,7 @@ public class Condense extends SubCommand { return false; } switch (args[1].toLowerCase()) { - case "start": { + case "start" -> { if (args.length == 2) { player.sendMessage( TranslatableCaption.of("commandconfig.command_syntax"), @@ -216,7 +216,7 @@ public class Condense extends SubCommand { TaskManager.runTaskAsync(run); return true; } - case "stop": + case "stop" -> { if (!Condense.TASK) { player.sendMessage(TranslatableCaption.of("condense.task_stopped")); return false; @@ -224,7 +224,8 @@ public class Condense extends SubCommand { Condense.TASK = false; player.sendMessage(TranslatableCaption.of("condense.task_stopped")); return true; - case "info": + } + case "info" -> { if (args.length == 2) { player.sendMessage( TranslatableCaption.of("commandconfig.command_syntax"), @@ -267,6 +268,7 @@ public class Condense extends SubCommand { player.sendMessage(TranslatableCaption.of("condense.eta")); player.sendMessage(TranslatableCaption.of("condense.radius_measured")); return true; + } } player.sendMessage( TranslatableCaption.of("commandconfig.command_syntax"), diff --git a/Core/src/main/java/com/plotsquared/core/command/DatabaseCommand.java b/Core/src/main/java/com/plotsquared/core/command/DatabaseCommand.java index 15b3f000c..908e02fe6 100644 --- a/Core/src/main/java/com/plotsquared/core/command/DatabaseCommand.java +++ b/Core/src/main/java/com/plotsquared/core/command/DatabaseCommand.java @@ -132,7 +132,7 @@ public class DatabaseCommand extends SubCommand { Database implementation; String prefix = ""; switch (args[0].toLowerCase()) { - case "import": + case "import" -> { if (args.length < 2) { player.sendMessage( TranslatableCaption.of("commandconfig.command_syntax"), @@ -210,7 +210,8 @@ public class DatabaseCommand extends SubCommand { () -> player.sendMessage(TranslatableCaption.of("database.conversion_done")) ); return true; - case "mysql": + } + case "mysql" -> { if (args.length < 6) { player.sendMessage(StaticCaption.of( "/plot database mysql [host] [port] [username] [password] [database] {prefix}")); @@ -224,18 +225,19 @@ public class DatabaseCommand extends SubCommand { prefix = args[6]; } implementation = new MySQL(host, port, database, username, password); - break; - case "sqlite": + } + case "sqlite" -> { if (args.length < 2) { player.sendMessage(StaticCaption.of("/plot database sqlite [file]")); } File sqliteFile = FileUtils.getFile(PlotSquared.platform().getDirectory(), args[1] + ".db"); implementation = new SQLite(sqliteFile); - break; - default: + } + default -> { player.sendMessage(StaticCaption.of("/plot database [sqlite/mysql]")); return false; + } } try { SQLManager manager = new SQLManager( diff --git a/Core/src/main/java/com/plotsquared/core/command/DebugExec.java b/Core/src/main/java/com/plotsquared/core/command/DebugExec.java index d7f1a4ef6..eed822f43 100644 --- a/Core/src/main/java/com/plotsquared/core/command/DebugExec.java +++ b/Core/src/main/java/com/plotsquared/core/command/DebugExec.java @@ -93,7 +93,7 @@ public class DebugExec extends SubCommand { if (args.length > 0) { String arg = args[0].toLowerCase(); switch (arg) { - case "analyze": { + case "analyze" -> { Plot plot = player.getCurrentPlot(); if (plot == null) { player.sendMessage(TranslatableCaption.of("errors.not_in_plot")); @@ -103,7 +103,7 @@ public class DebugExec extends SubCommand { if (analysis != null) { player.sendMessage( TranslatableCaption.of("debugexec.changes_column"), - Template.of("value", String.valueOf(analysis.changes / 1.0)) + Template.of("value", String.valueOf(analysis.changes)) ); return true; } @@ -119,7 +119,7 @@ public class DebugExec extends SubCommand { }); return true; } - case "calibrate-analysis": + case "calibrate-analysis" -> { if (args.length != 2) { player.sendMessage( TranslatableCaption.of("commandconfig.command_syntax"), @@ -144,7 +144,8 @@ public class DebugExec extends SubCommand { threshold ); return true; - case "start-expire": + } + case "start-expire" -> { if (ExpireManager.IMP == null) { ExpireManager.IMP = new ExpireManager(this.eventDispatcher); } @@ -154,14 +155,16 @@ public class DebugExec extends SubCommand { player.sendMessage(TranslatableCaption.of("debugexec.expiry_already_started")); } return true; - case "stop-expire": + } + case "stop-expire" -> { if (ExpireManager.IMP == null || !ExpireManager.IMP.cancelTask()) { player.sendMessage(TranslatableCaption.of("debugexec.task_halted")); } else { player.sendMessage(TranslatableCaption.of("debugexec.task_cancelled")); } return true; - case "remove-flag": + } + case "remove-flag" -> { if (args.length != 2) { player.sendMessage( TranslatableCaption.of("commandconfig.command_syntax"), @@ -186,7 +189,8 @@ public class DebugExec extends SubCommand { Template.of("value", flag) ); return true; - case "start-rgar": { + } + case "start-rgar" -> { if (args.length != 2) { player.sendMessage( TranslatableCaption.of("commandconfig.command_syntax"), @@ -214,7 +218,7 @@ public class DebugExec extends SubCommand { } return true; } - case "stop-rgar": + case "stop-rgar" -> { if (!HybridUtils.UPDATE) { player.sendMessage(TranslatableCaption.of("debugexec.task_not_running")); return false; @@ -222,6 +226,7 @@ public class DebugExec extends SubCommand { HybridUtils.UPDATE = false; player.sendMessage(TranslatableCaption.of("debugexec.task_cancelled")); return true; + } } } player.sendMessage(StaticCaption.of("Possible sub commands: /plot debugexec <" diff --git a/Core/src/main/java/com/plotsquared/core/command/Done.java b/Core/src/main/java/com/plotsquared/core/command/Done.java index 1ccec2feb..e78ff12ad 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Done.java +++ b/Core/src/main/java/com/plotsquared/core/command/Done.java @@ -105,7 +105,7 @@ public class Done extends SubCommand { finish(plot, player, true); plot.removeRunning(); } else { - this.hybridUtils.analyzePlot(plot, new RunnableVal() { + this.hybridUtils.analyzePlot(plot, new RunnableVal<>() { @Override public void run(PlotAnalysis value) { plot.removeRunning(); diff --git a/Core/src/main/java/com/plotsquared/core/command/FlagCommand.java b/Core/src/main/java/com/plotsquared/core/command/FlagCommand.java index 1c85463d9..1131fe8f7 100644 --- a/Core/src/main/java/com/plotsquared/core/command/FlagCommand.java +++ b/Core/src/main/java/com/plotsquared/core/command/FlagCommand.java @@ -119,8 +119,7 @@ public final class FlagCommand extends Command { } } catch (NumberFormatException ignore) { } - } else if (flag instanceof ListFlag) { - final ListFlag listFlag = (ListFlag) flag; + } else if (flag instanceof final ListFlag listFlag) { try { PlotFlag, ?> parsedFlag = listFlag.parse(value); for (final Object entry : parsedFlag.getValue()) { @@ -295,7 +294,7 @@ public final class FlagCommand extends Command { }).collect(Collectors.toList()); } } - } catch (final Exception e) { + } catch (final Exception ignored) { } } return tabOf(player, args, space); diff --git a/Core/src/main/java/com/plotsquared/core/command/Grant.java b/Core/src/main/java/com/plotsquared/core/command/Grant.java index b621f5b2d..f1e2a8d53 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Grant.java +++ b/Core/src/main/java/com/plotsquared/core/command/Grant.java @@ -75,8 +75,7 @@ public class Grant extends Command { ); final String arg0 = args[0].toLowerCase(); switch (arg0) { - case "add": - case "check": + case "add", "check" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_GRANT.format(arg0))) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -111,7 +110,7 @@ public class Grant extends Command { } } } else { - DBFunc.getPersistentMeta(uuid.getUuid(), new RunnableVal>() { + DBFunc.getPersistentMeta(uuid.getUuid(), new RunnableVal<>() { @Override public void run(Map value) { final byte[] array = value.get("grantedPlots"); @@ -148,6 +147,7 @@ public class Grant extends Command { } }); return CompletableFuture.completedFuture(true); + } } sendUsage(player); return CompletableFuture.completedFuture(true); diff --git a/Core/src/main/java/com/plotsquared/core/command/HomeCommand.java b/Core/src/main/java/com/plotsquared/core/command/HomeCommand.java index b106ccbd6..9bbb1547b 100644 --- a/Core/src/main/java/com/plotsquared/core/command/HomeCommand.java +++ b/Core/src/main/java/com/plotsquared/core/command/HomeCommand.java @@ -129,7 +129,7 @@ public class HomeCommand extends Command { PlotArea plotArea; boolean basePlotOnly = true; switch (args.length) { - case 1: + case 1 -> { identifier = args[0]; if (MathMan.isInteger(identifier)) { try { @@ -160,8 +160,8 @@ public class HomeCommand extends Command { } // it wasn't a valid plot id, trying to find plot by alias query.withAlias(identifier); - break; - case 2: + } + case 2 -> { // we assume args[0] is a plot area and args[1] an identifier plotArea = this.plotAreaManager.getPlotAreaByString(args[0]); identifier = args[1]; @@ -201,10 +201,8 @@ public class HomeCommand extends Command { // as the query already filters by owner, this is fine basePlotOnly = false; query.withPlot(plot); - break; - case 0: - sortBySettings(query, player); - break; + } + case 0 -> sortBySettings(query, player); } if (basePlotOnly) { query.whereBasePlot(); @@ -226,7 +224,7 @@ public class HomeCommand extends Command { public Collection tab(PlotPlayer player, String[] args, boolean space) { final List completions = new ArrayList<>(); switch (args.length - 1) { - case 0: + case 0 -> { completions.addAll( TabCompletions.completeAreas(args[0])); if (args[0].isEmpty()) { @@ -238,11 +236,9 @@ public class HomeCommand extends Command { // complete more numbers from the already given input completions.addAll( TabCompletions.completeNumbers(args[0], 10, 999)); - break; - case 1: - completions.addAll( - TabCompletions.completeNumbers(args[1], 10, 999)); - break; + } + case 1 -> completions.addAll( + TabCompletions.completeNumbers(args[1], 10, 999)); } return completions; } diff --git a/Core/src/main/java/com/plotsquared/core/command/Info.java b/Core/src/main/java/com/plotsquared/core/command/Info.java index 509d0af7d..b52bc03ab 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Info.java +++ b/Core/src/main/java/com/plotsquared/core/command/Info.java @@ -25,7 +25,6 @@ */ package com.plotsquared.core.command; -import com.plotsquared.core.PlotSquared; import com.plotsquared.core.configuration.Settings; import com.plotsquared.core.configuration.caption.Caption; import com.plotsquared.core.configuration.caption.StaticCaption; @@ -43,9 +42,7 @@ import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; -import java.util.Locale; import java.util.stream.Collectors; -import java.util.stream.Stream; @CommandDeclaration(command = "info", aliases = "i", @@ -60,30 +57,16 @@ public class Info extends SubCommand { if (args.length > 0) { arg = args[0]; switch (arg) { - case "trusted": - case "alias": - case "inv": - case "biome": - case "denied": - case "flags": - case "id": - case "size": - case "members": - case "creationdate": - case "seen": - case "owner": - case "rating": - case "likes": - plot = Plot.getPlotFromString(player, null, false); - break; - default: + case "trusted", "alias", "inv", "biome", "denied", "flags", "id", "size", "members", "creationdate", "seen", "owner", "rating", "likes" -> plot = Plot + .getPlotFromString(player, null, false); + default -> { plot = Plot.getPlotFromString(player, arg, false); if (args.length == 2) { arg = args[1]; } else { arg = null; } - break; + } } if (plot == null) { plot = player.getCurrentPlot(); @@ -185,36 +168,22 @@ public class Info extends SubCommand { } private Caption getCaption(String string) { - switch (string) { - case "trusted": - return TranslatableCaption.of("info.plot_info_trusted"); - case "alias": - return TranslatableCaption.of("info.plot_info_alias"); - case "biome": - return TranslatableCaption.of("info.plot_info_biome"); - case "denied": - return TranslatableCaption.of("info.plot_info_denied"); - case "flags": - return TranslatableCaption.of("info.plot_info_flags"); - case "id": - return TranslatableCaption.of("info.plot_info_id"); - case "size": - return TranslatableCaption.of("info.plot_info_size"); - case "members": - return TranslatableCaption.of("info.plot_info_members"); - case "owner": - return TranslatableCaption.of("info.plot_info_owner"); - case "rating": - return TranslatableCaption.of("info.plot_info_rating"); - case "likes": - return TranslatableCaption.of("info.plot_info_likes"); - case "seen": - return TranslatableCaption.of("info.plot_info_seen"); - case "creationdate": - return TranslatableCaption.of("info.plot_info_creationdate"); - default: - return null; - } + return switch (string) { + case "trusted" -> TranslatableCaption.of("info.plot_info_trusted"); + case "alias" -> TranslatableCaption.of("info.plot_info_alias"); + case "biome" -> TranslatableCaption.of("info.plot_info_biome"); + case "denied" -> TranslatableCaption.of("info.plot_info_denied"); + case "flags" -> TranslatableCaption.of("info.plot_info_flags"); + case "id" -> TranslatableCaption.of("info.plot_info_id"); + case "size" -> TranslatableCaption.of("info.plot_info_size"); + case "members" -> TranslatableCaption.of("info.plot_info_members"); + case "owner" -> TranslatableCaption.of("info.plot_info_owner"); + case "rating" -> TranslatableCaption.of("info.plot_info_rating"); + case "likes" -> TranslatableCaption.of("info.plot_info_likes"); + case "seen" -> TranslatableCaption.of("info.plot_info_seen"); + case "creationdate" -> TranslatableCaption.of("info.plot_info_creationdate"); + default -> null; + }; } } diff --git a/Core/src/main/java/com/plotsquared/core/command/Like.java b/Core/src/main/java/com/plotsquared/core/command/Like.java index 892df4b67..749e744bd 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Like.java +++ b/Core/src/main/java/com/plotsquared/core/command/Like.java @@ -100,7 +100,7 @@ public class Like extends SubCommand { final UUID uuid = player.getUUID(); if (args.length == 1) { switch (args[0].toLowerCase()) { - case "next": { + case "next" -> { final List plots = PlotQuery.newQuery().whereBasePlot().asList(); plots.sort((p1, p2) -> { double v1 = getLikesPercentage(p1); @@ -122,7 +122,7 @@ public class Like extends SubCommand { player.sendMessage(TranslatableCaption.of("invalid.found_no_plots")); return true; } - case "purge": { + case "purge" -> { final Plot plot = player.getCurrentPlot(); if (plot == null) { player.sendMessage(TranslatableCaption.of("errors.not_in_plot")); diff --git a/Core/src/main/java/com/plotsquared/core/command/ListCmd.java b/Core/src/main/java/com/plotsquared/core/command/ListCmd.java index 4e9d3d404..84ac5c0ee 100644 --- a/Core/src/main/java/com/plotsquared/core/command/ListCmd.java +++ b/Core/src/main/java/com/plotsquared/core/command/ListCmd.java @@ -192,7 +192,7 @@ public class ListCmd extends SubCommand { }; switch (arg) { - case "mine": + case "mine" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_LIST_MINE)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -206,8 +206,8 @@ public class ListCmd extends SubCommand { .ownedBy(player) .whereBasePlot() .withSortingStrategy(SortingStrategy.SORT_BY_TEMP)); - break; - case "shared": + } + case "shared" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_LIST_SHARED)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -219,8 +219,8 @@ public class ListCmd extends SubCommand { .newQuery() .withMember(player.getUUID()) .thatPasses(plot -> !plot.isOwnerAbs(player.getUUID()))); - break; - case "world": + } + case "world" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_LIST_WORLD)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -236,8 +236,8 @@ public class ListCmd extends SubCommand { return false; } plotConsumer.accept(PlotQuery.newQuery().inWorld(world)); - break; - case "expired": + } + case "expired" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_LIST_EXPIRED)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -250,8 +250,8 @@ public class ListCmd extends SubCommand { } else { plotConsumer.accept(PlotQuery.newQuery().expiredPlots()); } - break; - case "area": + } + case "area" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_LIST_AREA)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -271,8 +271,8 @@ public class ListCmd extends SubCommand { } else { plotConsumer.accept(PlotQuery.newQuery().inArea(area)); } - break; - case "all": + } + case "all" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_LIST_ALL)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -281,8 +281,8 @@ public class ListCmd extends SubCommand { return false; } plotConsumer.accept(PlotQuery.newQuery().allPlots()); - break; - case "done": + } + case "done" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_LIST_DONE)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -296,8 +296,8 @@ public class ListCmd extends SubCommand { .allPlots() .thatPasses(DoneFlag::isDone) .withSortingStrategy(SortingStrategy.SORT_BY_DONE)); - break; - case "top": + } + case "top" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_LIST_TOP)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -307,8 +307,8 @@ public class ListCmd extends SubCommand { } sort[0] = false; plotConsumer.accept(PlotQuery.newQuery().allPlots().withSortingStrategy(SortingStrategy.SORT_BY_RATING)); - break; - case "forsale": + } + case "forsale" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_LIST_FOR_SALE)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -320,8 +320,8 @@ public class ListCmd extends SubCommand { break; } plotConsumer.accept(PlotQuery.newQuery().allPlots().thatPasses(plot -> plot.getFlag(PriceFlag.class) > 0)); - break; - case "unowned": + } + case "unowned" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_LIST_UNOWNED)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -330,8 +330,8 @@ public class ListCmd extends SubCommand { return false; } plotConsumer.accept(PlotQuery.newQuery().allPlots().thatPasses(plot -> plot.getOwner() == null)); - break; - case "fuzzy": + } + case "fuzzy" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_LIST_FUZZY)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -354,8 +354,8 @@ public class ListCmd extends SubCommand { } sort[0] = false; plotConsumer.accept(PlotQuery.newQuery().plotsBySearch(term)); - break; - default: + } + default -> { if (this.plotAreaManager.hasPlotArea(args[0])) { if (!Permissions.hasPermission(player, Permission.PERMISSION_LIST_WORLD)) { player.sendMessage( @@ -374,7 +374,6 @@ public class ListCmd extends SubCommand { plotConsumer.accept(PlotQuery.newQuery().inWorld(args[0])); break; } - PlotSquared.get().getImpromptuUUIDPipeline().getSingle(args[0], (uuid, throwable) -> { if (throwable instanceof TimeoutException) { player.sendMessage(TranslatableCaption.of("players.fetching_players_timeout")); @@ -403,6 +402,7 @@ public class ListCmd extends SubCommand { } } }); + } } return true; @@ -411,7 +411,7 @@ public class ListCmd extends SubCommand { public void displayPlots(final PlotPlayer player, List plots, int pageSize, int page, String[] args) { // Header plots.removeIf(plot -> !plot.isBasePlot()); - this.paginate(player, plots, pageSize, page, new RunnableVal3() { + this.paginate(player, plots, pageSize, page, new RunnableVal3<>() { @Override public void run(Integer i, Plot plot, CaptionHolder caption) { Caption color; diff --git a/Core/src/main/java/com/plotsquared/core/command/MainCommand.java b/Core/src/main/java/com/plotsquared/core/command/MainCommand.java index a256e2192..59601c73b 100644 --- a/Core/src/main/java/com/plotsquared/core/command/MainCommand.java +++ b/Core/src/main/java/com/plotsquared/core/command/MainCommand.java @@ -184,7 +184,7 @@ public class MainCommand extends Command { } } try { - getInstance().execute(player, args, new RunnableVal3() { + getInstance().execute(player, args, new RunnableVal3<>() { @Override public void run(final Command cmd, final Runnable success, final Runnable failure) { if (cmd.hasConfirmation(player)) { @@ -222,7 +222,7 @@ public class MainCommand extends Command { success.run(); } } - }, new RunnableVal2() { + }, new RunnableVal2<>() { @Override public void run(Command cmd, CommandResult result) { // Post command stuff!? @@ -281,7 +281,7 @@ public class MainCommand extends Command { } if (args.length >= 2 && !args[0].isEmpty() && args[0].charAt(0) == '-') { if ("f".equals(args[0].substring(1))) { - confirm = new RunnableVal3() { + confirm = new RunnableVal3<>() { @Override public void run(Command cmd, Runnable success, Runnable failure) { if (area != null && PlotSquared.platform().econHandler().isEnabled(area)) { diff --git a/Core/src/main/java/com/plotsquared/core/command/Merge.java b/Core/src/main/java/com/plotsquared/core/command/Merge.java index 9fdc6088d..5217a170a 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Merge.java +++ b/Core/src/main/java/com/plotsquared/core/command/Merge.java @@ -74,23 +74,13 @@ public class Merge extends SubCommand { public static String direction(float yaw) { yaw = yaw / 90; int i = Math.round(yaw); - switch (i) { - case -4: - case 0: - case 4: - return "SOUTH"; - case -1: - case 3: - return "EAST"; - case -2: - case 2: - return "NORTH"; - case -3: - case 1: - return "WEST"; - default: - return ""; - } + return switch (i) { + case -4, 0, 4 -> "SOUTH"; + case -1, 3 -> "EAST"; + case -2, 2 -> "NORTH"; + case -3, 1 -> "WEST"; + default -> ""; + }; } @Override @@ -112,18 +102,10 @@ public class Merge extends SubCommand { Direction direction = null; if (args.length == 0) { switch (direction(player.getLocationFull().getYaw())) { - case "NORTH": - direction = Direction.NORTH; - break; - case "EAST": - direction = Direction.EAST; - break; - case "SOUTH": - direction = Direction.SOUTH; - break; - case "WEST": - direction = Direction.WEST; - break; + case "NORTH" -> direction = Direction.NORTH; + case "EAST" -> direction = Direction.EAST; + case "SOUTH" -> direction = Direction.SOUTH; + case "WEST" -> direction = Direction.WEST; } } else { for (int i = 0; i < values.length; i++) { diff --git a/Core/src/main/java/com/plotsquared/core/command/Owner.java b/Core/src/main/java/com/plotsquared/core/command/Owner.java index 24cd1e435..2c267de5b 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Owner.java +++ b/Core/src/main/java/com/plotsquared/core/command/Owner.java @@ -70,7 +70,6 @@ public class Owner extends SetCommand { @Override public boolean set(final PlotPlayer player, final Plot plot, String value) { if (value == null || value.isEmpty()) { - player.sendMessage(TranslatableCaption.of("owner.set_owner_missing_player")); player.sendMessage( TranslatableCaption.of("commandconfig.command_syntax"), Template.of("value", "/plot setowner ") @@ -155,7 +154,7 @@ public class Owner extends SetCommand { other.getPlotCount() : other.getPlotCount(plot.getWorldName())) + size; try (final MetaDataAccess metaDataAccess = player.accessPersistentMetaData(PlayerMetaDataKeys.PERSISTENT_GRANTED_PLOTS)) { - int grants = 0; + int grants; if (currentPlots >= other.getAllowedPlots()) { if (metaDataAccess.isPresent()) { grants = metaDataAccess.get().orElse(0); diff --git a/Core/src/main/java/com/plotsquared/core/command/Purge.java b/Core/src/main/java/com/plotsquared/core/command/Purge.java index b20b156c5..938a9bdba 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Purge.java +++ b/Core/src/main/java/com/plotsquared/core/command/Purge.java @@ -206,9 +206,7 @@ public class Purge extends SubCommand { "/plot purge " + StringMan.join(args, " ") + " (" + toDelete.size() + " plots)"; boolean finalClear = clear; Runnable run = () -> { - if (Settings.DEBUG) { - logger.info("Calculating plots to purge, please wait..."); - } + logger.info("Calculating plots to purge, please wait..."); HashSet ids = new HashSet<>(); Iterator iterator = toDelete.iterator(); AtomicBoolean cleared = new AtomicBoolean(true); @@ -223,9 +221,7 @@ public class Purge extends SubCommand { ids.add(plot.temp); if (finalClear) { plot.getPlotModificationManager().clear(false, true, player, () -> { - if (Settings.DEBUG) { - logger.info("Plot {} cleared by purge", plot.getId()); - } + logger.info("Plot {} cleared by purge", plot.getId()); }); } else { plot.getPlotModificationManager().removeSign(); diff --git a/Core/src/main/java/com/plotsquared/core/command/Rate.java b/Core/src/main/java/com/plotsquared/core/command/Rate.java index 0f9515721..fc3224add 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Rate.java +++ b/Core/src/main/java/com/plotsquared/core/command/Rate.java @@ -81,7 +81,7 @@ public class Rate extends SubCommand { public boolean onCommand(final PlotPlayer player, String[] args) { if (args.length == 1) { switch (args[0].toLowerCase()) { - case "next": { + case "next" -> { final List plots = PlotQuery.newQuery().whereBasePlot().asList(); plots.sort((p1, p2) -> { double v1 = 0; @@ -115,7 +115,7 @@ public class Rate extends SubCommand { player.sendMessage(TranslatableCaption.of("invalid.found_no_plots")); return false; } - case "purge": { + case "purge" -> { final Plot plot = player.getCurrentPlot(); if (plot == null) { player.sendMessage(TranslatableCaption.of("errors.not_in_plot")); @@ -292,7 +292,7 @@ public class Rate extends SubCommand { return TabCompletions.completePlayers(String.join(",", args).trim(), Collections.emptyList()); } - private class MutableInt { + private static class MutableInt { private int value; diff --git a/Core/src/main/java/com/plotsquared/core/command/SchematicCmd.java b/Core/src/main/java/com/plotsquared/core/command/SchematicCmd.java index f668a5761..5049c63dd 100644 --- a/Core/src/main/java/com/plotsquared/core/command/SchematicCmd.java +++ b/Core/src/main/java/com/plotsquared/core/command/SchematicCmd.java @@ -86,7 +86,7 @@ public class SchematicCmd extends SubCommand { } String arg = args[0].toLowerCase(); switch (arg) { - case "paste": { + case "paste" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_SCHEMATIC_PASTE)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -179,10 +179,8 @@ public class SchematicCmd extends SubCommand { } ); }); - break; } - case "saveall": - case "exportall": { + case "saveall", "exportall" -> { Location loc = player.getLocation(); final Plot plot = loc.getPlotAbs(); if (!(player instanceof ConsolePlayer)) { @@ -227,10 +225,8 @@ public class SchematicCmd extends SubCommand { Template.of("amount", String.valueOf(plots.size())) ); } - break; } - case "export": - case "save": + case "export", "save" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_SCHEMATIC_SAVE)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -272,8 +268,8 @@ public class SchematicCmd extends SubCommand { } else { player.sendMessage(TranslatableCaption.of("schematics.schematic_exportall_started")); } - break; - case "list": { + } + case "list" -> { if (!Permissions.hasPermission(player, Permission.PERMISSION_SCHEMATIC_LIST)) { player.sendMessage( TranslatableCaption.of("permission.no_permission"), @@ -287,13 +283,10 @@ public class SchematicCmd extends SubCommand { Template.of("list", string) ); } - break; - default: - player.sendMessage( - TranslatableCaption.of("commandconfig.command_syntax"), - Template.of("value", "Possible values: save, paste, exportall, list") - ); - break; + default -> player.sendMessage( + TranslatableCaption.of("commandconfig.command_syntax"), + Template.of("value", "Possible values: save, paste, exportall, list") + ); } return true; } diff --git a/Core/src/main/java/com/plotsquared/core/command/SetHome.java b/Core/src/main/java/com/plotsquared/core/command/SetHome.java index dd1c44b2e..de6ce5df9 100644 --- a/Core/src/main/java/com/plotsquared/core/command/SetHome.java +++ b/Core/src/main/java/com/plotsquared/core/command/SetHome.java @@ -47,16 +47,13 @@ public class SetHome extends SetCommand { return false; } switch (value.toLowerCase()) { - case "unset": - case "reset": - case "remove": - case "none": { + case "unset", "reset", "remove", "none" -> { Plot base = plot.getBasePlot(false); base.setHome(null); player.sendMessage(TranslatableCaption.of("position.position_unset")); return true; } - case "": { + case "" -> { Plot base = plot.getBasePlot(false); Location bottom = base.getBottomAbs(); Location location = player.getLocationFull(); @@ -67,12 +64,13 @@ public class SetHome extends SetCommand { player.sendMessage(TranslatableCaption.of("position.position_set")); return true; } - default: + default -> { player.sendMessage( TranslatableCaption.of("commandconfig.command_syntax"), Template.of("value", "Use /plot set home [none]") ); return false; + } } } diff --git a/Core/src/main/java/com/plotsquared/core/command/SubCommand.java b/Core/src/main/java/com/plotsquared/core/command/SubCommand.java index f69cb5e1a..b209934eb 100644 --- a/Core/src/main/java/com/plotsquared/core/command/SubCommand.java +++ b/Core/src/main/java/com/plotsquared/core/command/SubCommand.java @@ -43,7 +43,7 @@ public abstract class SubCommand extends Command { super(MainCommand.getInstance(), true); } - public SubCommand(Argument... arguments) { + public SubCommand(Argument... arguments) { this(); setRequiredArguments(arguments); } diff --git a/Core/src/main/java/com/plotsquared/core/command/Template.java b/Core/src/main/java/com/plotsquared/core/command/Template.java index 051c62879..0b78f53c0 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Template.java +++ b/Core/src/main/java/com/plotsquared/core/command/Template.java @@ -192,7 +192,7 @@ public class Template extends SubCommand { } final String world = args[1]; switch (args[0].toLowerCase()) { - case "import": { + case "import" -> { if (args.length != 3) { player.sendMessage( TranslatableCaption.of("commandconfig.command_syntax"), @@ -245,7 +245,7 @@ public class Template extends SubCommand { }); return true; } - case "export": + case "export" -> { if (args.length != 2) { player.sendMessage( TranslatableCaption.of("commandconfig.command_syntax"), @@ -276,8 +276,8 @@ public class Template extends SubCommand { player.sendMessage(TranslatableCaption.of("debugimportworlds.done")); }); return true; - default: - sendUsage(player); + } + default -> sendUsage(player); } return false; } diff --git a/Core/src/main/java/com/plotsquared/core/command/Trim.java b/Core/src/main/java/com/plotsquared/core/command/Trim.java index 3cdbe493d..5553dad19 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Trim.java +++ b/Core/src/main/java/com/plotsquared/core/command/Trim.java @@ -107,7 +107,7 @@ public class Trim extends SubCommand { StaticCaption.of(" - MCA #: " + result.value1.size()); StaticCaption.of(" - CHUNKS: " + (result.value1.size() * 1024) + " (max)"); StaticCaption.of(" - TIME ESTIMATE: 12 Parsecs"); - TaskManager.getPlatformImplementation().objectTask(plots, new RunnableVal() { + TaskManager.getPlatformImplementation().objectTask(plots, new RunnableVal<>() { @Override public void run(Plot plot) { Location pos1 = plot.getCorners()[0]; @@ -147,7 +147,7 @@ public class Trim extends SubCommand { } Trim.TASK = true; final boolean regen = args.length == 2 && Boolean.parseBoolean(args[1]); - getTrimRegions(world, new RunnableVal2, Set>() { + getTrimRegions(world, new RunnableVal2<>() { @Override public void run(Set viable, final Set nonViable) { Runnable regenTask; @@ -199,7 +199,7 @@ public class Trim extends SubCommand { } } final QueueCoordinator queue = blockQueue.getNewQueue(worldUtil.getWeWorld(world)); - TaskManager.getPlatformImplementation().objectTask(chunks, new RunnableVal() { + TaskManager.getPlatformImplementation().objectTask(chunks, new RunnableVal<>() { @Override public void run(BlockVector2 value) { queue.regenChunk(value.getX(), value.getZ()); diff --git a/Core/src/main/java/com/plotsquared/core/command/Visit.java b/Core/src/main/java/com/plotsquared/core/command/Visit.java index 8193b0cff..3eb22d8a6 100644 --- a/Core/src/main/java/com/plotsquared/core/command/Visit.java +++ b/Core/src/main/java/com/plotsquared/core/command/Visit.java @@ -314,10 +314,8 @@ public class Visit extends Command { public Collection tab(PlotPlayer player, String[] args, boolean space) { final List completions = new ArrayList<>(); switch (args.length - 1) { - case 0: - completions.addAll(TabCompletions.completePlayers(args[0], Collections.emptyList())); - break; - case 1: + case 0 -> completions.addAll(TabCompletions.completePlayers(args[0], Collections.emptyList())); + case 1 -> { completions.addAll( TabCompletions.completeAreas(args[1])); if (args[1].isEmpty()) { @@ -328,8 +326,8 @@ public class Visit extends Command { } completions.addAll( TabCompletions.completeNumbers(args[1], 10, 999)); - break; - case 2: + } + case 2 -> { if (args[2].isEmpty()) { // if no input is given, only suggest 1 - 3 completions.addAll( @@ -338,7 +336,7 @@ public class Visit extends Command { } completions.addAll( TabCompletions.completeNumbers(args[2], 10, 999)); - break; + } } return completions; diff --git a/Core/src/main/java/com/plotsquared/core/command/WE_Anywhere.java b/Core/src/main/java/com/plotsquared/core/command/WE_Anywhere.java deleted file mode 100644 index 3584cdc57..000000000 --- a/Core/src/main/java/com/plotsquared/core/command/WE_Anywhere.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * _____ _ _ _____ _ - * | __ \| | | | / ____| | | - * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | - * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | - * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | - * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| - * | | - * |_| - * PlotSquared plot management system for Minecraft - * Copyright (C) 2021 IntellectualSites - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.plotsquared.core.command; - -import com.plotsquared.core.player.PlotPlayer; - -@CommandDeclaration(command = "weanywhere", - permission = "plots.worldedit.bypass", - aliases = {"wea"}, - usage = "/plot weanywhere", - requiredType = RequiredType.NONE, - category = CommandCategory.ADMINISTRATION) -@Deprecated -public class WE_Anywhere extends SubCommand { - - @Override - public boolean onCommand(PlotPlayer player, String[] arguments) { - MainCommand.getInstance().toggle.worldedit(this, player, new String[0], null, null); - return true; - } - -} diff --git a/Core/src/main/java/com/plotsquared/core/configuration/Config.java b/Core/src/main/java/com/plotsquared/core/configuration/Config.java index f5b43eff8..a12428a6c 100644 --- a/Core/src/main/java/com/plotsquared/core/configuration/Config.java +++ b/Core/src/main/java/com/plotsquared/core/configuration/Config.java @@ -170,12 +170,11 @@ public class Config { } StringBuilder m = new StringBuilder(); for (Object obj : listValue) { - m.append(System.lineSeparator() + spacing + "- " + toYamlString(obj, spacing)); + m.append(System.lineSeparator()).append(spacing).append("- ").append(toYamlString(obj, spacing)); } return m.toString(); } - if (value instanceof String) { - String stringValue = (String) value; + if (value instanceof String stringValue) { if (stringValue.isEmpty()) { return "''"; } @@ -448,7 +447,7 @@ public class Config { @Ignore // This is not part of the config public static class ConfigBlock { - private HashMap INSTANCES = new HashMap<>(); + private final HashMap INSTANCES = new HashMap<>(); public T get(String key) { return INSTANCES.get(key); diff --git a/Core/src/main/java/com/plotsquared/core/configuration/ConfigurationSection.java b/Core/src/main/java/com/plotsquared/core/configuration/ConfigurationSection.java index e998c676a..af144c0c1 100644 --- a/Core/src/main/java/com/plotsquared/core/configuration/ConfigurationSection.java +++ b/Core/src/main/java/com/plotsquared/core/configuration/ConfigurationSection.java @@ -255,7 +255,7 @@ public interface ConfigurationSection { *

If the path exists but is not a String, this will return false. If * the path does not exist, this will return false. If the path does not * exist but a default value has been specified, this will check if that - * defaultvalue is a String and return appropriately. + * default value is a String and return appropriately. * * @param path Path of the String to check. * @return Whether or not the specified path is a String. diff --git a/Core/src/main/java/com/plotsquared/core/configuration/ConfigurationUtil.java b/Core/src/main/java/com/plotsquared/core/configuration/ConfigurationUtil.java index f4d750fdb..4b59f7e28 100644 --- a/Core/src/main/java/com/plotsquared/core/configuration/ConfigurationUtil.java +++ b/Core/src/main/java/com/plotsquared/core/configuration/ConfigurationUtil.java @@ -45,7 +45,7 @@ import java.util.function.Supplier; */ public class ConfigurationUtil { - public static final SettingValue INTEGER = new SettingValue("INTEGER") { + public static final SettingValue INTEGER = new SettingValue<>("INTEGER") { @Override public boolean validateValue(String string) { try { @@ -61,7 +61,7 @@ public class ConfigurationUtil { return Integer.parseInt(string); } }; - public static final SettingValue BOOLEAN = new SettingValue("BOOLEAN") { + public static final SettingValue BOOLEAN = new SettingValue<>("BOOLEAN") { @Override public boolean validateValue(String string) { //noinspection ResultOfMethodCallIgnored @@ -74,7 +74,7 @@ public class ConfigurationUtil { return Boolean.parseBoolean(string); } }; - public static final SettingValue BIOME = new SettingValue("BIOME") { + public static final SettingValue BIOME = new SettingValue<>("BIOME") { @Override public boolean validateValue(String string) { try { @@ -94,7 +94,7 @@ public class ConfigurationUtil { }; public static final SettingValue BLOCK_BUCKET = - new SettingValue("BLOCK_BUCKET") { + new SettingValue<>("BLOCK_BUCKET") { @Override public BlockBucket parseString(final String string) { diff --git a/Core/src/main/java/com/plotsquared/core/configuration/MemorySection.java b/Core/src/main/java/com/plotsquared/core/configuration/MemorySection.java index 74e8d8dc4..fbe8d142f 100644 --- a/Core/src/main/java/com/plotsquared/core/configuration/MemorySection.java +++ b/Core/src/main/java/com/plotsquared/core/configuration/MemorySection.java @@ -95,8 +95,7 @@ public class MemorySection implements ConfigurationSection { return Double.parseDouble((String) obj); } catch (NumberFormatException ignored) { } - } else if (obj instanceof List) { - List val = (List) obj; + } else if (obj instanceof List val) { if (!val.isEmpty()) { return toDouble(val.get(0), def); } @@ -113,8 +112,7 @@ public class MemorySection implements ConfigurationSection { return Integer.parseInt((String) obj); } catch (NumberFormatException ignored) { } - } else if (obj instanceof List) { - List val = (List) obj; + } else if (obj instanceof List val) { if (!val.isEmpty()) { return toInt(val.get(0), def); } @@ -131,8 +129,7 @@ public class MemorySection implements ConfigurationSection { return Long.parseLong((String) obj); } catch (NumberFormatException ignored) { } - } else if (obj instanceof List) { - List val = (List) obj; + } else if (obj instanceof List val) { if (!val.isEmpty()) { return toLong(val.get(0), def); } @@ -716,8 +713,7 @@ public class MemorySection implements ConfigurationSection { for (Object object : list) { if (object instanceof Character) { result.add((Character) object); - } else if (object instanceof String) { - String str = (String) object; + } else if (object instanceof String str) { if (str.length() == 1) { result.add(str.charAt(0)); @@ -798,14 +794,12 @@ public class MemorySection implements ConfigurationSection { } protected void mapChildrenKeys(Set output, ConfigurationSection section, boolean deep) { - if (section instanceof MemorySection) { - MemorySection sec = (MemorySection) section; + if (section instanceof MemorySection sec) { for (Map.Entry entry : sec.map.entrySet()) { output.add(createPath(section, entry.getKey(), this)); - if (deep && (entry.getValue() instanceof ConfigurationSection)) { - ConfigurationSection subsection = (ConfigurationSection) entry.getValue(); + if (deep && (entry.getValue() instanceof ConfigurationSection subsection)) { mapChildrenKeys(output, subsection, deep); } } @@ -822,8 +816,7 @@ public class MemorySection implements ConfigurationSection { Map output, ConfigurationSection section, boolean deep ) { - if (section instanceof MemorySection) { - MemorySection sec = (MemorySection) section; + if (section instanceof MemorySection sec) { for (Map.Entry entry : sec.map.entrySet()) { output.put(createPath(section, entry.getKey(), this), entry.getValue()); diff --git a/Core/src/main/java/com/plotsquared/core/configuration/Settings.java b/Core/src/main/java/com/plotsquared/core/configuration/Settings.java index 96143ef9c..b22546408 100644 --- a/Core/src/main/java/com/plotsquared/core/configuration/Settings.java +++ b/Core/src/main/java/com/plotsquared/core/configuration/Settings.java @@ -167,9 +167,6 @@ public class Settings extends Config { Teleport.ON_CLEAR = config.getBoolean("teleport.on_clear", Teleport.ON_CLEAR); Teleport.ON_DELETE = config.getBoolean("teleport.on_delete", Teleport.ON_DELETE); - // WorldEdit - //WE_ALLOW_HELPER = config.getBoolean("worldedit.enable-for-helpers"); - // Chunk processor Enabled_Components.CHUNK_PROCESSOR = config.getBoolean("chunk-processor.enabled", Enabled_Components.CHUNK_PROCESSOR); diff --git a/Core/src/main/java/com/plotsquared/core/configuration/file/YamlConfiguration.java b/Core/src/main/java/com/plotsquared/core/configuration/file/YamlConfiguration.java index aa30fcf1a..1ac34021d 100644 --- a/Core/src/main/java/com/plotsquared/core/configuration/file/YamlConfiguration.java +++ b/Core/src/main/java/com/plotsquared/core/configuration/file/YamlConfiguration.java @@ -81,13 +81,11 @@ public class YamlConfiguration extends FileConfiguration { dest = new File(file.getAbsolutePath() + "_broken_" + i++); } Files.copy(file.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING); - if (Settings.DEBUG) { - logger.error("Could not read: {}", file); - logger.error("Renamed to: {}", file); - logger.error("============ Full stacktrace ============"); - ex.printStackTrace(); - logger.error("========================================="); - } + logger.error("Could not read: {}", file); + logger.error("Renamed to: {}", file); + logger.error("============ Full stacktrace ============"); + ex.printStackTrace(); + logger.error("========================================="); } catch (IOException e) { e.printStackTrace(); } @@ -117,7 +115,7 @@ public class YamlConfiguration extends FileConfiguration { Map input; try { - input = (Map) yaml.load(contents); + input = yaml.load(contents); } catch (YAMLException e) { throw new InvalidConfigurationException(e); } catch (ClassCastException ignored) { @@ -183,8 +181,7 @@ public class YamlConfiguration extends FileConfiguration { if (options().copyHeader()) { Configuration def = getDefaults(); - if (def instanceof FileConfiguration) { - FileConfiguration fileDefaults = (FileConfiguration) def; + if (def instanceof FileConfiguration fileDefaults) { String defaultsHeader = fileDefaults.buildHeader(); if ((defaultsHeader != null) && !defaultsHeader.isEmpty()) { diff --git a/Core/src/main/java/com/plotsquared/core/configuration/file/YamlRepresenter.java b/Core/src/main/java/com/plotsquared/core/configuration/file/YamlRepresenter.java index a18fbada2..8945efe3f 100644 --- a/Core/src/main/java/com/plotsquared/core/configuration/file/YamlRepresenter.java +++ b/Core/src/main/java/com/plotsquared/core/configuration/file/YamlRepresenter.java @@ -51,7 +51,6 @@ class YamlRepresenter extends Representer { } - private class RepresentConfigurationSerializable extends RepresentMap { @Override diff --git a/Core/src/main/java/com/plotsquared/core/database/SQLManager.java b/Core/src/main/java/com/plotsquared/core/database/SQLManager.java index 5c1179a8e..84a6500c6 100644 --- a/Core/src/main/java/com/plotsquared/core/database/SQLManager.java +++ b/Core/src/main/java/com/plotsquared/core/database/SQLManager.java @@ -196,10 +196,7 @@ public class SQLManager implements AbstractDB { } TaskManager.runTaskAsync(() -> { long last = System.currentTimeMillis(); - while (true) { - if (SQLManager.this.closed) { - break; - } + while (!SQLManager.this.closed) { boolean hasTask = !globalTasks.isEmpty() || !playerTasks.isEmpty() || !plotTasks.isEmpty() || !clusterTasks.isEmpty(); @@ -685,7 +682,7 @@ public class SQLManager implements AbstractDB { * @param myList list of plots to be created */ public void createTiers(ArrayList myList, final String tier, Runnable whenDone) { - StmtMod mod = new StmtMod() { + StmtMod mod = new StmtMod<>() { @Override public String getCreateMySQL(int size) { return getCreateMySQL(size, SQLManager.this.CREATE_TIERS.replaceAll("%tier%", tier), @@ -750,12 +747,10 @@ public class SQLManager implements AbstractDB { e.printStackTrace(); continue; } - if (Settings.DEBUG) { - logger.info( - "- Finished converting flag values for plot with entry ID: {}", - plot.getId() - ); - } + logger.info( + "- Finished converting flag values for plot with entry ID: {}", + plot.getId() + ); } } catch (final Exception e) { logger.error("Failed to store flag values", e); @@ -770,7 +765,7 @@ public class SQLManager implements AbstractDB { * @param myList list of plots to be created */ public void createPlots(List myList, Runnable whenDone) { - StmtMod mod = new StmtMod() { + StmtMod mod = new StmtMod<>() { @Override public String getCreateMySQL(int size) { return getCreateMySQL(size, SQLManager.this.CREATE_PLOTS, 5); @@ -1007,7 +1002,7 @@ public class SQLManager implements AbstractDB { } public void createEmptySettings(final ArrayList myList, final Runnable whenDone) { - final StmtMod mod = new StmtMod() { + final StmtMod mod = new StmtMod<>() { @Override public String getCreateMySQL(int size) { return getCreateMySQL(size, SQLManager.this.CREATE_SETTINGS, 1); @@ -1673,7 +1668,7 @@ public class SQLManager implements AbstractDB { } public void deleteRows(ArrayList rowIds, final String table, final String column) { - setBulk(rowIds, new StmtMod() { + setBulk(rowIds, new StmtMod<>() { @Override public String getCreateMySQL(int size) { @@ -1786,13 +1781,10 @@ public class SQLManager implements AbstractDB { String.format("%.1f", ((float) flagsProcessed / totalFlags) * 100) ); } - - if (Settings.DEBUG) { - logger.info( - "- Finished converting flags for plot with entry ID: {}", - plotFlagEntry.getKey() - ); - } + logger.info( + "- Finished converting flags for plot with entry ID: {}", + plotFlagEntry.getKey() + ); } } catch (final Exception e) { logger.error("Failed to store flag values", e); @@ -1905,7 +1897,7 @@ public class SQLManager implements AbstractDB { if (last != null) { if (Settings.Enabled_Components.DATABASE_PURGER) { toDelete.add(last.temp); - } else if (Settings.DEBUG) { + } else { logger.info( "Plot #{}({}) in `{}plot` is a duplicate." + " Delete this plot or set `database-purger: true` in the settings.yml", @@ -1942,7 +1934,7 @@ public class SQLManager implements AbstractDB { plot.getSettings().getRatings().put(user, r.getInt("rating")); } else if (Settings.Enabled_Components.DATABASE_PURGER) { toDelete.add(id); - } else if (Settings.DEBUG) { + } else { logger.info("Entry #{}({}) in `plot_rating` does not exist." + " Create this plot or set `database-purger: true` in settings.yml", id, plot); } @@ -1970,7 +1962,7 @@ public class SQLManager implements AbstractDB { plot.getTrusted().add(user); } else if (Settings.Enabled_Components.DATABASE_PURGER) { toDelete.add(id); - } else if (Settings.DEBUG) { + } else { logger.info("Entry #{}({}) in `plot_helpers` does not exist." + " Create this plot or set `database-purger: true` in settings.yml", id, plot); } @@ -1997,7 +1989,7 @@ public class SQLManager implements AbstractDB { plot.getMembers().add(user); } else if (Settings.Enabled_Components.DATABASE_PURGER) { toDelete.add(id); - } else if (Settings.DEBUG) { + } else { logger.info("Entry #{}({}) in `plot_trusted` does not exist." + " Create this plot or set `database-purger: true` in settings.yml", id, plot); } @@ -2024,7 +2016,7 @@ public class SQLManager implements AbstractDB { plot.getDenied().add(user); } else if (Settings.Enabled_Components.DATABASE_PURGER) { toDelete.add(id); - } else if (Settings.DEBUG) { + } else { logger.info("Entry #{}({}) in `plot_denied` does not exist." + " Create this plot or set `database-purger: true` in settings.yml", id, plot); } @@ -2065,7 +2057,7 @@ public class SQLManager implements AbstractDB { } } else if (Settings.Enabled_Components.DATABASE_PURGER) { toDelete.add(id); - } else if (Settings.DEBUG) { + } else { logger.info("Entry #{}({}) in `plot_flags` does not exist." + " Create this plot or set `database-purger: true` in settings.yml", id, plot); } @@ -2076,12 +2068,10 @@ public class SQLManager implements AbstractDB { for (final Map.Entry>> plotFlagEntry : invalidFlags .entrySet()) { for (final PlotFlag flag : plotFlagEntry.getValue()) { - if (Settings.DEBUG) { - logger.info( - "Plot {} has an invalid flag ({}). A fix has been attempted", - plotFlagEntry.getKey(), flag.getName() - ); - } + logger.info( + "Plot {} has an invalid flag ({}). A fix has been attempted", + plotFlagEntry.getKey(), flag.getName() + ); removeFlag(plotFlagEntry.getKey(), flag); } } @@ -2122,7 +2112,7 @@ public class SQLManager implements AbstractDB { plot.getSettings().setMerged(merged); } else if (Settings.Enabled_Components.DATABASE_PURGER) { toDelete.add(id); - } else if (Settings.DEBUG) { + } else { logger.info("Entry #{}({}) in `plot_settings` does not exist." + " Create this plot or set `database-purger: true` in settings.yml", id, plot); } @@ -2295,71 +2285,66 @@ public class SQLManager implements AbstractDB { */ @Override public void purgeIds(final Set uniqueIds) { - addGlobalTask(new Runnable() { - @Override - public void run() { - if (!uniqueIds.isEmpty()) { - try { - ArrayList uniqueIdsList = new ArrayList<>(uniqueIds); - int size = uniqueIdsList.size(); - int packet = 990; - int amount = size / packet; - int count = 0; - int last = -1; - for (int j = 0; j <= amount; j++) { - List subList = - uniqueIdsList.subList(j * packet, Math.min(size, (j + 1) * packet)); - if (subList.isEmpty()) { - break; - } - StringBuilder idstr2 = new StringBuilder(); - String stmt_prefix = ""; - for (Integer id : subList) { - idstr2.append(stmt_prefix).append(id); - stmt_prefix = " OR `id` = "; - } - stmt_prefix = ""; - StringBuilder idstr = new StringBuilder(); - for (Integer id : subList) { - idstr.append(stmt_prefix).append(id); - stmt_prefix = " OR `plot_plot_id` = "; - } - PreparedStatement stmt = SQLManager.this.connection.prepareStatement( - "DELETE FROM `" + SQLManager.this.prefix - + "plot_helpers` WHERE `plot_plot_id` = " + idstr); - stmt.executeUpdate(); - stmt.close(); - stmt = SQLManager.this.connection.prepareStatement( - "DELETE FROM `" + SQLManager.this.prefix - + "plot_denied` WHERE `plot_plot_id` = " + idstr); - stmt.executeUpdate(); - stmt.close(); - stmt = SQLManager.this.connection.prepareStatement( - "DELETE FROM `" + SQLManager.this.prefix - + "plot_settings` WHERE `plot_plot_id` = " + idstr); - stmt.executeUpdate(); - stmt.close(); - stmt = SQLManager.this.connection.prepareStatement( - "DELETE FROM `" + SQLManager.this.prefix - + "plot_trusted` WHERE `plot_plot_id` = " + idstr); - stmt.executeUpdate(); - stmt.close(); - stmt = SQLManager.this.connection.prepareStatement( - "DELETE FROM `" + SQLManager.this.prefix + "plot` WHERE `id` = " - + idstr2); - stmt.executeUpdate(); - stmt.close(); - commit(); + addGlobalTask(() -> { + if (!uniqueIds.isEmpty()) { + try { + ArrayList uniqueIdsList = new ArrayList<>(uniqueIds); + int size = uniqueIdsList.size(); + int packet = 990; + int amount = size / packet; + int count = 0; + int last = -1; + for (int j = 0; j <= amount; j++) { + List subList = + uniqueIdsList.subList(j * packet, Math.min(size, (j + 1) * packet)); + if (subList.isEmpty()) { + break; } - } catch (SQLException e) { - logger.error("Failed to purge plots", e); - return; + StringBuilder idstr2 = new StringBuilder(); + String stmt_prefix = ""; + for (Integer id : subList) { + idstr2.append(stmt_prefix).append(id); + stmt_prefix = " OR `id` = "; + } + stmt_prefix = ""; + StringBuilder idstr = new StringBuilder(); + for (Integer id : subList) { + idstr.append(stmt_prefix).append(id); + stmt_prefix = " OR `plot_plot_id` = "; + } + PreparedStatement stmt = SQLManager.this.connection.prepareStatement( + "DELETE FROM `" + SQLManager.this.prefix + + "plot_helpers` WHERE `plot_plot_id` = " + idstr); + stmt.executeUpdate(); + stmt.close(); + stmt = SQLManager.this.connection.prepareStatement( + "DELETE FROM `" + SQLManager.this.prefix + + "plot_denied` WHERE `plot_plot_id` = " + idstr); + stmt.executeUpdate(); + stmt.close(); + stmt = SQLManager.this.connection.prepareStatement( + "DELETE FROM `" + SQLManager.this.prefix + + "plot_settings` WHERE `plot_plot_id` = " + idstr); + stmt.executeUpdate(); + stmt.close(); + stmt = SQLManager.this.connection.prepareStatement( + "DELETE FROM `" + SQLManager.this.prefix + + "plot_trusted` WHERE `plot_plot_id` = " + idstr); + stmt.executeUpdate(); + stmt.close(); + stmt = SQLManager.this.connection.prepareStatement( + "DELETE FROM `" + SQLManager.this.prefix + "plot` WHERE `id` = " + + idstr2); + stmt.executeUpdate(); + stmt.close(); + commit(); } - } - if (Settings.DEBUG) { - logger.info("Successfully purged {} plots", uniqueIds.size()); + } catch (SQLException e) { + logger.error("Failed to purge plots", e); + return; } } + logger.info("Successfully purged {} plots", uniqueIds.size()); }); } @@ -2919,7 +2904,7 @@ public class SQLManager implements AbstractDB { cluster = clusters.get(id); if (cluster != null) { cluster.helpers.add(user); - } else if (Settings.DEBUG) { + } else { logger.warn("Cluster #{}({}) in cluster_helpers does not exist." + " Please create the cluster or remove this entry", id, cluster); } @@ -2938,7 +2923,7 @@ public class SQLManager implements AbstractDB { cluster = clusters.get(id); if (cluster != null) { cluster.invited.add(user); - } else if (Settings.DEBUG) { + } else { logger.warn("Cluster #{}({}) in cluster_helpers does not exist." + " Please create the cluster or remove this entry", id, cluster); } @@ -2973,7 +2958,7 @@ public class SQLManager implements AbstractDB { merged[3 - i] = (m & 1 << i) != 0; } cluster.settings.setMerged(merged); - } else if (Settings.DEBUG) { + } else { logger.warn("Cluster #{}({}) in cluster_helpers does not exist." + " Please create the cluster or remove this entry", id, cluster); } @@ -3446,7 +3431,7 @@ public class SQLManager implements AbstractDB { } - public abstract class UniqueStatement { + public abstract static class UniqueStatement { public final String method; @@ -3468,7 +3453,7 @@ public class SQLManager implements AbstractDB { } - private class UUIDPair { + private static class UUIDPair { public final int id; public final UUID uuid; diff --git a/Core/src/main/java/com/plotsquared/core/events/Result.java b/Core/src/main/java/com/plotsquared/core/events/Result.java index 452ee1422..0d742f0c6 100644 --- a/Core/src/main/java/com/plotsquared/core/events/Result.java +++ b/Core/src/main/java/com/plotsquared/core/events/Result.java @@ -42,7 +42,7 @@ public enum Result { ACCEPT(1), FORCE(2); - private static Map map = new HashMap<>(); + private static final Map map = new HashMap<>(); static { for (Result eventResult : Result.values()) { @@ -50,7 +50,7 @@ public enum Result { } } - private int value; + private final int value; Result(int value) { this.value = value; diff --git a/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java b/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java index 720597f71..181ca9a9e 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java +++ b/Core/src/main/java/com/plotsquared/core/generator/ClassicPlotManager.java @@ -76,27 +76,16 @@ public class ClassicPlotManager extends SquarePlotManager { @Nullable QueueCoordinator queue ) { final Optional componentOptional = ClassicPlotManagerComponent.fromString(component); - if (componentOptional.isPresent()) { - switch (componentOptional.get()) { - case FLOOR: - return setFloor(plotId, blocks, actor, queue); - case WALL: - return setWallFilling(plotId, blocks, actor, queue); - case AIR: - return setAir(plotId, blocks, actor, queue); - case MAIN: - return setMain(plotId, blocks, actor, queue); - case MIDDLE: - return setMiddle(plotId, blocks, queue); - case OUTLINE: - return setOutline(plotId, blocks, actor, queue); - case BORDER: - return setWall(plotId, blocks, actor, queue); - case ALL: - return setAll(plotId, blocks, actor, queue); - } - } - return false; + return componentOptional.map(classicPlotManagerComponent -> switch (classicPlotManagerComponent) { + case FLOOR -> setFloor(plotId, blocks, actor, queue); + case WALL -> setWallFilling(plotId, blocks, actor, queue); + case AIR -> setAir(plotId, blocks, actor, queue); + case MAIN -> setMain(plotId, blocks, actor, queue); + case MIDDLE -> setMiddle(plotId, blocks, queue); + case OUTLINE -> setOutline(plotId, blocks, actor, queue); + case BORDER -> setWall(plotId, blocks, actor, queue); + case ALL -> setAll(plotId, blocks, actor, queue); + }).orElse(false); } @Override diff --git a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java index 89d873015..c56dd58de 100644 --- a/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java +++ b/Core/src/main/java/com/plotsquared/core/generator/HybridUtils.java @@ -144,11 +144,10 @@ public class HybridUtils { final PlotArea area = this.plotAreaManager.getPlotArea(world, null); - if (!(area instanceof HybridPlotWorld)) { + if (!(area instanceof HybridPlotWorld hpw)) { return; } - HybridPlotWorld hpw = (HybridPlotWorld) area; ChunkQueueCoordinator chunk = new ChunkQueueCoordinator(bot, top, false); hpw.getGenerator().generateChunk(chunk, hpw); @@ -352,7 +351,7 @@ public class HybridUtils { } CuboidRegion region = zones.poll(); final Runnable task = this; - analyzeRegion(origin.getWorldName(), region, new RunnableVal() { + analyzeRegion(origin.getWorldName(), region, new RunnableVal<>() { @Override public void run(PlotAnalysis value) { analysis.add(value); @@ -431,13 +430,11 @@ public class HybridUtils { BlockVector2 chunk = iter.next(); iter.remove(); boolean regenedRoad = regenerateRoad(area, chunk, extend); - if (!regenedRoad && Settings.DEBUG) { + if (!regenedRoad) { logger.info("Failed to regenerate roads"); } } - if (Settings.DEBUG) { - logger.info("Cancelled road task"); - } + logger.info("Cancelled road task"); return; } count.incrementAndGet(); @@ -459,10 +456,8 @@ public class HybridUtils { Iterator iterator = HybridUtils.regions.iterator(); BlockVector2 loc = iterator.next(); iterator.remove(); - if (Settings.DEBUG) { - logger.info("Updating .mcr: {}, {} (approx 1024 chunks)", loc.getX(), loc.getZ()); - logger.info("- Remaining: {}", HybridUtils.regions.size()); - } + logger.info("Updating .mcr: {}, {} (approx 1024 chunks)", loc.getX(), loc.getZ()); + logger.info("- Remaining: {}", HybridUtils.regions.size()); chunks.addAll(getChunks(loc)); System.gc(); } @@ -475,7 +470,7 @@ public class HybridUtils { final BlockVector2 chunk = iterator.next(); iterator.remove(); boolean regenedRoads = regenerateRoad(area, chunk, extend); - if (!regenedRoads && Settings.DEBUG) { + if (!regenedRoads) { logger.info("Failed to regenerate road"); } } diff --git a/Core/src/main/java/com/plotsquared/core/listener/ProcessedWEExtent.java b/Core/src/main/java/com/plotsquared/core/listener/ProcessedWEExtent.java index 0a4ecb9c7..c1cc887fc 100644 --- a/Core/src/main/java/com/plotsquared/core/listener/ProcessedWEExtent.java +++ b/Core/src/main/java/com/plotsquared/core/listener/ProcessedWEExtent.java @@ -64,7 +64,7 @@ public class ProcessedWEExtent extends AbstractDelegateExtent { boolean Eblocked = false; private int count; private Extent parent; - private Map tileEntityCount = new HashMap<>(); + private final Map tileEntityCount = new HashMap<>(); public ProcessedWEExtent( String world, diff --git a/Core/src/main/java/com/plotsquared/core/listener/WESubscriber.java b/Core/src/main/java/com/plotsquared/core/listener/WESubscriber.java index f8e4b14ce..2b8ceb6b5 100644 --- a/Core/src/main/java/com/plotsquared/core/listener/WESubscriber.java +++ b/Core/src/main/java/com/plotsquared/core/listener/WESubscriber.java @@ -98,7 +98,7 @@ public class WESubscriber { if (Permissions.hasPermission(plotPlayer, "plots.worldedit.bypass")) { plotPlayer.sendMessage( TranslatableCaption.of("worldedit.worldedit_bypass"), - Template.of("command", "/plot wea") + Template.of("command", "/plot toggle worldedit") ); } if (this.plotAreaManager.hasPlotArea(world)) { diff --git a/Core/src/main/java/com/plotsquared/core/location/Direction.java b/Core/src/main/java/com/plotsquared/core/location/Direction.java index 5db51046f..4152c586a 100644 --- a/Core/src/main/java/com/plotsquared/core/location/Direction.java +++ b/Core/src/main/java/com/plotsquared/core/location/Direction.java @@ -44,8 +44,8 @@ public enum Direction { ; - private int index; - private String name; + private final int index; + private final String name; Direction(int index, String name) { diff --git a/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java b/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java index 51c47d68c..a5dca5a43 100644 --- a/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/ConsolePlayer.java @@ -58,7 +58,6 @@ import java.util.UUID; public class ConsolePlayer extends PlotPlayer { - private static final Logger logger = LoggerFactory.getLogger("P2/" + ConsolePlayer.class.getSimpleName()); private static final MiniMessage MINI_MESSAGE = MiniMessage.builder().build(); private static ConsolePlayer instance; diff --git a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java index 450d2b429..fb2c764f6 100644 --- a/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java +++ b/Core/src/main/java/com/plotsquared/core/player/PlotPlayer.java @@ -587,9 +587,7 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer, if (Settings.Enabled_Components.BAN_DELETER && isBanned()) { for (Plot owned : getPlots()) { owned.getPlotModificationManager().deletePlot(null, null); - if (Settings.DEBUG) { - logger.info("Plot {} was deleted + cleared due to {} getting banned", owned.getId(), getName()); - } + logger.info("Plot {} was deleted + cleared due to {} getting banned", owned.getId(), getName()); } } if (ExpireManager.IMP != null) { @@ -636,7 +634,7 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer, public void populatePersistentMetaMap() { if (Settings.Enabled_Components.PERSISTENT_META) { - DBFunc.getPersistentMeta(getUUID(), new RunnableVal>() { + DBFunc.getPersistentMeta(getUUID(), new RunnableVal<>() { @Override public void run(Map value) { try { @@ -928,10 +926,9 @@ public abstract class PlotPlayer

implements CommandCaller, OfflinePlotPlayer, @Override public boolean equals(final Object obj) { - if (!(obj instanceof PlotPlayer)) { + if (!(obj instanceof final PlotPlayer other)) { return false; } - final PlotPlayer other = (PlotPlayer) obj; return this.getUUID().equals(other.getUUID()); } diff --git a/Core/src/main/java/com/plotsquared/core/plot/BlockBucket.java b/Core/src/main/java/com/plotsquared/core/plot/BlockBucket.java index 8596685ae..2b4e904a2 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/BlockBucket.java +++ b/Core/src/main/java/com/plotsquared/core/plot/BlockBucket.java @@ -50,10 +50,10 @@ import java.util.regex.Matcher; @SuppressWarnings({"unused", "WeakerAccess"}) public final class BlockBucket implements ConfigurationSerializable { - private static java.util.regex.Pattern regex = java.util.regex.Pattern.compile( + private static final java.util.regex.Pattern regex = java.util.regex.Pattern.compile( "((?[A-Za-z_]+):)?(?([A-Za-z_]+(\\[?[\\S\\s]+\\])?))(:(?[0-9]{1,3}))?"); private boolean compiled; - private StringBuilder input; + private final StringBuilder input; private BlockState single; private Pattern pattern; @@ -198,10 +198,9 @@ public final class BlockBucket implements ConfigurationSerializable { if (o == this) { return true; } - if (!(o instanceof BlockBucket)) { + if (!(o instanceof final BlockBucket other)) { return false; } - final BlockBucket other = (BlockBucket) o; final Object this$input = this.input; final Object other$input = other.input; return Objects.equals(this$input, other$input); @@ -247,10 +246,9 @@ public final class BlockBucket implements ConfigurationSerializable { if (o == this) { return true; } - if (!(o instanceof Range)) { + if (!(o instanceof final Range other)) { return false; } - final Range other = (Range) o; if (this.getMin() != other.getMin()) { return false; } diff --git a/Core/src/main/java/com/plotsquared/core/plot/Plot.java b/Core/src/main/java/com/plotsquared/core/plot/Plot.java index b37920e40..681f6ae2d 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/Plot.java +++ b/Core/src/main/java/com/plotsquared/core/plot/Plot.java @@ -1699,7 +1699,7 @@ public class Plot { e.printStackTrace(); return true; } - schematicHandler.paste(sch, this, 0, 1, 0, Settings.Schematics.PASTE_ON_TOP, player, new RunnableVal() { + schematicHandler.paste(sch, this, 0, 1, 0, Settings.Schematics.PASTE_ON_TOP, player, new RunnableVal<>() { @Override public void run(Boolean value) { if (value) { diff --git a/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java b/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java index 503b030e4..47f00de52 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java +++ b/Core/src/main/java/com/plotsquared/core/plot/PlotArea.java @@ -355,26 +355,10 @@ public abstract class PlotArea { this.minBuildHeight = config.getInt("world.min_height"); switch (config.getString("world.gamemode").toLowerCase()) { - case "creative": - case "c": - case "1": - this.gameMode = GameModes.CREATIVE; - break; - case "adventure": - case "a": - case "2": - this.gameMode = GameModes.ADVENTURE; - break; - case "spectator": - case "3": - this.gameMode = GameModes.SPECTATOR; - break; - case "survival": - case "s": - case "0": - default: - this.gameMode = GameModes.SURVIVAL; - break; + case "creative", "c", "1" -> this.gameMode = GameModes.CREATIVE; + case "adventure", "a", "2" -> this.gameMode = GameModes.ADVENTURE; + case "spectator", "3" -> this.gameMode = GameModes.SPECTATOR; + default -> this.gameMode = GameModes.SURVIVAL; } String homeNonMembers = config.getString("home.nonmembers"); @@ -1114,7 +1098,7 @@ public abstract class PlotArea { public void addCluster(final @Nullable PlotCluster plotCluster) { if (this.clusters == null) { - this.clusters = new QuadMap(Integer.MAX_VALUE, 0, 0, 62) { + this.clusters = new QuadMap<>(Integer.MAX_VALUE, 0, 0, 62) { @Override public CuboidRegion getRegion(PlotCluster value) { BlockVector2 pos1 = BlockVector2.at(value.getP1().getX(), value.getP1().getY()); diff --git a/Core/src/main/java/com/plotsquared/core/plot/PlotId.java b/Core/src/main/java/com/plotsquared/core/plot/PlotId.java index 8b050d756..9785f07e0 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/PlotId.java +++ b/Core/src/main/java/com/plotsquared/core/plot/PlotId.java @@ -181,17 +181,13 @@ public final class PlotId { * @return Relative plot ID */ public @NonNull PlotId getRelative(final @NonNull Direction direction) { - switch (direction) { - case NORTH: - return PlotId.of(this.getX(), this.getY() - 1); - case EAST: - return PlotId.of(this.getX() + 1, this.getY()); - case SOUTH: - return PlotId.of(this.getX(), this.getY() + 1); - case WEST: - return PlotId.of(this.getX() - 1, this.getY()); - } - return this; + return switch (direction) { + case NORTH -> PlotId.of(this.getX(), this.getY() - 1); + case EAST -> PlotId.of(this.getX() + 1, this.getY()); + case SOUTH -> PlotId.of(this.getX(), this.getY() + 1); + case WEST -> PlotId.of(this.getX() - 1, this.getY()); + default -> this; + }; } @Override diff --git a/Core/src/main/java/com/plotsquared/core/plot/PlotInventory.java b/Core/src/main/java/com/plotsquared/core/plot/PlotInventory.java index fc6806ecf..87127b783 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/PlotInventory.java +++ b/Core/src/main/java/com/plotsquared/core/plot/PlotInventory.java @@ -35,8 +35,6 @@ import org.slf4j.LoggerFactory; public class PlotInventory { - private static final Logger logger = LoggerFactory.getLogger("P2/" + PlotInventory.class.getSimpleName()); - private final PlotPlayer player; private final int lines; private final PlotItemStack[] items; diff --git a/Core/src/main/java/com/plotsquared/core/plot/PlotWorld.java b/Core/src/main/java/com/plotsquared/core/plot/PlotWorld.java index d4b280527..5477f8cc0 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/PlotWorld.java +++ b/Core/src/main/java/com/plotsquared/core/plot/PlotWorld.java @@ -106,10 +106,9 @@ public abstract class PlotWorld { if (o == this) { return true; } - if (!(o instanceof PlotWorld)) { + if (!(o instanceof final PlotWorld other)) { return false; } - final PlotWorld other = (PlotWorld) o; if (!other.canEqual(this)) { return false; } diff --git a/Core/src/main/java/com/plotsquared/core/plot/comment/CommentInbox.java b/Core/src/main/java/com/plotsquared/core/plot/comment/CommentInbox.java index 233c53841..06e3696e6 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/comment/CommentInbox.java +++ b/Core/src/main/java/com/plotsquared/core/plot/comment/CommentInbox.java @@ -58,11 +58,11 @@ public abstract class CommentInbox { */ public boolean canWrite(Plot plot, PlotPlayer player) { if (plot == null) { - return Permissions.hasPermission(player, "plots.inbox.write." + toString(), true); + return Permissions.hasPermission(player, "plots.inbox.write." + this, true); } - return Permissions.hasPermission(player, "plots.inbox.write." + toString(), true) && ( + return Permissions.hasPermission(player, "plots.inbox.write." + this, true) && ( plot.isOwner(player.getUUID()) || Permissions - .hasPermission(player, "plots.inbox.write." + toString() + ".other", true)); + .hasPermission(player, "plots.inbox.write." + this + ".other", true)); } /** @@ -72,9 +72,9 @@ public abstract class CommentInbox { */ @SuppressWarnings({"BooleanMethodIsAlwaysInverted"}) public boolean canModify(Plot plot, PlotPlayer player) { - if (Permissions.hasPermission(player, "plots.inbox.modify." + toString(), true)) { + if (Permissions.hasPermission(player, "plots.inbox.modify." + this, true)) { return plot.isOwner(player.getUUID()) || Permissions - .hasPermission(player, "plots.inbox.modify." + toString() + ".other", true); + .hasPermission(player, "plots.inbox.modify." + this + ".other", true); } return false; } diff --git a/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java b/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java index 0c90bc667..5f56e77a1 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java +++ b/Core/src/main/java/com/plotsquared/core/plot/expiration/ExpireManager.java @@ -70,7 +70,6 @@ import java.util.concurrent.ConcurrentLinkedDeque; public class ExpireManager { public static ExpireManager IMP; - private final Logger logger = LoggerFactory.getLogger("P2/" + ExpireManager.class); private final ConcurrentHashMap dates_cache; private final ConcurrentHashMap account_age_cache; private final EventDispatcher eventDispatcher; @@ -195,7 +194,7 @@ public class ExpireManager { } public boolean runAutomatedTask() { - return runTask(new RunnableVal3() { + return runTask(new RunnableVal3<>() { @Override public void run(Plot plot, Runnable runnable, Boolean confirm) { if (confirm) { @@ -346,10 +345,10 @@ public class ExpireManager { } } final RunnableVal handleAnalysis = - new RunnableVal() { + new RunnableVal<>() { @Override public void run(final PlotAnalysis changed) { - passesComplexity(changed, expired, new RunnableVal() { + passesComplexity(changed, expired, new RunnableVal<>() { @Override public void run(Boolean confirmation) { expiredTask.run( @@ -379,7 +378,7 @@ public class ExpireManager { PlotAnalysis analysis = newPlot.getComplexity(null); if (analysis != null) { - passesComplexity(analysis, expired, new RunnableVal() { + passesComplexity(analysis, expired, new RunnableVal<>() { @Override public void run(Boolean value) { doAnalysis.run(); diff --git a/Core/src/main/java/com/plotsquared/core/plot/expiration/PlotAnalysis.java b/Core/src/main/java/com/plotsquared/core/plot/expiration/PlotAnalysis.java index 376e85313..2322af70f 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/expiration/PlotAnalysis.java +++ b/Core/src/main/java/com/plotsquared/core/plot/expiration/PlotAnalysis.java @@ -97,16 +97,11 @@ public class PlotAnalysis { */ public static void calcOptimalModifiers(final Runnable whenDone, final double threshold) { if (running) { - if (Settings.DEBUG) { - logger.info("Calibration task already in progress!"); - } + logger.info("Calibration task already in progress!"); return; } if (threshold <= 0 || threshold >= 1) { - if (Settings.DEBUG) { - logger.info( - "Invalid threshold provided! (Cannot be 0 or 100 as then there's no point in calibrating)"); - } + logger.info("Invalid threshold provided! (Cannot be 0 or 100 as then there's no point in calibrating)"); return; } running = true; @@ -115,9 +110,7 @@ public class PlotAnalysis { @Override public void run() { Iterator iterator = plots.iterator(); - if (Settings.DEBUG) { - logger.info("- Reducing {} plots to those with sufficient data", plots.size()); - } + logger.info("- Reducing {} plots to those with sufficient data", plots.size()); while (iterator.hasNext()) { Plot plot = iterator.next(); if (plot.getSettings().getRatings() == null || plot.getSettings().getRatings() @@ -129,20 +122,14 @@ public class PlotAnalysis { } if (plots.size() < 3) { - if (Settings.DEBUG) { - logger.info( - "Calibration cancelled due to insufficient comparison data, please try again later"); - } + logger.info("Calibration cancelled due to insufficient comparison data, please try again later"); running = false; for (Plot plot : plots) { plot.removeRunning(); } return; } - - if (Settings.DEBUG) { - logger.info("- Analyzing plot contents (this may take a while)"); - } + logger.info("- Analyzing plot contents (this may take a while)"); int[] changes = new int[plots.size()]; int[] faces = new int[plots.size()]; @@ -160,19 +147,15 @@ public class PlotAnalysis { final AtomicInteger mi = new AtomicInteger(0); - Thread ratingAnalysis = new Thread(new Runnable() { - @Override - public void run() { - for (; mi.intValue() < plots.size(); mi.incrementAndGet()) { - int i = mi.intValue(); - Plot plot = plots.get(i); - ratings[i] = (int) ( - (plot.getAverageRating() + plot.getSettings().getRatings().size()) - * 100); - if (Settings.DEBUG) { - logger.info(" | {} (rating) {}", plot, ratings[i]); - } - } + Thread ratingAnalysis = new Thread(() -> { + for (; mi.intValue() < plots.size(); mi.incrementAndGet()) { + int i = mi.intValue(); + Plot plot = plots.get(i); + ratings[i] = (int) ( + (plot.getAverageRating() + plot.getSettings().getRatings().size()) + * 100); + logger.info(" | {} (rating) {}", plot, ratings[i]); + } }); ratingAnalysis.start(); @@ -183,14 +166,13 @@ public class PlotAnalysis { if (queuePlot == null) { break; } - if (Settings.DEBUG) { - logger.info(" | {}", queuePlot); - } + logger.info(" | {}", queuePlot); + final Object lock = new Object(); TaskManager.runTask(new Runnable() { @Override public void run() { - analyzePlot(queuePlot, new RunnableVal() { + analyzePlot(queuePlot, new RunnableVal<>() { @Override public void run(PlotAnalysis value) { try { @@ -217,9 +199,7 @@ public class PlotAnalysis { } } - if (Settings.DEBUG) { - logger.info(" - Waiting on plot rating thread: {}%", mi.intValue() * 100 / plots.size()); - } + logger.info(" - Waiting on plot rating thread: {}%", mi.intValue() * 100 / plots.size()); try { ratingAnalysis.join(); @@ -227,15 +207,12 @@ public class PlotAnalysis { e.printStackTrace(); } - if (Settings.DEBUG) { - logger.info( - " - Processing and grouping single plot analysis for bulk processing"); - } + logger.info(" - Processing and grouping single plot analysis for bulk processing"); + for (int i = 0; i < plots.size(); i++) { Plot plot = plots.get(i); - if (Settings.DEBUG) { - logger.info(" | {}", plot); - } + logger.info(" | {}", plot); + PlotAnalysis analysis = plot.getComplexity(null); changes[i] = analysis.changes; @@ -251,22 +228,16 @@ public class PlotAnalysis { variety_sd[i] = analysis.variety_sd; } - if (Settings.DEBUG) { - logger.info(" - Calculating rankings"); - } + logger.info(" - Calculating rankings"); int[] rankRatings = rank(ratings); int n = rankRatings.length; int optimalIndex = (int) Math.round((1 - threshold) * (n - 1)); - if (Settings.DEBUG) { - logger.info(" - Calculating rank correlation: "); - logger.info( - " - The analyzed plots which were processed and put into bulk data will be compared and correlated to the plot ranking"); - logger.info( - " - The calculated correlation constant will then be used to calibrate the threshold for auto plot clearing"); - } + logger.info(" - Calculating rank correlation: "); + logger.info(" - The analyzed plots which were processed and put into bulk data will be compared and correlated to the plot ranking"); + logger.info(" - The calculated correlation constant will then be used to calibrate the threshold for auto plot clearing"); Settings.Auto_Clear settings = new Settings.Auto_Clear(); @@ -279,9 +250,7 @@ public class PlotAnalysis { 0 : (int) (factorChanges * 1000 / MathMan.getMean(changes)); - if (Settings.DEBUG) { - logger.info(" - | changes {}", factorChanges); - } + logger.info(" - | changes {}", factorChanges); int[] rankFaces = rank(faces); int[] sdFaces = getSD(rankFaces, rankRatings); @@ -291,9 +260,7 @@ public class PlotAnalysis { settings.CALIBRATION.FACES = factorFaces == 1 ? 0 : (int) (factorFaces * 1000 / MathMan.getMean(faces)); - if (Settings.DEBUG) { - logger.info(" - | faces {}", factorFaces); - } + logger.info(" - | faces {}", factorFaces); int[] rankData = rank(data); int[] sdData = getSD(rankData, rankRatings); @@ -303,9 +270,7 @@ public class PlotAnalysis { settings.CALIBRATION.DATA = factor_data == 1 ? 0 : (int) (factor_data * 1000 / MathMan.getMean(data)); - if (Settings.DEBUG) { - logger.info(" - | data {}", factor_data); - } + logger.info(" - | data {}", factor_data); int[] rank_air = rank(air); int[] sd_air = getSD(rank_air, rankRatings); @@ -315,9 +280,8 @@ public class PlotAnalysis { settings.CALIBRATION.AIR = factor_air == 1 ? 0 : (int) (factor_air * 1000 / MathMan.getMean(air)); - if (Settings.DEBUG) { - logger.info("- | air {}", factor_air); - } + logger.info("- | air {}", factor_air); + int[] rank_variety = rank(variety); int[] sd_variety = getSD(rank_variety, rankRatings); @@ -328,9 +292,7 @@ public class PlotAnalysis { 0 : (int) (factor_variety * 1000 / MathMan.getMean(variety)); - if (Settings.DEBUG) { - logger.info("- | variety {}", factor_variety); - } + logger.info("- | variety {}", factor_variety); int[] rank_changes_sd = rank(changes_sd); int[] sd_changes_sd = getSD(rank_changes_sd, rankRatings); @@ -341,9 +303,7 @@ public class PlotAnalysis { 0 : (int) (factor_changes_sd * 1000 / MathMan.getMean(changes_sd)); - if (Settings.DEBUG) { - logger.info(" - | changed_sd {}", factor_changes_sd); - } + logger.info(" - | changed_sd {}", factor_changes_sd); int[] rank_faces_sd = rank(faces_sd); int[] sd_faces_sd = getSD(rank_faces_sd, rankRatings); @@ -354,9 +314,7 @@ public class PlotAnalysis { 0 : (int) (factor_faces_sd * 1000 / MathMan.getMean(faces_sd)); - if (Settings.DEBUG) { - logger.info(" - | faced_sd {}", factor_faces_sd); - } + logger.info(" - | faced_sd {}", factor_faces_sd); int[] rank_data_sd = rank(data_sd); int[] sd_data_sd = getSD(rank_data_sd, rankRatings); @@ -367,9 +325,7 @@ public class PlotAnalysis { 0 : (int) (factor_data_sd * 1000 / MathMan.getMean(data_sd)); - if (Settings.DEBUG) { - logger.info(" - | data_sd {}", factor_data_sd); - } + logger.info(" - | data_sd {}", factor_data_sd); int[] rank_air_sd = rank(air_sd); int[] sd_air_sd = getSD(rank_air_sd, rankRatings); @@ -379,9 +335,7 @@ public class PlotAnalysis { settings.CALIBRATION.AIR_SD = factor_air_sd == 1 ? 0 : (int) (factor_air_sd * 1000 / MathMan.getMean(air_sd)); - if (Settings.DEBUG) { - logger.info(" - | air_sd {}", factor_air_sd); - } + logger.info(" - | air_sd {}", factor_air_sd); int[] rank_variety_sd = rank(variety_sd); int[] sd_variety_sd = getSD(rank_variety_sd, rankRatings); @@ -392,15 +346,11 @@ public class PlotAnalysis { 0 : (int) (factor_variety_sd * 1000 / MathMan.getMean(variety_sd)); - if (Settings.DEBUG) { - logger.info(" - | variety_sd {}", factor_variety_sd); - } + logger.info(" - | variety_sd {}", factor_variety_sd); int[] complexity = new int[n]; - if (Settings.DEBUG) { - logger.info(" Calculating threshold"); - } + logger.info("Calculating threshold"); int max = 0; int min = 0; @@ -430,11 +380,9 @@ public class PlotAnalysis { logln("Correlation: "); logln(getCC(n, sum(square(getSD(rankComplexity, rankRatings))))); if (optimalComplexity == Integer.MAX_VALUE) { - if (Settings.DEBUG) { - logger.info("Insufficient data to determine correlation! {} | {}", + logger.info("Insufficient data to determine correlation! {} | {}", optimalIndex, n ); - } running = false; for (Plot plot : plots) { plot.removeRunning(); @@ -444,7 +392,6 @@ public class PlotAnalysis { } else { // Use the fast radix sort algorithm int[] sorted = complexity.clone(); sort(sorted); - optimalComplexity = sorted[optimalIndex]; logln("Complexity: "); logln(complexity); logln("Ratings: "); @@ -452,43 +399,37 @@ public class PlotAnalysis { } // Save calibration - if (Settings.DEBUG) { - logger.info(" Saving calibration"); - } + logger.info(" Saving calibration"); Settings.AUTO_CLEAR.put("auto-calibrated", settings); Settings.save(PlotSquared.get().getWorldsFile()); running = false; for (Plot plot : plots) { plot.removeRunning(); } - if (Settings.DEBUG) { - logger.info(" Done!"); - } + logger.info(" Done!"); whenDone.run(); } }); } public static void logln(Object obj) { - if (Settings.DEBUG) { - logger.info("" + log(obj)); - } + logger.info("" + log(obj)); } public static String log(Object obj) { - String result = ""; + StringBuilder result = new StringBuilder(); if (obj.getClass().isArray()) { String prefix = ""; for (int i = 0; i < Array.getLength(obj); i++) { - result += prefix + log(Array.get(obj, i)); + result.append(prefix).append(log(Array.get(obj, i))); prefix = ","; } return "( " + result + " )"; } else if (obj instanceof List) { String prefix = ""; for (Object element : (List) obj) { - result += prefix + log(element); + result.append(prefix).append(log(element)); prefix = ","; } return "[ " + result + " ]"; diff --git a/Core/src/main/java/com/plotsquared/core/plot/flag/FlagContainer.java b/Core/src/main/java/com/plotsquared/core/plot/flag/FlagContainer.java index c65573ce7..1c32a5634 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/flag/FlagContainer.java +++ b/Core/src/main/java/com/plotsquared/core/plot/flag/FlagContainer.java @@ -340,10 +340,9 @@ public class FlagContainer { if (o == this) { return true; } - if (!(o instanceof FlagContainer)) { + if (!(o instanceof final FlagContainer other)) { return false; } - final FlagContainer other = (FlagContainer) o; if (!other.canEqual(this)) { return false; } diff --git a/Core/src/main/java/com/plotsquared/core/plot/flag/PlotFlag.java b/Core/src/main/java/com/plotsquared/core/plot/flag/PlotFlag.java index d0b05dcd7..185a3cd19 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/flag/PlotFlag.java +++ b/Core/src/main/java/com/plotsquared/core/plot/flag/PlotFlag.java @@ -193,11 +193,10 @@ public abstract class PlotFlag> { if (o == this) { return true; } - if (!(o instanceof PlotFlag)) { + if (!(o instanceof final PlotFlag other)) { return false; } - final PlotFlag other = (PlotFlag) o; - if (!other.canEqual((Object) this)) { + if (!other.canEqual(this)) { return false; } final Object this$value = this.getValue(); diff --git a/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/FlyFlag.java b/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/FlyFlag.java index 0c705a2ff..c86a04029 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/FlyFlag.java +++ b/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/FlyFlag.java @@ -48,18 +48,11 @@ public class FlyFlag extends PlotFlag { @Override public FlyFlag parse(final @NonNull String input) { - switch (input.toLowerCase()) { - case "true": - case "enabled": - case "allow": - return FLIGHT_FLAG_ENABLED; - case "false": - case "disabled": - case "disallow": - return FLIGHT_FLAG_DISABLED; - default: - return FLIGHT_FLAG_DEFAULT; - } + return switch (input.toLowerCase()) { + case "true", "enabled", "allow" -> FLIGHT_FLAG_ENABLED; + case "false", "disabled", "disallow" -> FLIGHT_FLAG_DISABLED; + default -> FLIGHT_FLAG_DEFAULT; + }; } @Override diff --git a/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/GamemodeFlag.java b/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/GamemodeFlag.java index a1a0d2319..6fdb5d46d 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/GamemodeFlag.java +++ b/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/GamemodeFlag.java @@ -65,26 +65,13 @@ public class GamemodeFlag extends PlotFlag { @Override public GamemodeFlag parse(@NonNull String input) throws FlagParseException { - switch (input) { - case "creative": - case "c": - case "1": - return flagOf(GameModes.CREATIVE); - case "adventure": - case "a": - case "2": - return flagOf(GameModes.ADVENTURE); - case "spectator": - case "sp": - case "3": - return flagOf(GameModes.SPECTATOR); - case "survival": - case "s": - case "0": - return flagOf(GameModes.SURVIVAL); - default: - return flagOf(DEFAULT); - } + return switch (input) { + case "creative", "c", "1" -> flagOf(GameModes.CREATIVE); + case "adventure", "a", "2" -> flagOf(GameModes.ADVENTURE); + case "spectator", "sp", "3" -> flagOf(GameModes.SPECTATOR); + case "survival", "s", "0" -> flagOf(GameModes.SURVIVAL); + default -> flagOf(DEFAULT); + }; } @Override @@ -104,18 +91,13 @@ public class GamemodeFlag extends PlotFlag { @Override protected GamemodeFlag flagOf(@NonNull GameMode value) { - switch (value.getId()) { - case "creative": - return GAMEMODE_FLAG_CREATIVE; - case "adventure": - return GAMEMODE_FLAG_ADVENTURE; - case "spectator": - return GAMEMODE_FLAG_SPECTATOR; - case "survival": - return GAMEMODE_FLAG_SURVIVAL; - default: - return GAMEMODE_FLAG_DEFAULT; - } + return switch (value.getId()) { + case "creative" -> GAMEMODE_FLAG_CREATIVE; + case "adventure" -> GAMEMODE_FLAG_ADVENTURE; + case "spectator" -> GAMEMODE_FLAG_SPECTATOR; + case "survival" -> GAMEMODE_FLAG_SURVIVAL; + default -> GAMEMODE_FLAG_DEFAULT; + }; } @Override diff --git a/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/GuestGamemodeFlag.java b/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/GuestGamemodeFlag.java index 4997cb483..f082360e8 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/GuestGamemodeFlag.java +++ b/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/GuestGamemodeFlag.java @@ -60,26 +60,13 @@ public class GuestGamemodeFlag extends PlotFlag { @Override public GuestGamemodeFlag parse(@NonNull String input) throws FlagParseException { - switch (input) { - case "creative": - case "c": - case "1": - return flagOf(GameModes.CREATIVE); - case "adventure": - case "a": - case "2": - return flagOf(GameModes.ADVENTURE); - case "spectator": - case "sp": - case "3": - return flagOf(GameModes.SPECTATOR); - case "survival": - case "s": - case "0": - return flagOf(GameModes.SURVIVAL); - default: - return flagOf(GamemodeFlag.DEFAULT); - } + return switch (input) { + case "creative", "c", "1" -> flagOf(GameModes.CREATIVE); + case "adventure", "a", "2" -> flagOf(GameModes.ADVENTURE); + case "spectator", "sp", "3" -> flagOf(GameModes.SPECTATOR); + case "survival", "s", "0" -> flagOf(GameModes.SURVIVAL); + default -> flagOf(GamemodeFlag.DEFAULT); + }; } @Override @@ -99,18 +86,13 @@ public class GuestGamemodeFlag extends PlotFlag { @Override protected GuestGamemodeFlag flagOf(@NonNull GameMode value) { - switch (value.getId()) { - case "creative": - return GUEST_GAMEMODE_FLAG_CREATIVE; - case "adventure": - return GUEST_GAMEMODE_FLAG_ADVENTURE; - case "spectator": - return GUEST_GAMEMODE_FLAG_SPECTATOR; - case "survival": - return GUEST_GAMEMODE_FLAG_SURVIVAL; - default: - return GUEST_GAMEMODE_FLAG_DEFAULT; - } + return switch (value.getId()) { + case "creative" -> GUEST_GAMEMODE_FLAG_CREATIVE; + case "adventure" -> GUEST_GAMEMODE_FLAG_ADVENTURE; + case "spectator" -> GUEST_GAMEMODE_FLAG_SPECTATOR; + case "survival" -> GUEST_GAMEMODE_FLAG_SURVIVAL; + default -> GUEST_GAMEMODE_FLAG_DEFAULT; + }; } } diff --git a/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/KeepFlag.java b/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/KeepFlag.java index 7104930cc..3d9a70c60 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/KeepFlag.java +++ b/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/KeepFlag.java @@ -55,14 +55,11 @@ public class KeepFlag extends PlotFlag { return flagOf(value); } } - switch (input.toLowerCase()) { - case "true": - return flagOf(true); - case "false": - return flagOf(false); - default: - return flagOf(TimeUtil.timeToSec(input) * 1000 + System.currentTimeMillis()); - } + return switch (input.toLowerCase()) { + case "true" -> flagOf(true); + case "false" -> flagOf(false); + default -> flagOf(TimeUtil.timeToSec(input) * 1000 + System.currentTimeMillis()); + }; } @Override diff --git a/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/LiquidFlowFlag.java b/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/LiquidFlowFlag.java index f3a4fa95d..7c9b62cc7 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/LiquidFlowFlag.java +++ b/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/LiquidFlowFlag.java @@ -49,18 +49,11 @@ public class LiquidFlowFlag extends PlotFlag LIQUID_FLOW_ENABLED; + case "false", "disabled", "disallow" -> LIQUID_FLOW_DISABLED; + default -> LIQUID_FLOW_DEFAULT; + }; } @Override @@ -83,14 +76,11 @@ public class LiquidFlowFlag extends PlotFlag LIQUID_FLOW_ENABLED; + case DISABLED -> LIQUID_FLOW_DISABLED; + default -> LIQUID_FLOW_DEFAULT; + }; } @Override diff --git a/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/WeatherFlag.java b/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/WeatherFlag.java index c7d4ec9f9..404a37e15 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/WeatherFlag.java +++ b/Core/src/main/java/com/plotsquared/core/plot/flag/implementations/WeatherFlag.java @@ -54,20 +54,11 @@ public class WeatherFlag extends PlotFlag { @Override public WeatherFlag parse(@NonNull String input) { - switch (input.toLowerCase()) { - case "rain": - case "storm": - case "on": - case "lightning": - case "thunder": - return flagOf(PlotWeather.RAIN); - case "clear": - case "off": - case "sun": - return flagOf(PlotWeather.CLEAR); - default: - return flagOf(PlotWeather.RESET); - } + return switch (input.toLowerCase()) { + case "rain" -> flagOf(PlotWeather.RAIN); + case "clear" -> flagOf(PlotWeather.CLEAR); + default -> flagOf(PlotWeather.RESET); + }; } @Override @@ -82,25 +73,22 @@ public class WeatherFlag extends PlotFlag { @Override public String getExample() { - return "storm"; + return "rain"; } @Override protected WeatherFlag flagOf(@NonNull PlotWeather value) { - switch (value) { - case RAIN: - return PLOT_WEATHER_FLAG_RAIN; - case CLEAR: - return PLOT_WEATHER_FLAG_CLEAR; - default: - return PLOT_WEATHER_FLAG_OFF; - } + return switch (value) { + case RAIN -> PLOT_WEATHER_FLAG_RAIN; + case CLEAR -> PLOT_WEATHER_FLAG_CLEAR; + default -> PLOT_WEATHER_FLAG_OFF; + }; } @Override public Collection getTabCompletions() { return Arrays - .asList("rain", "storm", "on", "lightning", "thunder", "clear", "off", "sun", "reset"); + .asList("clear", "rain"); } } diff --git a/Core/src/main/java/com/plotsquared/core/plot/world/SinglePlot.java b/Core/src/main/java/com/plotsquared/core/plot/world/SinglePlot.java index f31573496..29f19b284 100644 --- a/Core/src/main/java/com/plotsquared/core/plot/world/SinglePlot.java +++ b/Core/src/main/java/com/plotsquared/core/plot/world/SinglePlot.java @@ -44,7 +44,7 @@ import java.util.function.Consumer; public class SinglePlot extends Plot { - private Set regions = Collections.singleton( + private final Set regions = Collections.singleton( new CuboidRegion( BlockVector3.at(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE), BlockVector3.at(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE) diff --git a/Core/src/main/java/com/plotsquared/core/setup/CommonSetupSteps.java b/Core/src/main/java/com/plotsquared/core/setup/CommonSetupSteps.java index 3a2851b21..690e417ed 100644 --- a/Core/src/main/java/com/plotsquared/core/setup/CommonSetupSteps.java +++ b/Core/src/main/java/com/plotsquared/core/setup/CommonSetupSteps.java @@ -278,9 +278,7 @@ public enum CommonSetupSteps implements SetupStep { } private static boolean isValidWorldName(String s) { - return s.chars().allMatch((i) -> { - return i == 95 || i == 45 || i >= 97 && i <= 122 || i >= 65 && i <= 90 || i >= 48 && i <= 57 || i == 46; - }); + return s.chars().allMatch((i) -> i == 95 || i == 45 || i >= 97 && i <= 122 || i >= 65 && i <= 90 || i >= 48 && i <= 57 || i == 46); } @Override diff --git a/Core/src/main/java/com/plotsquared/core/util/BlockUtil.java b/Core/src/main/java/com/plotsquared/core/util/BlockUtil.java index d3a78eef6..669cf020c 100644 --- a/Core/src/main/java/com/plotsquared/core/util/BlockUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/BlockUtil.java @@ -135,7 +135,7 @@ public final class BlockUtil { * Deserialize a serialized {@link BlockState} * * @param map Serialized block state - * @return Deserialized block state, or {@code null} if the map is + * @return Deserialized block state, or {@code null} if the map is * not a properly serialized block state */ public static @Nullable BlockState deserialize(final @NonNull Map map) { diff --git a/Core/src/main/java/com/plotsquared/core/util/MainUtil.java b/Core/src/main/java/com/plotsquared/core/util/MainUtil.java index 443255d9f..eebacec78 100644 --- a/Core/src/main/java/com/plotsquared/core/util/MainUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/MainUtil.java @@ -25,9 +25,6 @@ */ package com.plotsquared.core.util; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * plot functions * @@ -36,9 +33,6 @@ import org.slf4j.LoggerFactory; @Deprecated public class MainUtil { - private static final Logger logger = - LoggerFactory.getLogger("P2/" + MainUtil.class.getSimpleName()); - /** * Cache of mapping x,y,z coordinates to the chunk array
* - Used for efficient world generation
diff --git a/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java b/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java index 831a95ecb..681fa6a40 100644 --- a/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java +++ b/Core/src/main/java/com/plotsquared/core/util/WorldUtil.java @@ -355,7 +355,7 @@ public abstract class WorldUtil { * * @param block1 First block * @param block2 Second block - * @return {@code true} if the blocks have the same type, {@code false} if not + * @return {@code true} if the blocks have the same type, {@code false} if not */ public abstract boolean isBlockSame(@NonNull BlockState block1, @NonNull BlockState block2); diff --git a/Core/src/main/java/com/plotsquared/core/util/net/HttpUtil.java b/Core/src/main/java/com/plotsquared/core/util/net/HttpUtil.java deleted file mode 100644 index b2ffc0b54..000000000 --- a/Core/src/main/java/com/plotsquared/core/util/net/HttpUtil.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * _____ _ _ _____ _ - * | __ \| | | | / ____| | | - * | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| | - * | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` | - * | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| | - * |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_| - * | | - * |_| - * PlotSquared plot management system for Minecraft - * Copyright (C) 2021 IntellectualSites - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.plotsquared.core.util.net; - -import com.plotsquared.core.configuration.Settings; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.URL; - -public class HttpUtil { - - public static String readUrl(String urlString) { - try (BufferedReader reader = new BufferedReader( - new InputStreamReader(new URL(urlString).openStream()))) { - StringBuilder buffer = new StringBuilder(); - int read; - char[] chars = new char[1024]; - while ((read = reader.read(chars)) != -1) { - buffer.append(chars, 0, read); - } - return buffer.toString(); - } catch (IOException e) { - if (Settings.DEBUG) { - e.printStackTrace(); - } - } - return null; - } - -} diff --git a/Core/src/main/java/com/plotsquared/core/uuid/UUIDMapping.java b/Core/src/main/java/com/plotsquared/core/uuid/UUIDMapping.java index 6b515606d..f25f59612 100644 --- a/Core/src/main/java/com/plotsquared/core/uuid/UUIDMapping.java +++ b/Core/src/main/java/com/plotsquared/core/uuid/UUIDMapping.java @@ -55,10 +55,9 @@ public class UUIDMapping { if (o == this) { return true; } - if (!(o instanceof UUIDMapping)) { + if (!(o instanceof final UUIDMapping other)) { return false; } - final UUIDMapping other = (UUIDMapping) o; if (!other.canEqual(this)) { return false; } diff --git a/Core/src/main/java/com/plotsquared/core/uuid/UUIDPipeline.java b/Core/src/main/java/com/plotsquared/core/uuid/UUIDPipeline.java index f0150c6e0..97a49f680 100644 --- a/Core/src/main/java/com/plotsquared/core/uuid/UUIDPipeline.java +++ b/Core/src/main/java/com/plotsquared/core/uuid/UUIDPipeline.java @@ -176,7 +176,7 @@ public class UUIDPipeline { } catch (TimeoutException ignored) { // This is completely valid, we just don't care anymore if (Settings.DEBUG) { - logger.warn("(UUID) Request for {} timed out", username); + logger.warn("(UUID) Request for {} timed out. Rate limit.", username); } } return null; @@ -201,7 +201,7 @@ public class UUIDPipeline { } catch (TimeoutException ignored) { // This is completely valid, we just don't care anymore if (Settings.DEBUG) { - logger.warn("(UUID) Request for {} timed out", uuid); + logger.warn("(UUID) Request for {} timed out. Rate limit.", uuid); } } return null; diff --git a/Core/src/main/resources/lang/messages_en.json b/Core/src/main/resources/lang/messages_en.json index a36726441..c5528654d 100644 --- a/Core/src/main/resources/lang/messages_en.json +++ b/Core/src/main/resources/lang/messages_en.json @@ -392,7 +392,6 @@ "members.not_added_trusted": "You must be added or trusted to the plot to run that command.", "owner.set_owner": "You successfully set the plot owner.", "owner.set_owner_cancelled": "The set owner action was cancelled.", - "owner.set_owner_missing_player": "You need to specify a new owner.", "owner.now_owner": "You are now the plot owner of plot .", "signs.owner_sign_line_1": "ID: ", "signs.owner_sign_line_2": "Owner:",