From 8b1e0f41ba05657f5bab82a51e79e63687f1195f Mon Sep 17 00:00:00 2001 From: tastybento Date: Tue, 24 Nov 2026 19:47:57 -0800 Subject: [PATCH] Fix the code smells SonarCloud raised on Boxed II - Split the long methods in AreaManager, TemplateBuilder and BoxCleaner - Rename the AreaManager field that clashed with a constant - TemplateFile.read returns an empty array, not null, for a missing chunk - Delete seed world files with Files.delete so a failure is reported - Smaller tidy-ups: unnamed catch variables, computeIfAbsent, a record pattern, a constant for a repeated literal, an unused import, and a loop that changed its own counter No change in behaviour. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HBXcjZkd22rGNW5ZyL1git --- src/main/java/world/bentobox/boxed/Boxed.java | 5 +- .../bentobox/boxed/areas/AreaManager.java | 63 ++++++++++++------- .../boxed/commands/AdminAreasCommand.java | 10 +-- .../boxed/generators/template/RawBiomes.java | 4 +- .../boxed/generators/template/Template.java | 4 +- .../generators/template/TemplateBuilder.java | 55 ++++++++-------- .../generators/template/TemplateChunk.java | 17 +++-- .../generators/template/TemplateFile.java | 8 +-- .../bentobox/boxed/listeners/BoxCleaner.java | 35 +++++++---- .../boxed/areas/AreaLocationStrategyTest.java | 4 +- .../bentobox/boxed/areas/BoxHeightTest.java | 3 +- .../generators/template/TemplateFileTest.java | 6 +- 12 files changed, 124 insertions(+), 90 deletions(-) diff --git a/src/main/java/world/bentobox/boxed/Boxed.java b/src/main/java/world/bentobox/boxed/Boxed.java index 72e4ee4..5f3e162 100644 --- a/src/main/java/world/bentobox/boxed/Boxed.java +++ b/src/main/java/world/bentobox/boxed/Boxed.java @@ -7,7 +7,6 @@ import java.util.Comparator; import java.util.Collections; import java.util.HashMap; -import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; @@ -534,7 +533,9 @@ private World regenerateSeedWorld(World seedWorld, WorldCreator creator) { return seedWorld; } try (Stream files = Files.walk(folder.toPath())) { - files.sorted(Comparator.reverseOrder()).forEach(path -> path.toFile().delete()); + for (Path path : files.sorted(Comparator.reverseOrder()).toList()) { + Files.delete(path); + } } catch (IOException e) { logError("Could not delete seed world " + folder + ": " + e.getMessage()); } diff --git a/src/main/java/world/bentobox/boxed/areas/AreaManager.java b/src/main/java/world/bentobox/boxed/areas/AreaManager.java index f326160..8de1bb7 100644 --- a/src/main/java/world/bentobox/boxed/areas/AreaManager.java +++ b/src/main/java/world/bentobox/boxed/areas/AreaManager.java @@ -39,7 +39,7 @@ public class AreaManager { private final File gridFile; private final YamlConfiguration grid; private final Map areas = new LinkedHashMap<>(); - private final Map rows = new ConcurrentHashMap<>(); + private final Map areaByRow = new ConcurrentHashMap<>(); private final Map> templates = new ConcurrentHashMap<>(); private final Set pending = ConcurrentHashMap.newKeySet(); private final Area defaultArea; @@ -55,19 +55,7 @@ public AreaManager(YamlConfiguration config, File gridFile, long defaultSeed, this.gridFile = gridFile; this.grid = YamlConfiguration.loadConfiguration(gridFile); ConfigurationSection section = config.getConfigurationSection("areas"); - List ids = new ArrayList<>(); - // The default area always exists and always comes first - ids.add(Area.DEFAULT); - if (section != null) { - for (String id : section.getKeys(false)) { - if (!VALID_ID.matcher(id).matches()) { - errorLog.accept("Area name '" + id - + "' is not valid. Use lower case letters, numbers and underscores only. Ignoring it."); - } else if (!ids.contains(id)) { - ids.add(id); - } - } - } + List ids = getIds(section, errorLog); boolean changed = false; for (String id : ids) { String path = ROWS + "." + id; @@ -79,17 +67,12 @@ public AreaManager(YamlConfiguration config, File gridFile, long defaultSeed, if (s == null) { s = new YamlConfiguration(); } - String requires = s.getString("requires"); - if (requires != null && (!ids.contains(requires) || requires.equals(id))) { - errorLog.accept("Area '" + id + "' requires area '" + requires - + "', which is not a different, known area. Ignoring the requirement."); - requires = null; - } + String requires = getRequirement(s, id, ids, errorLog); Area area = new Area(id, s.getLong("seed", defaultSeed), s.getString("biomes", "biomes.yml"), s.getString("structures", "structures.yml"), grid.getInt(path), s.getBoolean("enabled", true), requires, Math.max(0, s.getInt("unlocks-next-at", 0))); areas.put(id, area); - rows.put(area.row(), area); + areaByRow.put(area.row(), area); } defaultArea = areas.get(Area.DEFAULT); if (changed) { @@ -97,6 +80,42 @@ public AreaManager(YamlConfiguration config, File gridFile, long defaultSeed, } } + /** + * Lists the names of the areas in the config. The default area always exists and always + * comes first. + */ + private static List getIds(ConfigurationSection section, java.util.function.Consumer errorLog) { + List ids = new ArrayList<>(); + ids.add(Area.DEFAULT); + if (section == null) { + return ids; + } + for (String id : section.getKeys(false)) { + if (!VALID_ID.matcher(id).matches()) { + errorLog.accept("Area name '" + id + + "' is not valid. Use lower case letters, numbers and underscores only. Ignoring it."); + } else if (!ids.contains(id)) { + ids.add(id); + } + } + return ids; + } + + /** + * @return the area that an area requires, or null if it requires none or the one it names + * is not a different, known area + */ + private static String getRequirement(ConfigurationSection s, String id, List ids, + java.util.function.Consumer errorLog) { + String requires = s.getString("requires"); + if (requires != null && (!ids.contains(requires) || requires.equals(id))) { + errorLog.accept("Area '" + id + "' requires area '" + requires + + "', which is not a different, known area. Ignoring the requirement."); + return null; + } + return requires; + } + /** * Rows are handed out in the order 0, 1, 2... Rows of areas that have since been removed * from the config stay taken, because their boxes are still in the world. @@ -191,7 +210,7 @@ public Area getAreaForBundle(@Nullable String bundle) { */ @NonNull public Area getAreaAtRow(int row) { - Area area = rows.get(row); + Area area = areaByRow.get(row); return area == null ? defaultArea : area; } diff --git a/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java b/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java index 1b4662c..1070569 100644 --- a/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java +++ b/src/main/java/world/bentobox/boxed/commands/AdminAreasCommand.java @@ -37,6 +37,8 @@ public class AdminAreasCommand extends CompositeCommand { private static final String PREFIX = "boxed.commands.boxadmin.areas."; + + private static final String AREAS = "areas."; private static final String UNKNOWN_AREA = PREFIX + "unknown-area"; public AdminAreasCommand(CompositeCommand parent) { @@ -183,7 +185,7 @@ public boolean execute(User user, String label, List args) { long seed; try { seed = args.size() == 2 ? Long.parseLong(args.get(1)) : ThreadLocalRandom.current().nextLong(); - } catch (NumberFormatException e) { + } catch (NumberFormatException _) { user.sendMessage(PREFIX + "create.invalid-seed"); return false; } @@ -215,9 +217,9 @@ private void createArea(Boxed addon, String name, long seed) throws IOException } File areasFile = new File(folder, "areas.yml"); YamlConfiguration config = YamlConfiguration.loadConfiguration(areasFile); - config.set("areas." + name + ".seed", seed); - config.set("areas." + name + ".biomes", biomes); - config.set("areas." + name + ".structures", structures); + config.set(AREAS + name + ".seed", seed); + config.set(AREAS + name + ".biomes", biomes); + config.set(AREAS + name + ".structures", structures); config.save(areasFile); // A bundle with the same name is how players choose the area diff --git a/src/main/java/world/bentobox/boxed/generators/template/RawBiomes.java b/src/main/java/world/bentobox/boxed/generators/template/RawBiomes.java index 529e7df..e5b5304 100644 --- a/src/main/java/world/bentobox/boxed/generators/template/RawBiomes.java +++ b/src/main/java/world/bentobox/boxed/generators/template/RawBiomes.java @@ -24,8 +24,8 @@ public record RawBiomes(int minY, List palette, byte[] cells) { @Override public boolean equals(Object o) { - return o instanceof RawBiomes other && minY == other.minY && palette.equals(other.palette) - && Arrays.equals(cells, other.cells); + return o instanceof RawBiomes(int otherMinY, List otherPalette, byte[] otherCells) + && minY == otherMinY && palette.equals(otherPalette) && Arrays.equals(cells, otherCells); } @Override diff --git a/src/main/java/world/bentobox/boxed/generators/template/Template.java b/src/main/java/world/bentobox/boxed/generators/template/Template.java index 105bb7e..53b162d 100644 --- a/src/main/java/world/bentobox/boxed/generators/template/Template.java +++ b/src/main/java/world/bentobox/boxed/generators/template/Template.java @@ -163,7 +163,7 @@ public TemplateChunk getChunk(int x, int z) { private TemplateChunk load(int x, int z) { try { byte[] data = file.read(x, z); - return data == null ? null : resolve(RawChunk.decode(data)); + return data.length == 0 ? null : resolve(RawChunk.decode(data)); } catch (IOException | RuntimeException e) { errorLog.accept("Could not read template chunk " + x + " " + z + ": " + e); return null; @@ -188,7 +188,7 @@ private BlockData blockData(String string) { return blockDataCache.computeIfAbsent(string, s -> { try { return Bukkit.createBlockData(s); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException _) { errorLog.accept("Template has a block this server does not know: " + s); return Material.AIR.createBlockData(); } diff --git a/src/main/java/world/bentobox/boxed/generators/template/TemplateBuilder.java b/src/main/java/world/bentobox/boxed/generators/template/TemplateBuilder.java index a47ebeb..efa16e0 100644 --- a/src/main/java/world/bentobox/boxed/generators/template/TemplateBuilder.java +++ b/src/main/java/world/bentobox/boxed/generators/template/TemplateBuilder.java @@ -206,25 +206,7 @@ public static RawChunk toRawChunk(ChunkSnapshot snapshot, int minY, int maxY, Li int[] uniform = new int[sectionCount]; for (int section = 0; section < sectionCount; section++) { short[] blocks = new short[RawChunk.SECTION_BLOCKS]; - boolean same = true; - int i = 0; - for (int y = 0; y < 16; y++) { - for (int z = 0; z < 16; z++) { - for (int x = 0; x < 16; x++) { - BlockData data = snapshot.getBlockData(x, minY + (section << 4) + y, z); - Integer id = blockIds.get(data); - if (id == null) { - id = blockPalette.size(); - blockIds.put(data, id); - blockPalette.add(data.getAsString()); - } - blocks[i] = id.shortValue(); - same &= blocks[i] == blocks[0]; - i++; - } - } - } - if (same) { + if (fillSection(snapshot, minY + (section << 4), blocks, blockIds, blockPalette)) { uniform[section] = blocks[0]; } else { sections[section] = blocks; @@ -234,6 +216,29 @@ public static RawChunk toRawChunk(ChunkSnapshot snapshot, int minY, int maxY, Li return new RawChunk(minY, blockPalette, sections, uniform, entities, tiles); } + /** + * Fills in the palette indices of one section, adding to the palette as needed. + * @return true if every block in the section is the same + */ + private static boolean fillSection(ChunkSnapshot snapshot, int baseY, short[] blocks, + Map blockIds, List blockPalette) { + boolean same = true; + int i = 0; + for (int y = 0; y < 16; y++) { + for (int z = 0; z < 16; z++) { + for (int x = 0; x < 16; x++) { + blocks[i] = blockIds.computeIfAbsent(snapshot.getBlockData(x, baseY + y, z), data -> { + blockPalette.add(data.getAsString()); + return blockPalette.size() - 1; + }).shortValue(); + same &= blocks[i] == blocks[0]; + i++; + } + } + } + return same; + } + /** * Gets the biomes of a chunk snapshot in their stored form. Can be called from any thread. * @param snapshot snapshot that includes biomes @@ -248,14 +253,10 @@ public static RawBiomes toRawBiomes(ChunkSnapshot snapshot, int minY, int maxY) for (int y = 0; y < maxY - minY; y += 4) { for (int z = 0; z < 16; z += 4) { for (int x = 0; x < 16; x += 4) { - Biome biome = snapshot.getBiome(x, minY + y, z); - Integer id = biomeIds.get(biome); - if (id == null) { - id = palette.size(); - biomeIds.put(biome, id); - palette.add(biome.getKey().toString()); - } - cells[RawBiomes.index(x, y, z)] = id.byteValue(); + cells[RawBiomes.index(x, y, z)] = biomeIds.computeIfAbsent(snapshot.getBiome(x, minY + y, z), b -> { + palette.add(b.getKey().toString()); + return palette.size() - 1; + }).byteValue(); } } } diff --git a/src/main/java/world/bentobox/boxed/generators/template/TemplateChunk.java b/src/main/java/world/bentobox/boxed/generators/template/TemplateChunk.java index 3db07ff..dc8fdae 100644 --- a/src/main/java/world/bentobox/boxed/generators/template/TemplateChunk.java +++ b/src/main/java/world/bentobox/boxed/generators/template/TemplateChunk.java @@ -81,15 +81,14 @@ public boolean isAirSection(int y) { */ @Nullable public Integer getGroundLevel(int x, int z) { - for (int y = minY + sections.length * 16 - 1; y >= minY; y--) { - if (isAirSection(y)) { - // Skip to the bottom of the empty section - y = minY + (((y - minY) >> 4) << 4); - continue; - } - Material m = getBlockData(x, y, z).getMaterial(); - if (m.isSolid() && !Tag.LEAVES.isTagged(m) && !Tag.LOGS.isTagged(m)) { - return y; + for (int section = sections.length - 1; section >= 0; section--) { + int baseY = minY + (section << 4); + // Empty sections are skipped whole + for (int y = baseY + 15; y >= baseY && !isAirSection(baseY); y--) { + Material m = getBlockData(x, y, z).getMaterial(); + if (m.isSolid() && !Tag.LEAVES.isTagged(m) && !Tag.LOGS.isTagged(m)) { + return y; + } } } return null; diff --git a/src/main/java/world/bentobox/boxed/generators/template/TemplateFile.java b/src/main/java/world/bentobox/boxed/generators/template/TemplateFile.java index 232aa7d..98ea28b 100644 --- a/src/main/java/world/bentobox/boxed/generators/template/TemplateFile.java +++ b/src/main/java/world/bentobox/boxed/generators/template/TemplateFile.java @@ -108,16 +108,16 @@ public long getSeed() { * Reads the compressed data of a chunk. Safe to call from any thread. * @param x chunk x, from -size to size - 1 * @param z chunk z, from -size to size - 1 - * @return compressed chunk, or null if the template does not have this chunk + * @return compressed chunk, or an empty array if the template does not have this chunk * @throws IOException if the file cannot be read */ public byte[] read(int x, int z) throws IOException { if (x < -size || x >= size || z < -size || z >= size) { - return null; + return new byte[0]; } int slot = slot(size, x, z); if (lengths[slot] <= 0) { - return null; + return new byte[0]; } return readFully(lengths[slot], offsets[slot]).array(); } @@ -257,7 +257,7 @@ public synchronized void abort() { try { channel.close(); Files.deleteIfExists(temp.toPath()); - } catch (IOException e) { + } catch (IOException _) { // Nothing more can be done } } diff --git a/src/main/java/world/bentobox/boxed/listeners/BoxCleaner.java b/src/main/java/world/bentobox/boxed/listeners/BoxCleaner.java index 8920dc6..fbdd5b5 100644 --- a/src/main/java/world/bentobox/boxed/listeners/BoxCleaner.java +++ b/src/main/java/world/bentobox/boxed/listeners/BoxCleaner.java @@ -251,19 +251,8 @@ static int restore(Chunk chunk, TemplateChunk template, BoxedBlockPopulator popu int maxY = world.getMaxHeight(); for (int sectionY = minY; sectionY < maxY; sectionY += 16) { // Most of the sky is air in both, which is quick to check - if (snapshot.isSectionEmpty((sectionY - minY) >> 4) && template.isAirSection(sectionY)) { - continue; - } - for (int y = sectionY; y < sectionY + 16; y++) { - for (int z = 0; z < 16; z++) { - for (int x = 0; x < 16; x++) { - BlockData wanted = template.getBlockData(x, y, z); - if (wanted != null && !wanted.equals(snapshot.getBlockData(x, y, z))) { - chunk.getBlock(x, y, z).setBlockData(wanted, false); - changed++; - } - } - } + if (!snapshot.isSectionEmpty((sectionY - minY) >> 4) || !template.isAirSection(sectionY)) { + changed += restoreSection(chunk, snapshot, template, sectionY); } } // Chests, spawners and so on get their contents back, whether or not the block changed @@ -280,6 +269,26 @@ static int restore(Chunk chunk, TemplateChunk template, BoxedBlockPopulator popu return changed; } + /** + * Puts back every block of a 16-block-high section that differs from the template. + * @return the number of blocks that were put back + */ + private static int restoreSection(Chunk chunk, ChunkSnapshot snapshot, TemplateChunk template, int sectionY) { + int changed = 0; + for (int y = sectionY; y < sectionY + 16; y++) { + for (int z = 0; z < 16; z++) { + for (int x = 0; x < 16; x++) { + BlockData wanted = template.getBlockData(x, y, z); + if (wanted != null && !wanted.equals(snapshot.getBlockData(x, y, z))) { + chunk.getBlock(x, y, z).setBlockData(wanted, false); + changed++; + } + } + } + } + return changed; + } + /** * Ends the current job. The record of the deleted box is removed so that the position is * free, unless the box has been brought back in the meantime. diff --git a/src/test/java/world/bentobox/boxed/areas/AreaLocationStrategyTest.java b/src/test/java/world/bentobox/boxed/areas/AreaLocationStrategyTest.java index 894f0f9..51d9adb 100644 --- a/src/test/java/world/bentobox/boxed/areas/AreaLocationStrategyTest.java +++ b/src/test/java/world/bentobox/boxed/areas/AreaLocationStrategyTest.java @@ -15,6 +15,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import world.bentobox.bentobox.managers.BlueprintsManager; import world.bentobox.bentobox.managers.IslandDeletionManager; import world.bentobox.boxed.Boxed; import world.bentobox.boxed.CommonTestSetup; @@ -47,7 +48,8 @@ void setUpStrategy() throws Exception { when(addon.getSettings()).thenReturn(settings); // No blueprints, so boxes go at the island height setting when(addon.getPlugin()).thenReturn(plugin); - when(plugin.getBlueprintsManager()).thenReturn(mock(world.bentobox.bentobox.managers.BlueprintsManager.class)); + BlueprintsManager blueprints = mock(BlueprintsManager.class); + when(plugin.getBlueprintsManager()).thenReturn(blueprints); AbstractBoxedChunkGenerator gen = mock(AbstractBoxedChunkGenerator.class); // 20 chunks half-width = boxes 640 blocks apart when(gen.getSize()).thenReturn(20); diff --git a/src/test/java/world/bentobox/boxed/areas/BoxHeightTest.java b/src/test/java/world/bentobox/boxed/areas/BoxHeightTest.java index 1e7fc0e..6c1e1b1 100644 --- a/src/test/java/world/bentobox/boxed/areas/BoxHeightTest.java +++ b/src/test/java/world/bentobox/boxed/areas/BoxHeightTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.File; @@ -138,7 +139,7 @@ void testSpawnSignIsFound() { void testCentrePutsTheSignOnTheGround() { assertEquals(4, new BoxHeight(addon).get(ice)); // The sign is one block north of the bedrock, which is in the chunk north of the centre - org.mockito.Mockito.verify(template).getChunk(0, -1); + verify(template).getChunk(0, -1); } @Test diff --git a/src/test/java/world/bentobox/boxed/generators/template/TemplateFileTest.java b/src/test/java/world/bentobox/boxed/generators/template/TemplateFileTest.java index af54024..ff40ec9 100644 --- a/src/test/java/world/bentobox/boxed/generators/template/TemplateFileTest.java +++ b/src/test/java/world/bentobox/boxed/generators/template/TemplateFileTest.java @@ -73,10 +73,10 @@ void testFileRoundTrip() throws IOException { assertArrayEquals(a, template.read(-2, -2)); assertArrayEquals(b, template.read(1, 1)); // Not written - assertNull(template.read(0, 0)); + assertEquals(0, template.read(0, 0).length); // Outside the template - assertNull(template.read(2, 0)); - assertNull(template.read(0, -3)); + assertEquals(0, template.read(2, 0).length); + assertEquals(0, template.read(0, -3).length); assertEquals(-1, template.slot(2, 0)); RawBiomes[] biomes = template.readBiomes();