Fix up some SpotBugs suggestions (#1911)

This is a manual go-through of some bugs SpotBugs pointed out.
This commit is contained in:
Camotoy 2021-02-16 16:25:46 -05:00 committed by GitHub
parent 1f1d94aa81
commit e0bd5a62a7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 66 additions and 59 deletions

View file

@ -55,7 +55,7 @@ public class LoopbackUtil {
if (!result.contains("minecraftuwp")) { if (!result.contains("minecraftuwp")) {
Files.write(Paths.get(System.getenv("temp") + "/loopback_minecraft.bat"), loopbackCommand.getBytes(), new OpenOption[0]); 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")); geyserLogger.info(ChatColor.AQUA + LanguageUtils.getLocaleStringLog("geyser.bootstrap.loopback.added"));
} }

View file

@ -52,7 +52,7 @@ public class IGeyserMain {
* @return The formatted message * @return The formatted message
*/ */
private String createMessage() { private String createMessage() {
String message = ""; StringBuilder message = new StringBuilder();
InputStream helpStream = IGeyserMain.class.getClassLoader().getResourceAsStream("languages/run-help/" + Locale.getDefault().toString() + ".txt"); InputStream helpStream = IGeyserMain.class.getClassLoader().getResourceAsStream("languages/run-help/" + Locale.getDefault().toString() + ".txt");
@ -68,10 +68,10 @@ public class IGeyserMain {
line = line.replace("${plugin_type}", this.getPluginType()); line = line.replace("${plugin_type}", this.getPluginType());
line = line.replace("${plugin_folder}", this.getPluginFolder()); line = line.replace("${plugin_folder}", this.getPluginFolder());
message += line + "\n"; message.append(line).append("\n");
} }
return message; return message.toString();
} }
/** /**

View file

@ -46,7 +46,7 @@ public class WitherEntity extends MonsterEntity {
if (entityMetadata.getId() >= 15 && entityMetadata.getId() <= 17) { if (entityMetadata.getId() >= 15 && entityMetadata.getId() <= 17) {
Entity entity = session.getEntityCache().getEntityByJavaId((int) entityMetadata.getValue()); 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(); entity = session.getPlayerEntity();
} }
@ -62,7 +62,7 @@ public class WitherEntity extends MonsterEntity {
} else if (entityMetadata.getId() == 17) { } else if (entityMetadata.getId() == 17) {
metadata.put(EntityData.WITHER_TARGET_3, targetID); metadata.put(EntityData.WITHER_TARGET_3, targetID);
} else if (entityMetadata.getId() == 18) { } 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) // Show the shield for the first few seconds of spawning (like Java)
if ((int) entityMetadata.getValue() >= 165) { if ((int) entityMetadata.getValue() >= 165) {

View file

@ -38,7 +38,7 @@ import java.io.InputStream;
*/ */
public class EntityIdentifierRegistry { public class EntityIdentifierRegistry {
public static NbtMap ENTITY_IDENTIFIERS; public static final NbtMap ENTITY_IDENTIFIERS;
private EntityIdentifierRegistry() { private EntityIdentifierRegistry() {
} }

View file

@ -303,9 +303,8 @@ public abstract class ItemTranslator {
CompoundTag javaTag = new CompoundTag(name); CompoundTag javaTag = new CompoundTag(name);
Map<String, Tag> javaValue = javaTag.getValue(); Map<String, Tag> javaValue = javaTag.getValue();
if (tag != null && !tag.isEmpty()) { if (tag != null && !tag.isEmpty()) {
for (String str : tag.keySet()) { for (Map.Entry<String, Object> entry : tag.entrySet()) {
Object bedrockTag = tag.get(str); Tag translatedTag = translateToJavaNBT(entry.getKey(), entry.getValue());
Tag translatedTag = translateToJavaNBT(str, bedrockTag);
if (translatedTag == null) if (translatedTag == null)
continue; continue;

View file

@ -44,7 +44,7 @@ public class JavaUnloadChunkTranslator extends PacketTranslator<ServerUnloadChun
Iterator<Vector3i> iterator = session.getSkullCache().keySet().iterator(); Iterator<Vector3i> iterator = session.getSkullCache().keySet().iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
Vector3i position = iterator.next(); 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); session.getSkullCache().get(position).despawnEntity(session);
iterator.remove(); iterator.remove();
} }

View file

@ -90,21 +90,22 @@ public class FileUtils {
*/ */
public static File fileOrCopiedFromResource(File file, String name, Function<String, String> format) throws IOException { public static File fileOrCopiedFromResource(File file, String name, Function<String, String> format) throws IOException {
if (!file.exists()) { if (!file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.createNewFile(); file.createNewFile();
FileOutputStream fos = new FileOutputStream(file); try (FileOutputStream fos = new FileOutputStream(file)) {
InputStream input = GeyserConnector.class.getResourceAsStream("/" + name); // resources need leading "/" prefix 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.flush();
fos.write(c); }
} }
fos.flush();
input.close();
fos.close();
} }
return file; return file;
@ -122,14 +123,13 @@ public class FileUtils {
file.createNewFile(); 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.flush();
fos.write(c);
} }
fos.flush();
fos.close();
} }
/** /**
@ -232,9 +232,10 @@ public class FileUtils {
try { try {
int size = stream.available(); int size = stream.available();
byte[] bytes = new byte[size]; byte[] bytes = new byte[size];
BufferedInputStream buf = new BufferedInputStream(stream); try (BufferedInputStream buf = new BufferedInputStream(stream)) {
buf.read(bytes, 0, bytes.length); //noinspection ResultOfMethodCallIgnored
buf.close(); buf.read(bytes, 0, bytes.length);
}
return bytes; return bytes;
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Error while trying to read input stream!"); throw new RuntimeException("Error while trying to read input stream!");

View file

@ -67,8 +67,8 @@ public class LanguageUtils {
// Load the locale // Load the locale
if (localeStream != null) { if (localeStream != null) {
Properties localeProp = new Properties(); Properties localeProp = new Properties();
try { try (InputStreamReader reader = new InputStreamReader(localeStream, StandardCharsets.UTF_8)) {
localeProp.load(new InputStreamReader(localeStream, StandardCharsets.UTF_8)); localeProp.load(reader);
} catch (Exception e) { } catch (Exception e) {
throw new AssertionError(getLocaleStringLog("geyser.language.load_failed", locale), e); throw new AssertionError(getLocaleStringLog("geyser.language.load_failed", locale), e);
} }

View file

@ -236,24 +236,23 @@ public class LocaleUtils {
WebUtils.downloadFile(clientJarInfo.getUrl(), tmpFilePath.toString()); WebUtils.downloadFile(clientJarInfo.getUrl(), tmpFilePath.toString());
// Load in the JAR as a zip and extract the file // Load in the JAR as a zip and extract the file
ZipFile localeJar = new ZipFile(tmpFilePath.toString()); try (ZipFile localeJar = new ZipFile(tmpFilePath.toString())) {
InputStream fileStream = localeJar.getInputStream(localeJar.getEntry("assets/minecraft/lang/en_us.json")); try (InputStream fileStream = localeJar.getInputStream(localeJar.getEntry("assets/minecraft/lang/en_us.json"))) {
FileOutputStream outStream = new FileOutputStream(localeFile); try (FileOutputStream outStream = new FileOutputStream(localeFile)) {
// Write the file to the locale dir // Write the file to the locale dir
byte[] buf = new byte[fileStream.available()]; byte[] buf = new byte[fileStream.available()];
int length; int length;
while ((length = fileStream.read(buf)) != -1) { while ((length = fileStream.read(buf)) != -1) {
outStream.write(buf, 0, length); outStream.write(buf, 0, length);
}
// Flush all changes to disk and cleanup
outStream.flush();
}
}
} }
// Flush all changes to disk and cleanup
outStream.flush();
outStream.close();
fileStream.close();
localeJar.close();
// Store the latest jar hash // Store the latest jar hash
FileUtils.writeFile(GeyserConnector.getInstance().getBootstrap().getConfigFolder().resolve("locales/en_us.hash").toString(), clientJarInfo.getSha1().toCharArray()); FileUtils.writeFile(GeyserConnector.getInstance().getBootstrap().getConfigFolder().resolve("locales/en_us.hash").toString(), clientJarInfo.getSha1().toCharArray());

View file

@ -30,6 +30,8 @@ import org.geysermc.connector.GeyserConnector;
import java.io.File; import java.io.File;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
/** /**
@ -70,10 +72,12 @@ public class ResourcePack {
pack.sha256 = FileUtils.calculateSHA256(file); pack.sha256 = FileUtils.calculateSHA256(file);
Stream<? extends ZipEntry> stream = null;
try { try {
ZipFile zip = new ZipFile(file); ZipFile zip = new ZipFile(file);
zip.stream().forEach((x) -> { stream = zip.stream();
stream.forEach((x) -> {
if (x.getName().contains("manifest.json")) { if (x.getName().contains("manifest.json")) {
try { try {
ResourcePackManifest manifest = FileUtils.loadJson(zip.getInputStream(x), ResourcePackManifest.class); ResourcePackManifest manifest = FileUtils.loadJson(zip.getInputStream(x), ResourcePackManifest.class);
@ -94,6 +98,10 @@ public class ResourcePack {
} catch (Exception e) { } catch (Exception e) {
GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog("geyser.resource_pack.broken", file.getName())); GeyserConnector.getInstance().getLogger().error(LanguageUtils.getLocaleStringLog("geyser.resource_pack.broken", file.getName()));
e.printStackTrace(); e.printStackTrace();
} finally {
if (stream != null) {
stream.close();
}
} }
} }
} }

View file

@ -147,7 +147,7 @@ public class SettingsUtils {
} }
if (Boolean.class.equals(gamerule.getType())) { 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)) { if (value != session.getConnector().getWorldManager().getGameRuleBool(session, gamerule)) {
session.getConnector().getWorldManager().setGameRule(session, gamerule.getJavaID(), value); session.getConnector().getWorldManager().setGameRule(session, gamerule.getJavaID(), value);
} }

View file

@ -112,7 +112,7 @@ public class WebUtils {
*/ */
private static String connectionToString(HttpURLConnection con) throws IOException { private static String connectionToString(HttpURLConnection con) throws IOException {
// Send the request (we dont use this but its required for getErrorStream() to work) // 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 // Read the error message if there is one if not just read normally
InputStream inputStream = con.getErrorStream(); InputStream inputStream = con.getErrorStream();
@ -120,18 +120,18 @@ public class WebUtils {
inputStream = con.getInputStream(); inputStream = con.getInputStream();
} }
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder content = new StringBuilder();
String inputLine; try (BufferedReader in = new BufferedReader(new InputStreamReader(inputStream))) {
StringBuffer content = new StringBuffer(); String inputLine;
while ((inputLine = in.readLine()) != null) { while ((inputLine = in.readLine()) != null) {
content.append(inputLine); content.append(inputLine);
content.append("\n"); content.append("\n");
}
con.disconnect();
} }
in.close();
con.disconnect();
return content.toString(); return content.toString();
} }
} }