Changeset 7030 in josm


Ignore:
Timestamp:
2014-04-29T18:06:29+02:00 (10 years ago)
Author:
Don-vip
Message:

see #8465 - use of try-with-resource

Location:
trunk
Files:
11 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/org/openstreetmap/josm/gui/dialogs/MapPaintDialog.java

    r7005 r7030  
    658658            try {
    659659                InputStream is = s.getSourceInputStream();
    660                 try {
    661                     BufferedReader reader = new BufferedReader(new InputStreamReader(is, Utils.UTF_8));
    662                     try {
    663                         String line;
    664                         while ((line = reader.readLine()) != null) {
    665                             txtSource.append(line + "\n");
    666                         }
    667                     } finally {
    668                         reader.close();
     660                try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, Utils.UTF_8))) {
     661                    String line;
     662                    while ((line = reader.readLine()) != null) {
     663                        txtSource.append(line + "\n");
    669664                    }
    670665                } finally {
  • trunk/src/org/openstreetmap/josm/gui/mappaint/MapPaintStyles.java

    r7005 r7030  
    235235                return new XmlStyleSource(entry);
    236236            else {
    237                 InputStreamReader reader = new InputStreamReader(in, Utils.UTF_8);
    238                 try {
     237                try (InputStreamReader reader = new InputStreamReader(in, Utils.UTF_8)) {
    239238                    WHILE: while (true) {
    240239                        int c = reader.read();
     
    253252                        }
    254253                    }
    255                 } finally {
    256                     reader.close();
    257254                }
    258255                Main.warn("Could not detect style type. Using default (xml).");
  • trunk/src/org/openstreetmap/josm/io/GeoJSONWriter.java

    r7005 r7030  
    6060        Map<String, Object> config = new HashMap<>(1);
    6161        config.put(JsonGenerator.PRETTY_PRINTING, pretty);
    62         JsonWriter writer = Json.createWriterFactory(config).createWriter(stringWriter);
    63         JsonObjectBuilder object = Json.createObjectBuilder()
    64                 .add("type", "FeatureCollection")
    65                 .add("generator", "JOSM");
    66         appendLayerBounds(layer.data, object);
    67         appendLayerFeatures(layer.data, object);
    68         writer.writeObject(object.build());
    69         String result = stringWriter.toString();
    70         writer.close();
    71         return result;
     62        try (JsonWriter writer = Json.createWriterFactory(config).createWriter(stringWriter)) {
     63            JsonObjectBuilder object = Json.createObjectBuilder()
     64                    .add("type", "FeatureCollection")
     65                    .add("generator", "JOSM");
     66            appendLayerBounds(layer.data, object);
     67            appendLayerFeatures(layer.data, object);
     68            writer.writeObject(object.build());
     69            return stringWriter.toString();
     70        }
    7271    }
    7372   
  • trunk/src/org/openstreetmap/josm/io/OsmApi.java

    r7012 r7030  
    632632                    // even if there is no payload.
    633633                    if (requestBody != null) {
    634                         BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(out, Utils.UTF_8));
    635                         try {
     634                        try (BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(out, Utils.UTF_8))) {
    636635                            bwr.write(requestBody);
    637636                            bwr.flush();
    638                         } finally {
    639                             bwr.close();
    640637                        }
    641638                    }
     
    671668                    // Unauthorized, see #3887.
    672669                    //
    673                     BufferedReader in = new BufferedReader(new InputStreamReader(i, Utils.UTF_8));
    674670                    String s;
    675                     try {
     671                    try (BufferedReader in = new BufferedReader(new InputStreamReader(i, Utils.UTF_8))) {
    676672                        while((s = in.readLine()) != null) {
    677673                            responseBody.append(s);
    678674                            responseBody.append("\n");
    679675                        }
    680                     } finally {
    681                         in.close();
    682676                    }
    683677                }
  • trunk/src/org/openstreetmap/josm/io/imagery/WMSImagery.java

    r7005 r7030  
    141141        URLConnection openConnection = Utils.openHttpConnection(getCapabilitiesUrl);
    142142        InputStream inputStream = openConnection.getInputStream();
    143         BufferedReader br = new BufferedReader(UTFInputStreamReader.create(inputStream));
    144         String line;
    145143        StringBuilder ba = new StringBuilder();
    146         try {
     144        try (BufferedReader br = new BufferedReader(UTFInputStreamReader.create(inputStream))) {
     145            String line;
    147146            while ((line = br.readLine()) != null) {
    148147                ba.append(line);
    149148                ba.append("\n");
    150149            }
    151         } finally {
    152             br.close();
    153150        }
    154151        String incomingData = ba.toString();
  • trunk/src/org/openstreetmap/josm/io/remotecontrol/RequestProcessor.java

    r7005 r7030  
    383383
    384384    public static String getHandlerInfoAsJSON(String cmd) {
    385         StringWriter w = new StringWriter();
    386         PrintWriter r = new PrintWriter(w);
    387         RequestHandler handler = null;
    388         try {
    389             Class<?> c = handlers.get(cmd);
    390             if (c==null) return null;
    391             handler = handlers.get(cmd).newInstance();
    392         } catch (Exception ex) {
    393             Main.error(ex);
     385        try (StringWriter w = new StringWriter()) {
     386            PrintWriter r = new PrintWriter(w);
     387            RequestHandler handler = null;
     388            try {
     389                Class<?> c = handlers.get(cmd);
     390                if (c==null) return null;
     391                handler = handlers.get(cmd).newInstance();
     392            } catch (InstantiationException | IllegalAccessException ex) {
     393                Main.error(ex);
     394                return null;
     395            }
     396   
     397            printJsonInfo(cmd, r, handler);
     398            return w.toString();
     399        } catch (IOException e) {
     400            Main.error(e);
    394401            return null;
    395402        }
    396 
     403    }
     404
     405    private static void printJsonInfo(String cmd, PrintWriter r, RequestHandler handler) {
    397406        r.printf("{ \"request\" : \"%s\"", cmd);
    398407        if (handler.getUsage() != null) {
     
    438447        }
    439448        r.append("]}");
    440         try {
    441             return w.toString();
    442         } finally {
    443             try {
    444                 w.close();
    445             } catch (IOException ex) {
    446                 Main.warn(ex);
    447             }
    448         }
    449449    }
    450450
  • trunk/test/functional/org/openstreetmap/josm/gui/history/HistoryBrowserTest.java

    r7025 r7030  
    3838        // load properties
    3939        //
    40         try {
    41             InputStream is = HistoryBrowserTest.class.getResourceAsStream("/test-functional-env.properties");
    42             try {
    43                 testProperties.load(is);
    44             } finally {
    45                 is.close();
    46             }
     40        try (InputStream is = HistoryBrowserTest.class.getResourceAsStream("/test-functional-env.properties");) {
     41            testProperties.load(is);
    4742        } catch(IOException e){
    4843            logger.log(Level.SEVERE, MessageFormat.format("failed to load property file ''{0}''", "test-functional-env.properties"));
  • trunk/test/functional/org/openstreetmap/josm/io/MultiFetchServerObjectReaderTest.java

    r7025 r7030  
    134134
    135135    @BeforeClass
    136     public static void  init() throws OsmTransferException {
     136    public static void init() throws OsmTransferException {
    137137        logger.info("initializing ...");
    138138        testProperties = new Properties();
     
    140140        // load properties
    141141        //
    142         try {
    143             InputStream is = MultiFetchServerObjectReaderTest.class.getResourceAsStream("/test-functional-env.properties");
    144             try {
    145                 testProperties.load(is);
    146             } finally {
    147                 is.close();
    148             }
     142        try (InputStream is = MultiFetchServerObjectReaderTest.class.getResourceAsStream("/test-functional-env.properties")) {
     143            testProperties.load(is);
    149144        } catch(IOException e){
    150145            logger.log(Level.SEVERE, MessageFormat.format("failed to load property file ''{0}''", "test-functional-env.properties"));
     
    211206        createDataSetOnServer(testDataSet);
    212207
    213         try {
     208        try (
    214209            PrintWriter pw = new PrintWriter(
    215210                    new OutputStreamWriter(new FileOutputStream(dataSetCacheOutputFile), Utils.UTF_8)
    216             );
     211        )) {
    217212            logger.info(MessageFormat.format("caching test data set in ''{0}'' ...", dataSetCacheOutputFile.toString()));
    218             OsmWriter w = new OsmWriter(pw, false, testDataSet.getVersion());
    219             w.header();
    220             w.writeDataSources(testDataSet);
    221             w.writeContent(testDataSet);
    222             w.footer();
    223             w.close();
    224             pw.close();
     213            try (OsmWriter w = new OsmWriter(pw, false, testDataSet.getVersion())) {
     214                w.header();
     215                w.writeDataSources(testDataSet);
     216                w.writeContent(testDataSet);
     217                w.footer();
     218            }
    225219        } catch(IOException e) {
    226220            fail(MessageFormat.format("failed to open file ''{0}'' for writing", dataSetCacheOutputFile.toString()));
     
    238232        logger.info(MessageFormat.format("reading cached dataset ''{0}''", f.toString()));
    239233        ds = new DataSet();
    240         FileInputStream fis = new FileInputStream(f);
    241         ds = OsmReader.parseDataSet(fis, NullProgressMonitor.INSTANCE);
    242         fis.close();
     234        try (FileInputStream fis = new FileInputStream(f)) {
     235            ds = OsmReader.parseDataSet(fis, NullProgressMonitor.INSTANCE);
     236        }
    243237    }
    244238
  • trunk/test/functional/org/openstreetmap/josm/io/OsmServerBackreferenceReaderTest.java

    r7025 r7030  
    147147        // load properties
    148148        //
    149         try {
    150             InputStream is = MultiFetchServerObjectReaderTest.class.getResourceAsStream("/test-functional-env.properties");
    151             try {
    152                 testProperties.load(is);
    153             } finally {
    154                 is.close();
    155             }
     149        try (InputStream is = MultiFetchServerObjectReaderTest.class.getResourceAsStream("/test-functional-env.properties")) {
     150            testProperties.load(is);
    156151        } catch(IOException e){
    157152            logger.log(Level.SEVERE, MessageFormat.format("failed to load property file ''{0}''", "test-functional-env.properties"));
     
    218213        createDataSetOnServer(testDataSet);
    219214
    220         try {
     215        try (
    221216            PrintWriter pw = new PrintWriter(
    222217                    new OutputStreamWriter(new FileOutputStream(dataSetCacheOutputFile), Utils.UTF_8)
    223             );
     218        )) {
    224219            logger.info(MessageFormat.format("caching test data set in ''{0}'' ...", dataSetCacheOutputFile.toString()));
    225             OsmWriter w = new OsmWriter(pw, false, testDataSet.getVersion());
    226             w.header();
    227             w.writeDataSources(testDataSet);
    228             w.writeContent(testDataSet);
    229             w.footer();
    230             w.close();
    231             pw.close();
     220            try (OsmWriter w = new OsmWriter(pw, false, testDataSet.getVersion())) {
     221                w.header();
     222                w.writeDataSources(testDataSet);
     223                w.writeContent(testDataSet);
     224                w.footer();
     225            }
    232226        } catch(IOException e) {
    233227            fail(MessageFormat.format("failed to open file ''{0}'' for writing", dataSetCacheOutputFile.toString()));
     
    245239        logger.info(MessageFormat.format("reading cached dataset ''{0}''", f.toString()));
    246240        ds = new DataSet();
    247         FileInputStream fis = new FileInputStream(f);
    248         ds = OsmReader.parseDataSet(fis, NullProgressMonitor.INSTANCE);
    249         fis.close();
     241        try (FileInputStream fis = new FileInputStream(f)) {
     242            ds = OsmReader.parseDataSet(fis, NullProgressMonitor.INSTANCE);
     243        }
    250244    }
    251245
  • trunk/test/unit/org/openstreetmap/josm/data/projection/ProjectionRegressionTest.java

    r7005 r7030  
    1818import java.util.List;
    1919import java.util.Map;
    20 import java.util.Map.Entry;
    2120import java.util.Random;
    2221import java.util.Set;
     
    9089
    9190        Random rand = new Random();
    92         BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(PROJECTION_DATA_FILE), Utils.UTF_8));
    93         out.write("# Data for test/unit/org/openstreetmap/josm/data/projection/ProjectionRegressionTest.java\n");
    94         out.write("# Format: 1. Projection code; 2. lat/lon; 3. lat/lon projected -> east/north; 4. east/north (3.) inverse projected\n");
    95         for (Entry<String, Projection> e : supportedCodesMap.entrySet()) {
    96         }
    97         for (String code : codesToWrite) {
    98             Projection proj = supportedCodesMap.get(code);
    99             Bounds b = proj.getWorldBoundsLatLon();
    100             double lat, lon;
    101             TestData prev = prevCodesMap.get(proj.toCode());
    102             if (prev != null) {
    103                 lat = prev.ll.lat();
    104                 lon = prev.ll.lon();
    105             } else {
    106                 lat = b.getMin().lat() + rand.nextDouble() * (b.getMax().lat() - b.getMin().lat());
    107                 lon = b.getMin().lon() + rand.nextDouble() * (b.getMax().lon() - b.getMin().lon());
    108             }
    109             EastNorth en = proj.latlon2eastNorth(new LatLon(lat, lon));
    110             LatLon ll2 = proj.eastNorth2latlon(en);
    111             out.write(String.format("%s%n  ll  %s %s%n  en  %s %s%n  ll2 %s %s%n", proj.toCode(), lat, lon, en.east(), en.north(), ll2.lat(), ll2.lon()));
    112         }
    113         out.close();
     91        try (BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(PROJECTION_DATA_FILE), Utils.UTF_8))) {
     92            out.write("# Data for test/unit/org/openstreetmap/josm/data/projection/ProjectionRegressionTest.java\n");
     93            out.write("# Format: 1. Projection code; 2. lat/lon; 3. lat/lon projected -> east/north; 4. east/north (3.) inverse projected\n");
     94            for (String code : codesToWrite) {
     95                Projection proj = supportedCodesMap.get(code);
     96                Bounds b = proj.getWorldBoundsLatLon();
     97                double lat, lon;
     98                TestData prev = prevCodesMap.get(proj.toCode());
     99                if (prev != null) {
     100                    lat = prev.ll.lat();
     101                    lon = prev.ll.lon();
     102                } else {
     103                    lat = b.getMin().lat() + rand.nextDouble() * (b.getMax().lat() - b.getMin().lat());
     104                    lon = b.getMin().lon() + rand.nextDouble() * (b.getMax().lon() - b.getMin().lon());
     105                }
     106                EastNorth en = proj.latlon2eastNorth(new LatLon(lat, lon));
     107                LatLon ll2 = proj.eastNorth2latlon(en);
     108                out.write(String.format("%s%n  ll  %s %s%n  en  %s %s%n  ll2 %s %s%n", proj.toCode(), lat, lon, en.east(), en.north(), ll2.lat(), ll2.lon()));
     109            }
     110        }
    114111    }
    115112
    116113    private static List<TestData> readData() throws IOException, FileNotFoundException {
    117         BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(PROJECTION_DATA_FILE), Utils.UTF_8));
    118         List<TestData> result = new ArrayList<>();
    119         String line;
    120         while ((line = in.readLine()) != null) {
    121             if (line.startsWith("#")) {
    122                 continue;
    123             }
    124             TestData next = new TestData();
    125 
    126             Pair<Double,Double> ll = readLine("ll", in.readLine());
    127             Pair<Double,Double> en = readLine("en", in.readLine());
    128             Pair<Double,Double> ll2 = readLine("ll2", in.readLine());
    129 
    130             next.code = line;
    131             next.ll = new LatLon(ll.a, ll.b);
    132             next.en = new EastNorth(en.a, en.b);
    133             next.ll2 = new LatLon(ll2.a, ll2.b);
    134 
    135             result.add(next);
    136         }
    137         in.close();
    138         return result;
     114        try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(PROJECTION_DATA_FILE), Utils.UTF_8))) {
     115            List<TestData> result = new ArrayList<>();
     116            String line;
     117            while ((line = in.readLine()) != null) {
     118                if (line.startsWith("#")) {
     119                    continue;
     120                }
     121                TestData next = new TestData();
     122   
     123                Pair<Double,Double> ll = readLine("ll", in.readLine());
     124                Pair<Double,Double> en = readLine("en", in.readLine());
     125                Pair<Double,Double> ll2 = readLine("ll2", in.readLine());
     126   
     127                next.code = line;
     128                next.ll = new LatLon(ll.a, ll.b);
     129                next.en = new EastNorth(en.a, en.b);
     130                next.ll2 = new LatLon(ll2.a, ll2.b);
     131   
     132                result.add(next);
     133            }
     134            return result;
     135        }
    139136    }
    140137
  • trunk/test/unit/org/openstreetmap/josm/tools/UtilsTest.java

    r6920 r7030  
    7979    public void testOpenUrlGzip() throws Exception {
    8080        Main.initApplicationPreferences();
    81         final BufferedReader x = Utils.openURLReaderAndDecompress(new URL("https://www.openstreetmap.org/trace/1613906/data"), true);
    82         Assert.assertTrue(x.readLine().startsWith("<?xml version="));
    83         x.close();
     81        try (BufferedReader x = Utils.openURLReaderAndDecompress(new URL("https://www.openstreetmap.org/trace/1613906/data"), true)) {
     82            Assert.assertTrue(x.readLine().startsWith("<?xml version="));
     83        }
    8484    }
    8585
     
    8787    public void testOpenUrlBzip() throws Exception {
    8888        Main.initApplicationPreferences();
    89         final BufferedReader x = Utils.openURLReaderAndDecompress(new URL("https://www.openstreetmap.org/trace/785544/data"), true);
    90         Assert.assertTrue(x.readLine().startsWith("<?xml version="));
    91         x.close();
     89        try (BufferedReader x = Utils.openURLReaderAndDecompress(new URL("https://www.openstreetmap.org/trace/785544/data"), true)) {
     90            Assert.assertTrue(x.readLine().startsWith("<?xml version="));
     91        }
    9292    }
    9393
Note: See TracChangeset for help on using the changeset viewer.