From e0bd5a62a7897f0f3c441efd8ce8b0ee8ca36361 Mon Sep 17 00:00:00 2001 From: Camotoy <20743703+Camotoy@users.noreply.github.com> Date: Tue, 16 Feb 2021 16:25:46 -0500 Subject: [PATCH] Fix up some SpotBugs suggestions (#1911) This is a manual go-through of some bugs SpotBugs pointed out. --- .../platform/standalone/LoopbackUtil.java | 2 +- .../connector/common/main/IGeyserMain.java | 6 +-- .../entity/living/monster/WitherEntity.java | 4 +- .../translators/EntityIdentifierRegistry.java | 2 +- .../translators/item/ItemTranslator.java | 5 +-- .../java/world/JavaUnloadChunkTranslator.java | 2 +- .../geysermc/connector/utils/FileUtils.java | 39 ++++++++++--------- .../connector/utils/LanguageUtils.java | 4 +- .../geysermc/connector/utils/LocaleUtils.java | 31 +++++++-------- .../connector/utils/ResourcePack.java | 10 ++++- .../connector/utils/SettingsUtils.java | 2 +- .../geysermc/connector/utils/WebUtils.java | 20 +++++----- 12 files changed, 67 insertions(+), 60 deletions(-) diff --git a/bootstrap/standalone/src/main/java/org/geysermc/platform/standalone/LoopbackUtil.java b/bootstrap/standalone/src/main/java/org/geysermc/platform/standalone/LoopbackUtil.java index 9c10234f3e7..7eeba84bd7c 100644 --- a/bootstrap/standalone/src/main/java/org/geysermc/platform/standalone/LoopbackUtil.java +++ b/bootstrap/standalone/src/main/java/org/geysermc/platform/standalone/LoopbackUtil.java @@ -55,7 +55,7 @@ public static void checkLoopback(GeyserStandaloneLogger geyserLogger) { if (!result.contains("minecraftuwp")) { Files.write(Paths.get(System.getenv("temp") + "/loopback_minecraft.bat"), loopbackCommand.getBytes(), new OpenOption[0]); - process = Runtime.getRuntime().exec(startScript); + Runtime.getRuntime().exec(startScript); geyserLogger.info(ChatColor.AQUA + LanguageUtils.getLocaleStringLog("geyser.bootstrap.loopback.added")); } diff --git a/connector/src/main/java/org/geysermc/connector/common/main/IGeyserMain.java b/connector/src/main/java/org/geysermc/connector/common/main/IGeyserMain.java index 3f674d7faee..f91da11b590 100644 --- a/connector/src/main/java/org/geysermc/connector/common/main/IGeyserMain.java +++ b/connector/src/main/java/org/geysermc/connector/common/main/IGeyserMain.java @@ -52,7 +52,7 @@ public void displayMessage() { * @return The formatted message */ private String createMessage() { - String message = ""; + StringBuilder message = new StringBuilder(); InputStream helpStream = IGeyserMain.class.getClassLoader().getResourceAsStream("languages/run-help/" + Locale.getDefault().toString() + ".txt"); @@ -68,10 +68,10 @@ private String createMessage() { line = line.replace("${plugin_type}", this.getPluginType()); line = line.replace("${plugin_folder}", this.getPluginFolder()); - message += line + "\n"; + message.append(line).append("\n"); } - return message; + return message.toString(); } /** diff --git a/connector/src/main/java/org/geysermc/connector/entity/living/monster/WitherEntity.java b/connector/src/main/java/org/geysermc/connector/entity/living/monster/WitherEntity.java index 8dcce6a7f23..e024b4e55a8 100644 --- a/connector/src/main/java/org/geysermc/connector/entity/living/monster/WitherEntity.java +++ b/connector/src/main/java/org/geysermc/connector/entity/living/monster/WitherEntity.java @@ -46,7 +46,7 @@ public void updateBedrockMetadata(EntityMetadata entityMetadata, GeyserSession s if (entityMetadata.getId() >= 15 && entityMetadata.getId() <= 17) { Entity entity = session.getEntityCache().getEntityByJavaId((int) entityMetadata.getValue()); - if (entity == null && session.getPlayerEntity().getEntityId() == (Integer) entityMetadata.getValue()) { + if (entity == null && session.getPlayerEntity().getEntityId() == (int) entityMetadata.getValue()) { entity = session.getPlayerEntity(); } @@ -62,7 +62,7 @@ public void updateBedrockMetadata(EntityMetadata entityMetadata, GeyserSession s } else if (entityMetadata.getId() == 17) { metadata.put(EntityData.WITHER_TARGET_3, targetID); } else if (entityMetadata.getId() == 18) { - metadata.put(EntityData.WITHER_INVULNERABLE_TICKS, (int) entityMetadata.getValue()); + metadata.put(EntityData.WITHER_INVULNERABLE_TICKS, entityMetadata.getValue()); // Show the shield for the first few seconds of spawning (like Java) if ((int) entityMetadata.getValue() >= 165) { diff --git a/connector/src/main/java/org/geysermc/connector/network/translators/EntityIdentifierRegistry.java b/connector/src/main/java/org/geysermc/connector/network/translators/EntityIdentifierRegistry.java index f4c0f9abc13..fb6d5b93dec 100644 --- a/connector/src/main/java/org/geysermc/connector/network/translators/EntityIdentifierRegistry.java +++ b/connector/src/main/java/org/geysermc/connector/network/translators/EntityIdentifierRegistry.java @@ -38,7 +38,7 @@ */ public class EntityIdentifierRegistry { - public static NbtMap ENTITY_IDENTIFIERS; + public static final NbtMap ENTITY_IDENTIFIERS; private EntityIdentifierRegistry() { } diff --git a/connector/src/main/java/org/geysermc/connector/network/translators/item/ItemTranslator.java b/connector/src/main/java/org/geysermc/connector/network/translators/item/ItemTranslator.java index 90acb781a0e..f63df2f7eb6 100644 --- a/connector/src/main/java/org/geysermc/connector/network/translators/item/ItemTranslator.java +++ b/connector/src/main/java/org/geysermc/connector/network/translators/item/ItemTranslator.java @@ -303,9 +303,8 @@ public CompoundTag translateToJavaNBT(String name, NbtMap tag) { CompoundTag javaTag = new CompoundTag(name); Map javaValue = javaTag.getValue(); if (tag != null && !tag.isEmpty()) { - for (String str : tag.keySet()) { - Object bedrockTag = tag.get(str); - Tag translatedTag = translateToJavaNBT(str, bedrockTag); + for (Map.Entry entry : tag.entrySet()) { + Tag translatedTag = translateToJavaNBT(entry.getKey(), entry.getValue()); if (translatedTag == null) continue; diff --git a/connector/src/main/java/org/geysermc/connector/network/translators/java/world/JavaUnloadChunkTranslator.java b/connector/src/main/java/org/geysermc/connector/network/translators/java/world/JavaUnloadChunkTranslator.java index b768a207401..4e0f03bd110 100644 --- a/connector/src/main/java/org/geysermc/connector/network/translators/java/world/JavaUnloadChunkTranslator.java +++ b/connector/src/main/java/org/geysermc/connector/network/translators/java/world/JavaUnloadChunkTranslator.java @@ -44,7 +44,7 @@ public void translate(ServerUnloadChunkPacket packet, GeyserSession session) { Iterator iterator = session.getSkullCache().keySet().iterator(); while (iterator.hasNext()) { Vector3i position = iterator.next(); - if (Math.floor(position.getX() / 16) == packet.getX() && Math.floor(position.getZ() / 16) == packet.getZ()) { + if ((position.getX() >> 4) == packet.getX() && (position.getZ() >> 4) == packet.getZ()) { session.getSkullCache().get(position).despawnEntity(session); iterator.remove(); } diff --git a/connector/src/main/java/org/geysermc/connector/utils/FileUtils.java b/connector/src/main/java/org/geysermc/connector/utils/FileUtils.java index d1dd6fd7845..a96d29da24a 100644 --- a/connector/src/main/java/org/geysermc/connector/utils/FileUtils.java +++ b/connector/src/main/java/org/geysermc/connector/utils/FileUtils.java @@ -90,21 +90,22 @@ public static File fileOrCopiedFromResource(String name, Function format) throws IOException { if (!file.exists()) { + //noinspection ResultOfMethodCallIgnored file.createNewFile(); - FileOutputStream fos = new FileOutputStream(file); - InputStream input = GeyserConnector.class.getResourceAsStream("/" + name); // resources need leading "/" prefix + try (FileOutputStream fos = new FileOutputStream(file)) { + try (InputStream input = GeyserConnector.class.getResourceAsStream("/" + name)) { // resources need leading "/" prefix + byte[] bytes = new byte[input.available()]; - byte[] bytes = new byte[input.available()]; + //noinspection ResultOfMethodCallIgnored + input.read(bytes); - input.read(bytes); + for(char c : format.apply(new String(bytes)).toCharArray()) { + fos.write(c); + } - for(char c : format.apply(new String(bytes)).toCharArray()) { - fos.write(c); + fos.flush(); + } } - - fos.flush(); - input.close(); - fos.close(); } return file; @@ -122,14 +123,13 @@ public static void writeFile(File file, char[] data) throws IOException { file.createNewFile(); } - FileOutputStream fos = new FileOutputStream(file); + try (FileOutputStream fos = new FileOutputStream(file)) { + for (char c : data) { + fos.write(c); + } - for (char c : data) { - fos.write(c); + fos.flush(); } - - fos.flush(); - fos.close(); } /** @@ -232,9 +232,10 @@ public static byte[] readAllBytes(InputStream stream) { try { int size = stream.available(); byte[] bytes = new byte[size]; - BufferedInputStream buf = new BufferedInputStream(stream); - buf.read(bytes, 0, bytes.length); - buf.close(); + try (BufferedInputStream buf = new BufferedInputStream(stream)) { + //noinspection ResultOfMethodCallIgnored + buf.read(bytes, 0, bytes.length); + } return bytes; } catch (IOException e) { throw new RuntimeException("Error while trying to read input stream!"); diff --git a/connector/src/main/java/org/geysermc/connector/utils/LanguageUtils.java b/connector/src/main/java/org/geysermc/connector/utils/LanguageUtils.java index 1a1f758d69d..5284bbcff17 100644 --- a/connector/src/main/java/org/geysermc/connector/utils/LanguageUtils.java +++ b/connector/src/main/java/org/geysermc/connector/utils/LanguageUtils.java @@ -67,8 +67,8 @@ public static void loadGeyserLocale(String locale) { // Load the locale if (localeStream != null) { Properties localeProp = new Properties(); - try { - localeProp.load(new InputStreamReader(localeStream, StandardCharsets.UTF_8)); + try (InputStreamReader reader = new InputStreamReader(localeStream, StandardCharsets.UTF_8)) { + localeProp.load(reader); } catch (Exception e) { throw new AssertionError(getLocaleStringLog("geyser.language.load_failed", locale), e); } diff --git a/connector/src/main/java/org/geysermc/connector/utils/LocaleUtils.java b/connector/src/main/java/org/geysermc/connector/utils/LocaleUtils.java index 15a52cf7f9d..dea05cca06b 100644 --- a/connector/src/main/java/org/geysermc/connector/utils/LocaleUtils.java +++ b/connector/src/main/java/org/geysermc/connector/utils/LocaleUtils.java @@ -236,23 +236,22 @@ private static void downloadEN_US(File localeFile) { WebUtils.downloadFile(clientJarInfo.getUrl(), tmpFilePath.toString()); // Load in the JAR as a zip and extract the file - ZipFile localeJar = new ZipFile(tmpFilePath.toString()); - InputStream fileStream = localeJar.getInputStream(localeJar.getEntry("assets/minecraft/lang/en_us.json")); - FileOutputStream outStream = new FileOutputStream(localeFile); - - // Write the file to the locale dir - byte[] buf = new byte[fileStream.available()]; - int length; - while ((length = fileStream.read(buf)) != -1) { - outStream.write(buf, 0, length); - } - - // Flush all changes to disk and cleanup - outStream.flush(); - outStream.close(); + try (ZipFile localeJar = new ZipFile(tmpFilePath.toString())) { + try (InputStream fileStream = localeJar.getInputStream(localeJar.getEntry("assets/minecraft/lang/en_us.json"))) { + try (FileOutputStream outStream = new FileOutputStream(localeFile)) { + + // Write the file to the locale dir + byte[] buf = new byte[fileStream.available()]; + int length; + while ((length = fileStream.read(buf)) != -1) { + outStream.write(buf, 0, length); + } - fileStream.close(); - localeJar.close(); + // Flush all changes to disk and cleanup + outStream.flush(); + } + } + } // Store the latest jar hash FileUtils.writeFile(GeyserConnector.getInstance().getBootstrap().getConfigFolder().resolve("locales/en_us.hash").toString(), clientJarInfo.getSha1().toCharArray()); diff --git a/connector/src/main/java/org/geysermc/connector/utils/ResourcePack.java b/connector/src/main/java/org/geysermc/connector/utils/ResourcePack.java index bcb1ffd503c..91d1b782e66 100644 --- a/connector/src/main/java/org/geysermc/connector/utils/ResourcePack.java +++ b/connector/src/main/java/org/geysermc/connector/utils/ResourcePack.java @@ -30,6 +30,8 @@ import java.io.File; import java.util.HashMap; import java.util.Map; +import java.util.stream.Stream; +import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** @@ -70,10 +72,12 @@ public static void loadPacks() { pack.sha256 = FileUtils.calculateSHA256(file); + Stream stream = null; try { ZipFile zip = new ZipFile(file); - zip.stream().forEach((x) -> { + stream = zip.stream(); + stream.forEach((x) -> { if (x.getName().contains("manifest.json")) { try { ResourcePackManifest manifest = FileUtils.loadJson(zip.getInputStream(x), ResourcePackManifest.class); @@ -94,6 +98,10 @@ public static void loadPacks() { } catch (Exception e) { GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog("geyser.resource_pack.broken", file.getName())); e.printStackTrace(); + } finally { + if (stream != null) { + stream.close(); + } } } } diff --git a/connector/src/main/java/org/geysermc/connector/utils/SettingsUtils.java b/connector/src/main/java/org/geysermc/connector/utils/SettingsUtils.java index 77afda53d1d..c01378d0012 100644 --- a/connector/src/main/java/org/geysermc/connector/utils/SettingsUtils.java +++ b/connector/src/main/java/org/geysermc/connector/utils/SettingsUtils.java @@ -147,7 +147,7 @@ public static boolean handleSettingsForm(GeyserSession session, String response) } if (Boolean.class.equals(gamerule.getType())) { - Boolean value = settingsResponse.getToggleResponses().get(offset).booleanValue(); + boolean value = settingsResponse.getToggleResponses().get(offset); if (value != session.getConnector().getWorldManager().getGameRuleBool(session, gamerule)) { session.getConnector().getWorldManager().setGameRule(session, gamerule.getJavaID(), value); } diff --git a/connector/src/main/java/org/geysermc/connector/utils/WebUtils.java b/connector/src/main/java/org/geysermc/connector/utils/WebUtils.java index 874fb062021..2d69c9adfa0 100644 --- a/connector/src/main/java/org/geysermc/connector/utils/WebUtils.java +++ b/connector/src/main/java/org/geysermc/connector/utils/WebUtils.java @@ -112,7 +112,7 @@ public static String post(String reqURL, String postContent) throws IOException */ private static String connectionToString(HttpURLConnection con) throws IOException { // Send the request (we dont use this but its required for getErrorStream() to work) - int code = con.getResponseCode(); + con.getResponseCode(); // Read the error message if there is one if not just read normally InputStream inputStream = con.getErrorStream(); @@ -120,17 +120,17 @@ private static String connectionToString(HttpURLConnection con) throws IOExcepti inputStream = con.getInputStream(); } - BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); - String inputLine; - StringBuffer content = new StringBuffer(); + StringBuilder content = new StringBuilder(); + try (BufferedReader in = new BufferedReader(new InputStreamReader(inputStream))) { + String inputLine; - while ((inputLine = in.readLine()) != null) { - content.append(inputLine); - content.append("\n"); - } + while ((inputLine = in.readLine()) != null) { + content.append(inputLine); + content.append("\n"); + } - in.close(); - con.disconnect(); + con.disconnect(); + } return content.toString(); }