From 2534c2c27ad41ac0f937a4230b6c7deea148c415 Mon Sep 17 00:00:00 2001 From: klaxnek Date: Sat, 10 Aug 2019 12:15:17 +0200 Subject: [PATCH] Fixes some SonarQube detected bugs: 1. Use try-with-resources in AutoCloseable objects 2. Use the "equals" method if value comparison was intended. 3. Fixed getting the cheapest mana card in getCheapestPermanentAI. --- .../main/java/forge/ai/ComputerUtilCard.java | 2 +- .../src/main/java/forge/card/ColorSet.java | 2 +- .../item/generation/BoosterGenerator.java | 2 +- .../src/main/java/forge/util/FileUtil.java | 33 ++++--------- .../src/main/java/forge/game/GameFormat.java | 2 +- .../ability/effects/ChangeZoneEffect.java | 4 +- .../src/main/java/forge/gui/ImportDialog.java | 19 ++------ .../forge/card/CardReaderExperiments.java | 4 +- .../main/java/forge/card/CardScriptInfo.java | 4 +- .../java/forge/deck/io/CardThemedLDAIO.java | 47 +++++-------------- .../forge/deck/io/CardThemedMatrixIO.java | 22 ++------- .../forge/download/GuiDownloadZipService.java | 2 +- .../main/java/forge/error/BugReporter.java | 7 +-- .../main/java/forge/gauntlet/GauntletIO.java | 26 +++------- .../main/java/forge/quest/io/QuestDataIO.java | 23 +++++---- .../java/forge/tournament/TournamentIO.java | 23 ++------- .../src/main/java/forge/util/HttpUtil.java | 21 ++------- 17 files changed, 67 insertions(+), 176 deletions(-) diff --git a/forge-ai/src/main/java/forge/ai/ComputerUtilCard.java b/forge-ai/src/main/java/forge/ai/ComputerUtilCard.java index 858ceb8fb22..1e7069df2e2 100644 --- a/forge-ai/src/main/java/forge/ai/ComputerUtilCard.java +++ b/forge-ai/src/main/java/forge/ai/ComputerUtilCard.java @@ -228,7 +228,7 @@ public class ComputerUtilCard { Card cheapest = null; for (Card c : all) { - if (cheapest == null || cheapest.getManaCost().getCMC() <= cheapest.getManaCost().getCMC()) { + if (cheapest == null || c.getManaCost().getCMC() <= cheapest.getManaCost().getCMC()) { cheapest = c; } } diff --git a/forge-core/src/main/java/forge/card/ColorSet.java b/forge-core/src/main/java/forge/card/ColorSet.java index 0a1cc08ba1f..c3b34c5cdd8 100644 --- a/forge-core/src/main/java/forge/card/ColorSet.java +++ b/forge-core/src/main/java/forge/card/ColorSet.java @@ -283,7 +283,7 @@ public final class ColorSet implements Comparable, Iterable, Ser return "n/a"; } final String toReturn = MagicColor.toLongString(myColor); - if (toReturn == MagicColor.Constant.COLORLESS && myColor != 0) { + if (toReturn.equals(MagicColor.Constant.COLORLESS) && myColor != 0) { return "multi"; } return toReturn; diff --git a/forge-core/src/main/java/forge/item/generation/BoosterGenerator.java b/forge-core/src/main/java/forge/item/generation/BoosterGenerator.java index 2b991577846..896e8d6de6b 100644 --- a/forge-core/src/main/java/forge/item/generation/BoosterGenerator.java +++ b/forge-core/src/main/java/forge/item/generation/BoosterGenerator.java @@ -306,7 +306,7 @@ public class BoosterGenerator { // 1 out of ~30 normal and mythic rares are foil, // match that. // If not special card, make it always foil. - if ((MyRandom.getRandom().nextInt(30) == 1) || (foilSlot != BoosterSlots.SPECIAL)) { + if ((MyRandom.getRandom().nextInt(30) == 1) || (!foilSlot.equals(BoosterSlots.SPECIAL))) { foilCardGeneratedAndHeld.add(generateFoilCard(ps)); } else { // Otherwise it's not foil (even though this is the diff --git a/forge-core/src/main/java/forge/util/FileUtil.java b/forge-core/src/main/java/forge/util/FileUtil.java index 44178ff5c8c..32eda08b4a2 100644 --- a/forge-core/src/main/java/forge/util/FileUtil.java +++ b/forge-core/src/main/java/forge/util/FileUtil.java @@ -106,11 +106,8 @@ public final class FileUtil { File source = new File(sourceFilename); if (!source.exists()) { return; } //if source doesn't exist, nothing to copy - InputStream is = null; - OutputStream os = null; - try { - is = new FileInputStream(source); - os = new FileOutputStream(new File(destFilename)); + try (InputStream is = new FileInputStream(source); + OutputStream os = new FileOutputStream(new File(destFilename))){ byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { @@ -120,15 +117,6 @@ public final class FileUtil { catch (Exception e) { e.printStackTrace(); } - finally { - try { - is.close(); - os.close(); - } - catch (IOException e) { - e.printStackTrace(); - } - } } public static void writeFile(String filename, String text) { @@ -136,10 +124,8 @@ public final class FileUtil { } public static void writeFile(File file, String text) { - try { - PrintWriter p = new PrintWriter(file); + try (PrintWriter p = new PrintWriter(file)) { p.print(text); - p.close(); } catch (final Exception ex) { throw new RuntimeException("FileUtil : writeFile() error, problem writing file - " + file + " : " + ex); } @@ -174,12 +160,10 @@ public final class FileUtil { * a {@link java.util.List} object. */ public static void writeFile(File file, Collection data) { - try { - PrintWriter p = new PrintWriter(file); + try (PrintWriter p = new PrintWriter(file)) { for (Object o : data) { p.println(o); } - p.close(); } catch (final Exception ex) { throw new RuntimeException("FileUtil : writeFile() error, problem writing file - " + file + " : " + ex); } @@ -291,10 +275,11 @@ public final class FileUtil { ThreadUtil.executeWithTimeout(new Callable() { @Override public Void call() throws Exception { - BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); - String line; - while ((line = in.readLine()) != null) { - lines.add(line); + try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()))) { + String line; + while ((line = in.readLine()) != null) { + lines.add(line); + } } return null; } diff --git a/forge-game/src/main/java/forge/game/GameFormat.java b/forge-game/src/main/java/forge/game/GameFormat.java index 64358578f7f..27122eb2da9 100644 --- a/forge-game/src/main/java/forge/game/GameFormat.java +++ b/forge-game/src/main/java/forge/game/GameFormat.java @@ -370,7 +370,7 @@ public class GameFormat implements Comparable { rarities = Lists.newArrayList(); for (String s: Arrays.asList(strCars.split(", "))) { cr = CardRarity.smartValueOf(s); - if (cr.name() != "Unknown") { + if (!cr.name().equals("Unknown")) { rarities.add(cr); } } diff --git a/forge-game/src/main/java/forge/game/ability/effects/ChangeZoneEffect.java b/forge-game/src/main/java/forge/game/ability/effects/ChangeZoneEffect.java index 3a053f5937a..58220d302fb 100644 --- a/forge-game/src/main/java/forge/game/ability/effects/ChangeZoneEffect.java +++ b/forge-game/src/main/java/forge/game/ability/effects/ChangeZoneEffect.java @@ -180,7 +180,7 @@ public class ChangeZoneEffect extends SpellAbilityEffect { sb.append(num).append(" of those ").append(type).append(" card(s)"); } else { sb.append(destination.equals("Exile") ? " exiles " : " puts "); - if (type == "Card") { + if (type.equals("Card")) { sb.append(num); } else { sb.append(num).append(" ").append(type); @@ -208,7 +208,7 @@ public class ChangeZoneEffect extends SpellAbilityEffect { } sb.append(" of ").append(fetchPlayer); - if (fetchPlayer != "their") { + if (!fetchPlayer.equals("their")) { sb.append("'s"); } sb.append(" library"); diff --git a/forge-gui-desktop/src/main/java/forge/gui/ImportDialog.java b/forge-gui-desktop/src/main/java/forge/gui/ImportDialog.java index 80c46b6730b..1ff99429027 100644 --- a/forge-gui-desktop/src/main/java/forge/gui/ImportDialog.java +++ b/forge-gui-desktop/src/main/java/forge/gui/ImportDialog.java @@ -1011,21 +1011,12 @@ public class ImportDialog { destFile.createNewFile(); } - FileInputStream srcStream = null; - FileChannel src = null; - FileOutputStream destStream = null; - FileChannel dest = null; - try { - srcStream = new FileInputStream(srcFile); - src = srcStream.getChannel(); - destStream = new FileOutputStream(destFile); - dest = destStream.getChannel(); + try (FileInputStream srcStream = new FileInputStream(srcFile); + FileChannel src = srcStream.getChannel(); + FileOutputStream destStream = new FileOutputStream(destFile); + FileChannel dest = destStream.getChannel() + ) { dest.transferFrom(src, 0, src.size()); - } finally { - if (src != null) { src.close(); } - if (srcStream != null) { srcStream.close(); } - if (dest != null) { dest.close(); } - if (destStream != null) { destStream.close(); } } if (deleteSrcAfter) { diff --git a/forge-gui/src/main/java/forge/card/CardReaderExperiments.java b/forge-gui/src/main/java/forge/card/CardReaderExperiments.java index 8e355bb9eaf..91159243231 100644 --- a/forge-gui/src/main/java/forge/card/CardReaderExperiments.java +++ b/forge-gui/src/main/java/forge/card/CardReaderExperiments.java @@ -174,8 +174,7 @@ public class CardReaderExperiments { } if (updated) { - try { - PrintWriter p = new PrintWriter(file); + try (PrintWriter p = new PrintWriter(file)) { for (int i = 0; i < lines.size(); i++) { if (i < lines.size() - 1) { p.println(lines.get(i)); @@ -184,7 +183,6 @@ public class CardReaderExperiments { p.print(lines.get(i)); } } - p.close(); output.add(rules.getName()); } catch (final Exception ex) { } diff --git a/forge-gui/src/main/java/forge/card/CardScriptInfo.java b/forge-gui/src/main/java/forge/card/CardScriptInfo.java index a799ac7b738..4025ea8a6e4 100644 --- a/forge-gui/src/main/java/forge/card/CardScriptInfo.java +++ b/forge-gui/src/main/java/forge/card/CardScriptInfo.java @@ -49,13 +49,11 @@ public final class CardScriptInfo { public boolean trySetText(final String text0) { if (file == null) { return false; } - try { - final PrintWriter p = new PrintWriter(file); + try (PrintWriter p = new PrintWriter(file)) { p.print(text0); if (!text0.endsWith(("\n"))){ p.print("\n"); } - p.close(); text = text0; return true; diff --git a/forge-gui/src/main/java/forge/deck/io/CardThemedLDAIO.java b/forge-gui/src/main/java/forge/deck/io/CardThemedLDAIO.java index 75257a9a78d..56d281f79e4 100644 --- a/forge-gui/src/main/java/forge/deck/io/CardThemedLDAIO.java +++ b/forge-gui/src/main/java/forge/deck/io/CardThemedLDAIO.java @@ -19,33 +19,21 @@ public class CardThemedLDAIO { public static void saveRawLDA(String format, List lda){ File file = getRAWLDAFile(format); - ObjectOutputStream s = null; - try { - FileOutputStream f = new FileOutputStream(file); - s = new ObjectOutputStream(f); + try (FileOutputStream f = new FileOutputStream(file); + ObjectOutputStream s = new ObjectOutputStream(f)){ s.writeObject(lda); s.close(); } catch (IOException e) { System.out.println("Error writing matrix data: " + e); - } finally { - if(s!=null) { - try { - s.close(); - }catch(Exception e){ - e.printStackTrace(); - } - } } } public static List loadRawLDA(String format){ - try { - FileInputStream fin = new FileInputStream(getRAWLDAFile(format)); - ObjectInputStream s = new ObjectInputStream(fin); + try (FileInputStream fin = new FileInputStream(getRAWLDAFile(format)); + ObjectInputStream s = new ObjectInputStream(fin)) { List matrix = (List) s.readObject(); - s.close(); return matrix; - }catch (Exception e){ + } catch (Exception e){ System.out.println("Error reading LDA data: " + e); return null; } @@ -54,37 +42,24 @@ public class CardThemedLDAIO { public static void saveLDA(String format, Map>>> map){ File file = getLDAFile(format); - ObjectOutputStream s = null; - try { - FileOutputStream f = new FileOutputStream(file); - s = new ObjectOutputStream(f); + + try (FileOutputStream f = new FileOutputStream(file); + ObjectOutputStream s = new ObjectOutputStream(f)){ s.writeObject(map); - s.close(); } catch (IOException e) { System.out.println("Error writing matrix data: " + e); - } finally { - if(s!=null) { - try { - s.close(); - }catch(Exception e){ - e.printStackTrace(); - } - } } } public static Map>>> loadLDA(String format){ - try { - FileInputStream fin = new FileInputStream(getLDAFile(format)); - ObjectInputStream s = new ObjectInputStream(fin); + try (FileInputStream fin = new FileInputStream(getLDAFile(format)); + ObjectInputStream s = new ObjectInputStream(fin)) { Map>>> matrix = (Map>>>) s.readObject(); - s.close(); return matrix; - }catch (Exception e){ + } catch (Exception e){ System.out.println("Error reading LDA data: " + e); return null; } - } public static File getLDAFile(final String name) { diff --git a/forge-gui/src/main/java/forge/deck/io/CardThemedMatrixIO.java b/forge-gui/src/main/java/forge/deck/io/CardThemedMatrixIO.java index 29253b5f0f6..0536e70e32e 100644 --- a/forge-gui/src/main/java/forge/deck/io/CardThemedMatrixIO.java +++ b/forge-gui/src/main/java/forge/deck/io/CardThemedMatrixIO.java @@ -24,37 +24,23 @@ public class CardThemedMatrixIO { public static void saveMatrix(String format, HashMap>> map){ File file = getMatrixFile(format); - ObjectOutputStream s = null; - try { - FileOutputStream f = new FileOutputStream(file); - s = new ObjectOutputStream(f); + try (FileOutputStream f = new FileOutputStream(file); + ObjectOutputStream s = new ObjectOutputStream(f)) { s.writeObject(map); - s.close(); } catch (IOException e) { System.out.println("Error writing matrix data: " + e); - } finally { - if(s!=null) { - try { - s.close(); - }catch(Exception e){ - e.printStackTrace(); - } - } } } public static HashMap>> loadMatrix(String format){ - try { - FileInputStream fin = new FileInputStream(getMatrixFile(format)); - ObjectInputStream s = new ObjectInputStream(fin); + try (FileInputStream fin = new FileInputStream(getMatrixFile(format)); + ObjectInputStream s = new ObjectInputStream(fin)){ HashMap>> matrix = (HashMap>>) s.readObject(); - s.close(); return matrix; }catch (Exception e){ System.out.println("Error reading matrix data: " + e); return null; } - } public static File getMatrixFile(final String name) { diff --git a/forge-gui/src/main/java/forge/download/GuiDownloadZipService.java b/forge-gui/src/main/java/forge/download/GuiDownloadZipService.java index 70537c1bcc7..6a7904a4eb3 100644 --- a/forge-gui/src/main/java/forge/download/GuiDownloadZipService.java +++ b/forge-gui/src/main/java/forge/download/GuiDownloadZipService.java @@ -211,7 +211,7 @@ public class GuiDownloadZipService extends GuiDownloadService { } } - protected void copyInputStream(final InputStream in, final String outPath) throws IOException{ + protected void copyInputStream(final InputStream in, final String outPath) throws IOException { final byte[] buffer = new byte[1024]; int len; final BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outPath)); diff --git a/forge-gui/src/main/java/forge/error/BugReporter.java b/forge-gui/src/main/java/forge/error/BugReporter.java index 05614e7ff42..9c3dc291beb 100644 --- a/forge-gui/src/main/java/forge/error/BugReporter.java +++ b/forge-gui/src/main/java/forge/error/BugReporter.java @@ -145,12 +145,9 @@ public class BugReporter { f = GuiBase.getInterface().getSaveFile(f); - try { - final BufferedWriter bw = new BufferedWriter(new FileWriter(f)); + try (BufferedWriter bw = new BufferedWriter(new FileWriter(f))){ bw.write(text); - bw.close(); - } - catch (final IOException ex) { + } catch (final IOException ex) { SOptionPane.showMessageDialog("There was an error during saving. Sorry!\n" + ex, "Error saving file", SOptionPane.ERROR_ICON); } diff --git a/forge-gui/src/main/java/forge/gauntlet/GauntletIO.java b/forge-gui/src/main/java/forge/gauntlet/GauntletIO.java index 065146f68e0..721e4bd3298 100644 --- a/forge-gui/src/main/java/forge/gauntlet/GauntletIO.java +++ b/forge-gui/src/main/java/forge/gauntlet/GauntletIO.java @@ -109,37 +109,23 @@ public class GauntletIO { } public static GauntletData loadGauntlet(final File xmlSaveFile) { - GZIPInputStream zin = null; boolean isCorrupt = false; - try { - zin = new GZIPInputStream(new FileInputStream(xmlSaveFile)); - final InputStreamReader reader = new InputStreamReader(zin); - + try (GZIPInputStream zin = new GZIPInputStream(new FileInputStream(xmlSaveFile)); + InputStreamReader reader = new InputStreamReader(zin)) { final GauntletData data = (GauntletData)GauntletIO.getSerializer(true).fromXML(reader); final String filename = xmlSaveFile.getName(); data.setName(filename.substring(0, filename.length() - SUFFIX_DATA.length())); return data; - } - catch (final IOException e) { + } catch (final IOException e) { e.printStackTrace(); - } - catch (final ConversionException e) { + } catch (final ConversionException e) { BugReporter.reportException(e); - } - catch (final Exception e) { //if there's a non-IO exception, delete the corrupt file + } catch (final Exception e) { //if there's a non-IO exception, delete the corrupt file e.printStackTrace(); isCorrupt = true; } - finally { - if (zin != null) { - try { - zin.close(); - } catch (final IOException e) { - System.out.println("error closing gauntlet data reader: " + e); - } - } - } + if (isCorrupt) { try { xmlSaveFile.delete(); diff --git a/forge-gui/src/main/java/forge/quest/io/QuestDataIO.java b/forge-gui/src/main/java/forge/quest/io/QuestDataIO.java index cd232367df9..c64544b11b8 100644 --- a/forge-gui/src/main/java/forge/quest/io/QuestDataIO.java +++ b/forge-gui/src/main/java/forge/quest/io/QuestDataIO.java @@ -120,20 +120,19 @@ public class QuestDataIO { */ public static QuestData loadData(final File xmlSaveFile) throws IOException { QuestData data; - - final GZIPInputStream zin = new GZIPInputStream(new FileInputStream(xmlSaveFile)); final StringBuilder xml = new StringBuilder(); - final char[] buf = new char[1024]; - final InputStreamReader reader = new InputStreamReader(zin); - while (reader.ready()) { - final int len = reader.read(buf); - if (len == -1) { - break; - } // when end of stream was reached - xml.append(buf, 0, len); - } - zin.close(); + try (GZIPInputStream zin = new GZIPInputStream(new FileInputStream(xmlSaveFile)); + InputStreamReader reader = new InputStreamReader(zin)) { + final char[] buf = new char[1024]; + while (reader.ready()) { + final int len = reader.read(buf); + if (len == -1) { + break; + } // when end of stream was reached + xml.append(buf, 0, len); + } + } String bigXML = xml.toString(); try { diff --git a/forge-gui/src/main/java/forge/tournament/TournamentIO.java b/forge-gui/src/main/java/forge/tournament/TournamentIO.java index d005efc38bf..ab906dd5443 100644 --- a/forge-gui/src/main/java/forge/tournament/TournamentIO.java +++ b/forge-gui/src/main/java/forge/tournament/TournamentIO.java @@ -83,34 +83,21 @@ public class TournamentIO { } public static TournamentData loadTournament(final File xmlSaveFile) { - GZIPInputStream zin = null; boolean isCorrupt = false; - try { - zin = new GZIPInputStream(new FileInputStream(xmlSaveFile)); - final InputStreamReader reader = new InputStreamReader(zin); - + try (GZIPInputStream zin = new GZIPInputStream(new FileInputStream(xmlSaveFile)); + InputStreamReader reader = new InputStreamReader(zin)) { final TournamentData data = (TournamentData)TournamentIO.getSerializer(true).fromXML(reader); final String filename = xmlSaveFile.getName(); data.setName(filename.substring(0, filename.length() - SUFFIX_DATA.length())); return data; - } - catch (final IOException e) { + } catch (final IOException e) { e.printStackTrace(); - } - catch (final Exception e) { //if there's a non-IO exception, delete the corrupt file + } catch (final Exception e) { //if there's a non-IO exception, delete the corrupt file e.printStackTrace(); isCorrupt = true; } - finally { - if (zin != null) { - try { - zin.close(); - } catch (final IOException e) { - System.out.println("error closing tournament data reader: " + e); - } - } - } + if (isCorrupt) { try { xmlSaveFile.delete(); diff --git a/forge-gui/src/main/java/forge/util/HttpUtil.java b/forge-gui/src/main/java/forge/util/HttpUtil.java index 516950f47b7..9acc274576e 100644 --- a/forge-gui/src/main/java/forge/util/HttpUtil.java +++ b/forge-gui/src/main/java/forge/util/HttpUtil.java @@ -86,15 +86,9 @@ public class HttpUtil { return; } - FileInputStream uploadFileReader = null; - try { - uploadFileReader = new FileInputStream(f); - } catch (final FileNotFoundException e) { - return; - } final int numBytesToRead = 1024; int availableBytesToRead; - try { + try (FileInputStream uploadFileReader = new FileInputStream(f)) { while ((availableBytesToRead = uploadFileReader.available()) > 0) { byte[] bufferBytesRead; bufferBytesRead = availableBytesToRead >= numBytesToRead ? new byte[numBytesToRead] @@ -103,10 +97,10 @@ public class HttpUtil { httpOut.write(bufferBytesRead); httpOut.flush(); } - uploadFileReader.close(); } catch (final IOException e) { return; } + try { httpOut.write(("--" + HttpUtil.BOUNDARY + "--\r\n").getBytes()); } catch (final IOException e) { @@ -150,22 +144,17 @@ public class HttpUtil { } } - public static String getURL(final String sURL) { + public static String getURL(final String sURL) { URL url = null; try { url = new URL(sURL); } catch (final MalformedURLException e) { return null; } - InputStream is = null; - try { - is = url.openStream(); - } catch (final IOException e) { - return null; - } + int ptr = 0; final StringBuffer buffer = new StringBuffer(); - try { + try (InputStream is = url.openStream()) { while ((ptr = is.read()) != -1) { buffer.append((char) ptr); }