[tor-commits] [onionoo/master] Improve resource handling using try-with-resources.

karsten at torproject.org karsten at torproject.org
Fri Aug 7 12:34:18 UTC 2015


commit ab7c18d5ee2964e280c7c028a3445488ae05e2ec
Author: Karsten Loesing <karsten.loesing at gmx.net>
Date:   Fri Aug 7 12:09:55 2015 +0200

    Improve resource handling using try-with-resources.
    
    Patch by firebrand.  Implements #16626.
---
 .../torproject/onionoo/docs/BandwidthStatus.java   |   58 +++++++--------
 .../org/torproject/onionoo/docs/ClientsStatus.java |   20 +++---
 .../org/torproject/onionoo/docs/DocumentStore.java |   28 +++-----
 .../org/torproject/onionoo/docs/UptimeStatus.java  |   24 +++----
 .../org/torproject/onionoo/docs/WeightsStatus.java |   75 ++++++++++----------
 .../torproject/onionoo/server/ResourceServlet.java |    7 +-
 .../onionoo/updater/DescriptorDownloader.java      |   53 +++++++-------
 .../onionoo/updater/DescriptorQueue.java           |   16 ++---
 .../torproject/onionoo/updater/LookupService.java  |   47 +++++-------
 .../onionoo/updater/LookupServiceTest.java         |   12 ++--
 10 files changed, 157 insertions(+), 183 deletions(-)

diff --git a/src/main/java/org/torproject/onionoo/docs/BandwidthStatus.java b/src/main/java/org/torproject/onionoo/docs/BandwidthStatus.java
index c3b2db4..06f295b 100644
--- a/src/main/java/org/torproject/onionoo/docs/BandwidthStatus.java
+++ b/src/main/java/org/torproject/onionoo/docs/BandwidthStatus.java
@@ -44,37 +44,37 @@ public class BandwidthStatus extends Document {
   }
 
   public void setFromDocumentString(String documentString) {
-    Scanner s = new Scanner(documentString);
-    while (s.hasNextLine()) {
-      String line = s.nextLine();
-      String[] parts = line.split(" ");
-      if (parts.length != 6) {
-        log.error("Illegal line '" + line + "' in bandwidth "
-            + "history.  Skipping this line.");
-        continue;
-      }
-      SortedMap<Long, long[]> history = parts[0].equals("r")
-          ? readHistory : writeHistory;
-      long startMillis = DateTimeHelper.parse(parts[1] + " " + parts[2]);
-      long endMillis = DateTimeHelper.parse(parts[3] + " " + parts[4]);
-      if (startMillis < 0L || endMillis < 0L) {
-        log.error("Could not parse timestamp while reading "
-            + "bandwidth history.  Skipping.");
-        break;
-      }
-      long bandwidth = Long.parseLong(parts[5]);
-      long previousEndMillis = history.headMap(startMillis).isEmpty()
-          ? startMillis
-          : history.get(history.headMap(startMillis).lastKey())[1];
-      long nextStartMillis = history.tailMap(startMillis).isEmpty()
-          ? endMillis : history.tailMap(startMillis).firstKey();
-      if (previousEndMillis <= startMillis &&
-          nextStartMillis >= endMillis) {
-        history.put(startMillis, new long[] { startMillis, endMillis,
-            bandwidth });
+    try (Scanner s = new Scanner(documentString)) {
+      while (s.hasNextLine()) {
+        String line = s.nextLine();
+        String[] parts = line.split(" ");
+        if (parts.length != 6) {
+          log.error("Illegal line '" + line + "' in bandwidth "
+              + "history.  Skipping this line.");
+          continue;
+        }
+        SortedMap<Long, long[]> history = parts[0].equals("r")
+            ? readHistory : writeHistory;
+        long startMillis = DateTimeHelper.parse(parts[1] + " " + parts[2]);
+        long endMillis = DateTimeHelper.parse(parts[3] + " " + parts[4]);
+        if (startMillis < 0L || endMillis < 0L) {
+          log.error("Could not parse timestamp while reading "
+              + "bandwidth history.  Skipping.");
+          break;
+        }
+        long bandwidth = Long.parseLong(parts[5]);
+        long previousEndMillis = history.headMap(startMillis).isEmpty()
+            ? startMillis
+            : history.get(history.headMap(startMillis).lastKey())[1];
+        long nextStartMillis = history.tailMap(startMillis).isEmpty()
+            ? endMillis : history.tailMap(startMillis).firstKey();
+        if (previousEndMillis <= startMillis &&
+            nextStartMillis >= endMillis) {
+          history.put(startMillis, new long[] { startMillis, endMillis,
+              bandwidth });
+        }
       }
     }
-    s.close();
   }
 
   public void addToWriteHistory(BandwidthHistory bandwidthHistory) {
diff --git a/src/main/java/org/torproject/onionoo/docs/ClientsStatus.java b/src/main/java/org/torproject/onionoo/docs/ClientsStatus.java
index adb80a0..3cce0dd 100644
--- a/src/main/java/org/torproject/onionoo/docs/ClientsStatus.java
+++ b/src/main/java/org/torproject/onionoo/docs/ClientsStatus.java
@@ -33,18 +33,18 @@ public class ClientsStatus extends Document {
   }
 
   public void setFromDocumentString(String documentString) {
-    Scanner s = new Scanner(documentString);
-    while (s.hasNextLine()) {
-      String line = s.nextLine();
-      ClientsHistory parsedLine = ClientsHistory.fromString(line);
-      if (parsedLine != null) {
-        this.history.add(parsedLine);
-      } else {
-        log.error("Could not parse clients history line '"
-            + line + "'.  Skipping.");
+    try (Scanner s = new Scanner(documentString)) {
+      while (s.hasNextLine()) {
+        String line = s.nextLine();
+        ClientsHistory parsedLine = ClientsHistory.fromString(line);
+        if (parsedLine != null) {
+          this.history.add(parsedLine);
+        } else {
+          log.error("Could not parse clients history line '"
+              + line + "'.  Skipping.");
+        }
       }
     }
-    s.close();
   }
 
   public void addToHistory(SortedSet<ClientsHistory> newIntervals) {
diff --git a/src/main/java/org/torproject/onionoo/docs/DocumentStore.java b/src/main/java/org/torproject/onionoo/docs/DocumentStore.java
index 3d2ae7a..3be6fdb 100644
--- a/src/main/java/org/torproject/onionoo/docs/DocumentStore.java
+++ b/src/main/java/org/torproject/onionoo/docs/DocumentStore.java
@@ -110,9 +110,8 @@ public class DocumentStore {
     if (directory != null) {
       File summaryFile = new File(directory, "summary");
       if (summaryFile.exists()) {
-        try {
-          BufferedReader br = new BufferedReader(new FileReader(
-              summaryFile));
+        try (BufferedReader br = new BufferedReader(new FileReader(
+            summaryFile))) {
           String line;
           while ((line = br.readLine()) != null) {
             if (line.length() == 0) {
@@ -123,7 +122,6 @@ public class DocumentStore {
               parsedNodeStatuses.put(node.getFingerprint(), node);
             }
           }
-          br.close();
           this.lastModifiedNodeStatuses = summaryFile.lastModified();
           this.listedFiles += parsedNodeStatuses.size();
           this.listOperations++;
@@ -155,10 +153,9 @@ public class DocumentStore {
       File summaryFile = new File(this.outDir, "summary");
       if (summaryFile.exists()) {
         String line = null;
-        try {
+        try (BufferedReader br = new BufferedReader(new FileReader(
+            summaryFile))) {
           Gson gson = new Gson();
-          BufferedReader br = new BufferedReader(new FileReader(
-              summaryFile));
           while ((line = br.readLine()) != null) {
             if (line.length() == 0) {
               continue;
@@ -170,7 +167,6 @@ public class DocumentStore {
                   summaryDocument);
             }
           }
-          br.close();
           this.lastModifiedSummaryDocuments = summaryFile.lastModified();
           this.listedFiles += parsedSummaryDocuments.size();
           this.listOperations++;
@@ -443,16 +439,14 @@ public class DocumentStore {
       return null;
     }
     String documentString = null;
-    try {
-      ByteArrayOutputStream baos = new ByteArrayOutputStream();
-      BufferedInputStream bis = new BufferedInputStream(
-          new FileInputStream(documentFile));
+    try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        BufferedInputStream bis = new BufferedInputStream(
+        new FileInputStream(documentFile))) {
       int len;
       byte[] data = new byte[1024];
       while ((len = bis.read(data, 0, 1024)) >= 0) {
         baos.write(data, 0, len);
       }
-      bis.close();
       byte[] allData = baos.toByteArray();
       if (allData.length == 0) {
         /* Document file is empty. */
@@ -744,10 +738,10 @@ public class DocumentStore {
 
   private static void writeToFile(File file, String content)
       throws IOException {
-    BufferedOutputStream bos = new BufferedOutputStream(
-        new FileOutputStream(file));
-    bos.write(content.getBytes("US-ASCII"));
-    bos.close();
+    try (BufferedOutputStream bos = new BufferedOutputStream(
+        new FileOutputStream(file))) {
+      bos.write(content.getBytes("US-ASCII"));
+    }
   }
 
   private void writeSummaryDocuments() {
diff --git a/src/main/java/org/torproject/onionoo/docs/UptimeStatus.java b/src/main/java/org/torproject/onionoo/docs/UptimeStatus.java
index 266a245..8c5542d 100644
--- a/src/main/java/org/torproject/onionoo/docs/UptimeStatus.java
+++ b/src/main/java/org/torproject/onionoo/docs/UptimeStatus.java
@@ -36,22 +36,22 @@ public class UptimeStatus extends Document {
   }
 
   public void setFromDocumentString(String documentString) {
-    Scanner s = new Scanner(documentString);
-    while (s.hasNextLine()) {
-      String line = s.nextLine();
-      UptimeHistory parsedLine = UptimeHistory.fromString(line);
-      if (parsedLine != null) {
-        if (parsedLine.isRelay()) {
-          this.relayHistory.add(parsedLine);
+    try (Scanner s = new Scanner(documentString)) {
+      while (s.hasNextLine()) {
+        String line = s.nextLine();
+        UptimeHistory parsedLine = UptimeHistory.fromString(line);
+        if (parsedLine != null) {
+          if (parsedLine.isRelay()) {
+            this.relayHistory.add(parsedLine);
+          } else {
+            this.bridgeHistory.add(parsedLine);
+          }
         } else {
-          this.bridgeHistory.add(parsedLine);
+          log.error("Could not parse uptime history line '"
+              + line + "'.  Skipping.");
         }
-      } else {
-        log.error("Could not parse uptime history line '"
-            + line + "'.  Skipping.");
       }
     }
-    s.close();
   }
 
   public void addToHistory(boolean relay, long startMillis,
diff --git a/src/main/java/org/torproject/onionoo/docs/WeightsStatus.java b/src/main/java/org/torproject/onionoo/docs/WeightsStatus.java
index 6d2f63f..5d7f23e 100644
--- a/src/main/java/org/torproject/onionoo/docs/WeightsStatus.java
+++ b/src/main/java/org/torproject/onionoo/docs/WeightsStatus.java
@@ -37,46 +37,47 @@ public class WeightsStatus extends Document {
   }
 
   public void setFromDocumentString(String documentString) {
-    Scanner s = new Scanner(documentString);
-    while (s.hasNextLine()) {
-      String line = s.nextLine();
-      String[] parts = line.split(" ");
-      if (parts.length == 2) {
-        /* Skip lines containing descriptor digest and advertised
-         * bandwidth. */
-        continue;
-      }
-      if (parts.length != 9 && parts.length != 11) {
-        log.error("Illegal line '" + line + "' in weights "
+    try (Scanner s = new Scanner(documentString)) {
+      while (s.hasNextLine()) {
+        String line = s.nextLine();
+        String[] parts = line.split(" ");
+        if (parts.length == 2) {
+          /* Skip lines containing descriptor digest and advertised
+           * bandwidth. */
+          continue;
+        }
+        if (parts.length != 9 && parts.length != 11) {
+          log.error("Illegal line '" + line + "' in weights "
               + "status file.  Skipping this line.");
-        continue;
-      }
-      if (parts[4].equals("NaN")) {
-        /* Remove corrupt lines written on 2013-07-07 and the days
-         * after. */
-        continue;
-      }
-      long validAfterMillis = DateTimeHelper.parse(parts[0] + " "
-          + parts[1]);
-      long freshUntilMillis = DateTimeHelper.parse(parts[2] + " "
-          + parts[3]);
-      if (validAfterMillis < 0L || freshUntilMillis < 0L) {
-        log.error("Could not parse timestamp while reading "
-            + "weights status file.  Skipping.");
-        break;
-      }
-      long[] interval = new long[] { validAfterMillis, freshUntilMillis };
-      double[] weights = new double[] { -1.0,
-          Double.parseDouble(parts[5]),
-          Double.parseDouble(parts[6]),
-          Double.parseDouble(parts[7]),
-          Double.parseDouble(parts[8]), -1.0, -1.0 };
-      if (parts.length == 11) {
-        weights[6] = Double.parseDouble(parts[10]);
+          continue;
+        }
+        if (parts[4].equals("NaN")) {
+          /* Remove corrupt lines written on 2013-07-07 and the days
+           * after. */
+          continue;
+        }
+        long validAfterMillis = DateTimeHelper.parse(parts[0] + " "
+            + parts[1]);
+        long freshUntilMillis = DateTimeHelper.parse(parts[2] + " "
+            + parts[3]);
+        if (validAfterMillis < 0L || freshUntilMillis < 0L) {
+          log.error("Could not parse timestamp while reading "
+              + "weights status file.  Skipping.");
+          break;
+        }
+        long[] interval = new long[] { validAfterMillis,
+            freshUntilMillis };
+        double[] weights = new double[] { -1.0,
+            Double.parseDouble(parts[5]),
+            Double.parseDouble(parts[6]),
+            Double.parseDouble(parts[7]),
+            Double.parseDouble(parts[8]), -1.0, -1.0 };
+        if (parts.length == 11) {
+          weights[6] = Double.parseDouble(parts[10]);
+        }
+        this.history.put(interval, weights);
       }
-      this.history.put(interval, weights);
     }
-    s.close();
   }
 
   public void addToHistory(long validAfterMillis, long freshUntilMillis,
diff --git a/src/main/java/org/torproject/onionoo/server/ResourceServlet.java b/src/main/java/org/torproject/onionoo/server/ResourceServlet.java
index 8589e13..1b6ad7f 100644
--- a/src/main/java/org/torproject/onionoo/server/ResourceServlet.java
+++ b/src/main/java/org/torproject/onionoo/server/ResourceServlet.java
@@ -345,13 +345,12 @@ public class ResourceServlet extends HttpServlet {
     response.setCharacterEncoding("utf-8");
     response.setHeader("Cache-Control", "public, max-age="
         + (cacheMaxAgeMillis / 1000L));
-    PrintWriter pw = response.getWriter();
-    rb.buildResponse(pw);
+    try (PrintWriter pw = response.getWriter()) {
+      rb.buildResponse(pw);
+    }
     int relayDocumentsWritten = rh.getOrderedRelays().size();
     int bridgeDocumentsWritten = rh.getOrderedBridges().size();
     int charsWritten = rb.getCharsWritten();
-    pw.flush();
-    pw.close();
     long writtenResponseMillis = time.currentTimeMillis();
     PerformanceMetrics.logStatistics(receivedRequestMillis, resourceType,
         parameterMap.keySet(), parsedRequestMillis, relayDocumentsWritten,
diff --git a/src/main/java/org/torproject/onionoo/updater/DescriptorDownloader.java b/src/main/java/org/torproject/onionoo/updater/DescriptorDownloader.java
index d5b6c49..2655b1a 100644
--- a/src/main/java/org/torproject/onionoo/updater/DescriptorDownloader.java
+++ b/src/main/java/org/torproject/onionoo/updater/DescriptorDownloader.java
@@ -86,26 +86,26 @@ class DescriptorDownloader {
             + huc.getResponseMessage() + ".  Skipping.");
         return 0;
       }
-      BufferedReader br = new BufferedReader(new InputStreamReader(
-          huc.getInputStream()));
-      String line;
-      while ((line = br.readLine()) != null) {
-        if (!line.trim().startsWith("<tr>") ||
-            !line.contains("<a href=\"")) {
-          continue;
-        }
-        String linePart = line.substring(
-            line.indexOf("<a href=\"") + "<a href=\"".length());
-        if (!linePart.contains("\"")) {
-          continue;
-        }
-        linePart = linePart.substring(0, linePart.indexOf("\""));
-        if (linePart.endsWith("/")) {
-          continue;
+      try (BufferedReader br = new BufferedReader(new InputStreamReader(
+          huc.getInputStream()))) {
+        String line;
+        while ((line = br.readLine()) != null) {
+          if (!line.trim().startsWith("<tr>") ||
+              !line.contains("<a href=\"")) {
+            continue;
+          }
+          String linePart = line.substring(
+              line.indexOf("<a href=\"") + "<a href=\"".length());
+          if (!linePart.contains("\"")) {
+            continue;
+          }
+          linePart = linePart.substring(0, linePart.indexOf("\""));
+          if (linePart.endsWith("/")) {
+            continue;
+          }
+          this.remoteFiles.add(linePart);
         }
-        this.remoteFiles.add(linePart);
       }
-      br.close();
     } catch (IOException e) {
       log.error("Could not fetch or parse " + directoryUrl
         + ".  Skipping. Reason: " + e.getMessage());
@@ -145,16 +145,15 @@ class DescriptorDownloader {
         } else {
           is = huc.getInputStream();
         }
-        BufferedInputStream bis = new BufferedInputStream(is);
-        BufferedOutputStream bos = new BufferedOutputStream(
-            new FileOutputStream(localTempFile));
-        int len;
-        byte[] data = new byte[1024];
-        while ((len = bis.read(data, 0, 1024)) >= 0) {
-          bos.write(data, 0, len);
+        try (BufferedInputStream bis = new BufferedInputStream(is);
+            BufferedOutputStream bos = new BufferedOutputStream(
+            new FileOutputStream(localTempFile))) {
+          int len;
+          byte[] data = new byte[1024];
+          while ((len = bis.read(data, 0, 1024)) >= 0) {
+            bos.write(data, 0, len);
+          }
         }
-        bis.close();
-        bos.close();
         localTempFile.renameTo(localFile);
         if (lastModified >= 0) {
           localFile.setLastModified(lastModified);
diff --git a/src/main/java/org/torproject/onionoo/updater/DescriptorQueue.java b/src/main/java/org/torproject/onionoo/updater/DescriptorQueue.java
index 6740ca9..6010bbf 100644
--- a/src/main/java/org/torproject/onionoo/updater/DescriptorQueue.java
+++ b/src/main/java/org/torproject/onionoo/updater/DescriptorQueue.java
@@ -97,8 +97,7 @@ class DescriptorQueue {
           + "to descriptor reader.");
       return null;
     }
-    File directory = new File(inDir, directoryName);
-    return directory;
+    return new File(inDir, directoryName);
   }
 
   private void addDirectory(File directory) {
@@ -150,9 +149,8 @@ class DescriptorQueue {
     this.historyFile = new File(this.statusDir, historyFileName);
     if (this.historyFile.exists() && this.historyFile.isFile()) {
       SortedMap<String, Long> excludedFiles = new TreeMap<String, Long>();
-      try {
-        BufferedReader br = new BufferedReader(new FileReader(
-            this.historyFile));
+      try (BufferedReader br = new BufferedReader(new FileReader(
+          this.historyFile))) {
         String line;
         while ((line = br.readLine()) != null) {
           try {
@@ -163,7 +161,6 @@ class DescriptorQueue {
                 + "history.  Skipping line.");
           }
         }
-        br.close();
       } catch (IOException e) {
         log.error("Could not read history file '"
             + this.historyFile.getAbsolutePath() + "'.  Not excluding "
@@ -185,22 +182,19 @@ class DescriptorQueue {
         this.descriptorReader.getExcludedFiles());
     excludedAndParsedFiles.putAll(this.descriptorReader.getParsedFiles());
     this.historySizeAfter = excludedAndParsedFiles.size();
-    try {
+    try (BufferedWriter bw = new BufferedWriter(new FileWriter(
+        this.historyFile))) {
       this.historyFile.getParentFile().mkdirs();
-      BufferedWriter bw = new BufferedWriter(new FileWriter(
-          this.historyFile));
       for (Map.Entry<String, Long> e : excludedAndParsedFiles.entrySet()) {
         String absolutePath = e.getKey();
         long lastModifiedMillis = e.getValue();
         bw.write(String.valueOf(lastModifiedMillis) + " " + absolutePath
             + "\n");
       }
-      bw.close();
     } catch (IOException e) {
       log.error("Could not write history file '"
           + this.historyFile.getAbsolutePath() + "'.  Not excluding "
           + "descriptors in next execution.");
-      return;
     }
   }
 
diff --git a/src/main/java/org/torproject/onionoo/updater/LookupService.java b/src/main/java/org/torproject/onionoo/updater/LookupService.java
index 16dd625..aaa4c1c 100644
--- a/src/main/java/org/torproject/onionoo/updater/LookupService.java
+++ b/src/main/java/org/torproject/onionoo/updater/LookupService.java
@@ -116,11 +116,10 @@ public class LookupService {
     Map<Long, Long> addressNumberBlocks = new HashMap<Long, Long>();
     Map<Long, Float[]> addressNumberLatLong =
         new HashMap<Long, Float[]>();
-    try {
+    try (BufferedReader br = this.createBufferedReaderFromUtf8File(
+        this.geoLite2CityBlocksIPv4CsvFile)) {
       SortedSet<Long> sortedAddressNumbers = new TreeSet<Long>(
           addressStringNumbers.values());
-      BufferedReader br = this.createBufferedReaderFromUtf8File(
-          this.geoLite2CityBlocksIPv4CsvFile);
       String line = br.readLine();
       while ((line = br.readLine()) != null) {
         String[] parts = line.split(",", 9);
@@ -128,7 +127,6 @@ public class LookupService {
           log.error("Illegal line '" + line + "' in "
               + this.geoLite2CityBlocksIPv4CsvFile.getAbsolutePath()
               + ".");
-          br.close();
           return lookupResults;
         }
         try {
@@ -139,7 +137,6 @@ public class LookupService {
             log.error("Illegal IP address in '" + line + "' in "
                 + this.geoLite2CityBlocksIPv4CsvFile.getAbsolutePath()
                 + ".");
-            br.close();
             return lookupResults;
           }
           int networkMaskLength = networkAddressAndMask.length < 2 ? 0
@@ -149,7 +146,6 @@ public class LookupService {
                 + "' in "
                 + this.geoLite2CityBlocksIPv4CsvFile.getAbsolutePath()
                 + ".");
-            br.close();
             return lookupResults;
           }
           if (parts[1].length() == 0 && parts[2].length() == 0) {
@@ -174,11 +170,9 @@ public class LookupService {
               + "' in "
               + this.geoLite2CityBlocksIPv4CsvFile.getAbsolutePath()
               + ".");
-          br.close();
           return lookupResults;
         }
       }
-      br.close();
     } catch (IOException e) {
       log.error("I/O exception while reading "
           + this.geoLite2CityBlocksIPv4CsvFile.getAbsolutePath()
@@ -188,11 +182,10 @@ public class LookupService {
 
     /* Obtain a map from relevant blocks to location lines. */
     Map<Long, String> blockLocations = new HashMap<Long, String>();
-    try {
+    try (BufferedReader br = this.createBufferedReaderFromUtf8File(
+        this.geoLite2CityLocationsEnCsvFile)) {
       Set<Long> blockNumbers = new HashSet<Long>(
           addressNumberBlocks.values());
-      BufferedReader br = this.createBufferedReaderFromUtf8File(
-          this.geoLite2CityLocationsEnCsvFile);
       String line = br.readLine();
       while ((line = br.readLine()) != null) {
         String[] parts = line.replaceAll("\"", "").split(",", 13);
@@ -200,7 +193,6 @@ public class LookupService {
           log.error("Illegal line '" + line + "' in "
               + this.geoLite2CityLocationsEnCsvFile.getAbsolutePath()
               + ".");
-          br.close();
           return lookupResults;
         }
 
@@ -214,11 +206,9 @@ public class LookupService {
               + "'" + line + "' in "
               + this.geoLite2CityLocationsEnCsvFile.getAbsolutePath()
               + ".");
-          br.close();
           return lookupResults;
         }
       }
-      br.close();
     } catch (IOException e) {
       log.error("I/O exception while reading "
           + this.geoLite2CityLocationsEnCsvFile.getAbsolutePath()
@@ -228,12 +218,11 @@ public class LookupService {
 
     /* Obtain a map from IP address numbers to ASN. */
     Map<Long, String> addressNumberASN = new HashMap<Long, String>();
-    try {
+    try (BufferedReader br = this.createBufferedReaderFromIso88591File(
+        this.geoIPASNum2CsvFile)) {
       SortedSet<Long> sortedAddressNumbers = new TreeSet<Long>(
           addressStringNumbers.values());
       long firstAddressNumber = sortedAddressNumbers.first();
-      BufferedReader br = this.createBufferedReaderFromIso88591File(
-          this.geoIPASNum2CsvFile);
       String line;
       long previousStartIpNum = -1L;
       while ((line = br.readLine()) != null) {
@@ -241,7 +230,6 @@ public class LookupService {
         if (parts.length != 3) {
           log.error("Illegal line '" + line + "' in "
               + geoIPASNum2CsvFile.getAbsolutePath() + ".");
-          br.close();
           return lookupResults;
         }
         try {
@@ -249,7 +237,6 @@ public class LookupService {
           if (startIpNum <= previousStartIpNum) {
             log.error("Line '" + line + "' not sorted in "
                 + geoIPASNum2CsvFile.getAbsolutePath() + ".");
-            br.close();
             return lookupResults;
           }
           previousStartIpNum = startIpNum;
@@ -283,11 +270,9 @@ public class LookupService {
           log.error("Number format exception while parsing line "
               + "'" + line + "' in "
               + geoIPASNum2CsvFile.getAbsolutePath() + ".");
-          br.close();
           return lookupResults;
         }
       }
-      br.close();
     } catch (IOException e) {
       log.error("I/O exception while reading "
           + geoIPASNum2CsvFile.getAbsolutePath() + ": " + e);
@@ -346,23 +331,23 @@ public class LookupService {
 
   private BufferedReader createBufferedReaderFromUtf8File(File utf8File)
       throws FileNotFoundException, CharacterCodingException {
-    CharsetDecoder dec = StandardCharsets.UTF_8.newDecoder();
-    dec.onMalformedInput(CodingErrorAction.REPORT);
-    dec.onUnmappableCharacter(CodingErrorAction.REPORT);
-    BufferedReader br = new BufferedReader(
-        new InputStreamReader(new FileInputStream(utf8File), dec));
-    return br;
+    return this.createBufferedReaderFromFile(utf8File,
+        StandardCharsets.UTF_8.newDecoder());
   }
 
   private BufferedReader createBufferedReaderFromIso88591File(
       File iso88591File) throws FileNotFoundException,
       CharacterCodingException {
-    CharsetDecoder dec = StandardCharsets.ISO_8859_1.newDecoder();
+    return this.createBufferedReaderFromFile(iso88591File,
+        StandardCharsets.ISO_8859_1.newDecoder());
+  }
+
+  private BufferedReader createBufferedReaderFromFile(File file,
+      CharsetDecoder dec) throws FileNotFoundException {
     dec.onMalformedInput(CodingErrorAction.REPORT);
     dec.onUnmappableCharacter(CodingErrorAction.REPORT);
-    BufferedReader br = new BufferedReader(
-        new InputStreamReader(new FileInputStream(iso88591File), dec));
-    return br;
+    return new BufferedReader(new InputStreamReader(
+        new FileInputStream(file), dec));
   }
 
   private int addressesLookedUp = 0, addressesResolved = 0;
diff --git a/src/test/java/org/torproject/onionoo/updater/LookupServiceTest.java b/src/test/java/org/torproject/onionoo/updater/LookupServiceTest.java
index 5673d9a..2b90a37 100644
--- a/src/test/java/org/torproject/onionoo/updater/LookupServiceTest.java
+++ b/src/test/java/org/torproject/onionoo/updater/LookupServiceTest.java
@@ -85,13 +85,15 @@ public class LookupServiceTest {
   private void writeCsvFile(List<String> lines, String fileName,
       String encoding) throws IOException {
     if (lines != null && !lines.isEmpty()) {
-      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
+      try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
           new FileOutputStream(new File(this.tempGeoipDir, fileName)),
-          encoding));
-      for (String line : lines) {
-        bw.write(line + "\n");
+          encoding))) {
+
+        for (String line : lines) {
+          bw.write(line);
+          bw.newLine();
+        }
       }
-      bw.close();
     }
   }
 



More information about the tor-commits mailing list