Ignore:
Timestamp:
2014-05-01T02:34:43+02:00 (10 years ago)
Author:
Don-vip
Message:

see #8465 - global use of try-with-resources, according to

Location:
trunk/src/org/openstreetmap/josm/data
Files:
11 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/org/openstreetmap/josm/data/AutosaveTask.java

    r7029 r7033  
    157157            try {
    158158                if (result.createNewFile()) {
    159                     try {
    160                         File pidFile = new File(autosaveDir, filename+".pid");
    161                         PrintStream ps = new PrintStream(pidFile, "UTF-8");
     159                    File pidFile = new File(autosaveDir, filename+".pid");
     160                    try (PrintStream ps = new PrintStream(pidFile, "UTF-8")) {
    162161                        ps.println(ManagementFactory.getRuntimeMXBean().getName());
    163                         Utils.close(ps);
    164162                    } catch (Throwable t) {
    165163                        Main.error(t);
     
    305303                File pidFile = getPidFile(file);
    306304                if (pidFile.exists()) {
    307                     try {
    308                         BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(pidFile), Utils.UTF_8));
     305                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(pidFile), Utils.UTF_8))) {
    309306                        try {
    310307                            String jvmId = reader.readLine();
  • trunk/src/org/openstreetmap/josm/data/CustomConfigurator.java

    r7027 r7033  
    427427                String fileDir = file.getParentFile().getAbsolutePath();
    428428                if (fileDir!=null) engine.eval("scriptDir='"+normalizeDirName(fileDir) +"';");
    429                 openAndReadXML(new BufferedInputStream(new FileInputStream(file)));
     429                try (InputStream is = new BufferedInputStream(new FileInputStream(file))) {
     430                    openAndReadXML(is);
     431                }
    430432            } catch (Exception ex) {
    431433                log("Error reading custom preferences: " + ex.getMessage());
     
    445447            } catch (Exception ex) {
    446448                log("Error reading custom preferences: "+ex.getMessage());
    447             } finally {
    448                 Utils.close(is);
    449449            }
    450450            log("-- Reading complete --");
     
    460460                engine.eval("homeDir='"+normalizeDirName(Main.pref.getPreferencesDir()) +"';");
    461461                engine.eval("josmVersion="+Version.getInstance().getVersion()+";");
    462                 String className =  CustomConfigurator.class.getName();
     462                String className = CustomConfigurator.class.getName();
    463463                engine.eval("API.messageBox="+className+".messageBox");
    464464                engine.eval("API.askText=function(text) { return String("+className+".askForText(text));}");
  • trunk/src/org/openstreetmap/josm/data/Preferences.java

    r7027 r7033  
    1111import java.io.FileOutputStream;
    1212import java.io.IOException;
     13import java.io.InputStream;
    1314import java.io.InputStreamReader;
    1415import java.io.OutputStreamWriter;
     
    719720
    720721    /**
    721      * Called after every put. In case of a problem, do nothing but output the error
    722      * in log.
     722     * Called after every put. In case of a problem, do nothing but output the error in log.
    723723     */
    724724    public void save() throws IOException {
     
    736736        }
    737737
    738         final PrintWriter out = new PrintWriter(new OutputStreamWriter(
    739                 new FileOutputStream(prefFile + "_tmp"), Utils.UTF_8), false);
    740         out.print(toXML(false));
    741         Utils.close(out);
     738        try (PrintWriter out = new PrintWriter(new OutputStreamWriter(
     739                new FileOutputStream(prefFile + "_tmp"), Utils.UTF_8), false)) {
     740            out.print(toXML(false));
     741        }
    742742
    743743        File tmpFile = new File(prefFile + "_tmp");
     
    748748        setCorrectPermissions(backupFile);
    749749    }
    750 
    751750
    752751    private void setCorrectPermissions(File file) {
     
    761760        settingsMap.clear();
    762761        File pref = getPreferenceFile();
    763         BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(pref), Utils.UTF_8));
    764         try {
     762        try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(pref), Utils.UTF_8))) {
    765763            validateXML(in);
    766             Utils.close(in);
    767             in = new BufferedReader(new InputStreamReader(new FileInputStream(pref), Utils.UTF_8));
     764        }
     765        try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(pref), Utils.UTF_8))) {
    768766            fromXML(in);
    769         } finally {
    770             Utils.close(in);
    771767        }
    772768        updateSystemProperties();
     
    13591355    public void validateXML(Reader in) throws Exception {
    13601356        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    1361         Schema schema = factory.newSchema(new StreamSource(new MirroredInputStream("resource://data/preferences.xsd")));
    1362         Validator validator = schema.newValidator();
    1363         validator.validate(new StreamSource(in));
     1357        try (InputStream xsdStream = new MirroredInputStream("resource://data/preferences.xsd")) {
     1358            Schema schema = factory.newSchema(new StreamSource(xsdStream));
     1359            Validator validator = schema.newValidator();
     1360            validator.validate(new StreamSource(in));
     1361        }
    13641362    }
    13651363
  • trunk/src/org/openstreetmap/josm/data/Version.java

    r7005 r7033  
    3838        String s = null;
    3939        try {
    40             BufferedReader in = Utils.openURLReader(resource);
    4140            StringBuilder sb = new StringBuilder();
    42             try {
     41            try (BufferedReader in = Utils.openURLReader(resource)) {
    4342                for (String line = in.readLine(); line != null; line = in.readLine()) {
    4443                    sb.append(line).append("\n");
    4544                }
    46             } finally {
    47                 Utils.close(in);
    4845            }
    4946            s = sb.toString();
  • trunk/src/org/openstreetmap/josm/data/imagery/WmsCache.java

    r7028 r7033  
    111111    private String getCacheDirectory(String url) {
    112112        String cacheDirName = null;
    113         InputStream fis = null;
    114         OutputStream fos = null;
    115         try {
    116             Properties layersIndex = new Properties();
    117             File layerIndexFile = new File(cacheDirPath(), LAYERS_INDEX_FILENAME);
    118             try {
    119                 fis = new FileInputStream(layerIndexFile);
    120                 layersIndex.load(fis);
    121             } catch (FileNotFoundException e) {
    122                 Main.error("Unable to load layers index for wms cache (file " + layerIndexFile + " not found)");
     113        Properties layersIndex = new Properties();
     114        File layerIndexFile = new File(cacheDirPath(), LAYERS_INDEX_FILENAME);
     115        try (InputStream fis = new FileInputStream(layerIndexFile)) {
     116            layersIndex.load(fis);
     117        } catch (FileNotFoundException e) {
     118            Main.error("Unable to load layers index for wms cache (file " + layerIndexFile + " not found)");
     119        } catch (IOException e) {
     120            Main.error("Unable to load layers index for wms cache");
     121            Main.error(e);
     122        }
     123
     124        for (Object propKey: layersIndex.keySet()) {
     125            String s = (String)propKey;
     126            if (url.equals(layersIndex.getProperty(s))) {
     127                cacheDirName = s;
     128                break;
     129            }
     130        }
     131
     132        if (cacheDirName == null) {
     133            int counter = 0;
     134            while (true) {
     135                counter++;
     136                if (!layersIndex.keySet().contains(String.valueOf(counter))) {
     137                    break;
     138                }
     139            }
     140            cacheDirName = String.valueOf(counter);
     141            layersIndex.setProperty(cacheDirName, url);
     142            try (OutputStream fos = new FileOutputStream(layerIndexFile)) {
     143                layersIndex.store(fos, "");
    123144            } catch (IOException e) {
    124                 Main.error("Unable to load layers index for wms cache");
     145                Main.error("Unable to save layer index for wms cache");
    125146                Main.error(e);
    126147            }
    127 
    128             for (Object propKey: layersIndex.keySet()) {
    129                 String s = (String)propKey;
    130                 if (url.equals(layersIndex.getProperty(s))) {
    131                     cacheDirName = s;
    132                     break;
    133                 }
    134             }
    135 
    136             if (cacheDirName == null) {
    137                 int counter = 0;
    138                 while (true) {
    139                     counter++;
    140                     if (!layersIndex.keySet().contains(String.valueOf(counter))) {
    141                         break;
    142                     }
    143                 }
    144                 cacheDirName = String.valueOf(counter);
    145                 layersIndex.setProperty(cacheDirName, url);
    146                 try {
    147                     fos = new FileOutputStream(layerIndexFile);
    148                     layersIndex.store(fos, "");
    149                 } catch (IOException e) {
    150                     Main.error("Unable to save layer index for wms cache");
    151                     Main.error(e);
    152                 }
    153             }
    154         } finally {
    155             Utils.close(fos);
    156             Utils.close(fis);
    157148        }
    158149
     
    181172                    WmsCacheType.class.getClassLoader());
    182173            Unmarshaller unmarshaller = context.createUnmarshaller();
    183             WmsCacheType cacheEntries = (WmsCacheType)unmarshaller.unmarshal(new FileInputStream(indexFile));
     174            WmsCacheType cacheEntries;
     175            try (InputStream is = new FileInputStream(indexFile)) {
     176                cacheEntries = (WmsCacheType)unmarshaller.unmarshal(is);
     177            }
    184178            totalFileSize = cacheEntries.getTotalFileSize();
    185179            if (cacheEntries.getTileSize() != tileSize) {
     
    292286                    WmsCacheType.class.getClassLoader());
    293287            Marshaller marshaller = context.createMarshaller();
    294             marshaller.marshal(index, new FileOutputStream(new File(cacheDir, INDEX_FILENAME)));
     288            try (OutputStream fos = new FileOutputStream(new File(cacheDir, INDEX_FILENAME))) {
     289                marshaller.marshal(index, fos);
     290            }
    295291        } catch (Exception e) {
    296292            Main.error("Failed to save wms-cache file");
     
    302298        return new File(cacheDir, projection.cacheDirectory + "/" + entry.filename);
    303299    }
    304 
    305300
    306301    private BufferedImage loadImage(ProjectionEntries projectionEntries, CacheEntry entry) throws IOException {
     
    524519            totalFileSize += imageFile.length();
    525520        } else {
    526             OutputStream os = new BufferedOutputStream(new FileOutputStream(imageFile));
    527             try {
     521            try (OutputStream os = new BufferedOutputStream(new FileOutputStream(imageFile))) {
    528522                totalFileSize += Utils.copyStream(imageData, os);
    529             } finally {
    530                 Utils.close(os);
    531523            }
    532524        }
  • trunk/src/org/openstreetmap/josm/data/projection/Projections.java

    r7005 r7033  
    132132    private static void loadInits() {
    133133        Pattern epsgPattern = Pattern.compile("<(\\d+)>(.*)<>");
    134         BufferedReader r = null;
    135         try {
     134        try (
    136135            InputStream in = new MirroredInputStream("resource://data/projection/epsg");
    137             r = new BufferedReader(new InputStreamReader(in, Utils.UTF_8));
     136            BufferedReader r = new BufferedReader(new InputStreamReader(in, Utils.UTF_8));
     137        ) {
    138138            String line, lastline = "";
    139139            while ((line = r.readLine()) != null) {
    140140                line = line.trim();
    141141                if (!line.startsWith("#") && !line.isEmpty()) {
    142                     if (!lastline.startsWith("#")) throw new AssertionError();
     142                    if (!lastline.startsWith("#")) throw new AssertionError("EPSG file seems corrupted");
    143143                    String name = lastline.substring(1).trim();
    144144                    Matcher m = epsgPattern.matcher(line);
     
    153153        } catch (IOException ex) {
    154154            throw new RuntimeException(ex);
    155         } finally {
    156             Utils.close(r);
    157155        }
    158156    }
  • trunk/src/org/openstreetmap/josm/data/projection/datum/NTV2GridShiftFileWrapper.java

    r6883 r7033  
    4848    public NTV2GridShiftFile getShiftFile() {
    4949        if (instance == null) {
    50             try {
    51                 InputStream is = new MirroredInputStream(gridFileName);
     50            try (InputStream is = new MirroredInputStream(gridFileName)) {
    5251                instance = new NTV2GridShiftFile();
    5352                instance.loadGridShiftFile(is, false);
     
    5857        return instance;
    5958    }
    60 
    6159}
  • trunk/src/org/openstreetmap/josm/data/validation/OsmValidator.java

    r7005 r7033  
    171171            File file = new File(getValidatorDir() + "ignorederrors");
    172172            if (file.exists()) {
    173                 BufferedReader in = null;
    174                 try {
    175                     in = new BufferedReader(new InputStreamReader(new FileInputStream(file), Utils.UTF_8));
     173                try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), Utils.UTF_8))) {
    176174                    for (String line = in.readLine(); line != null; line = in.readLine()) {
    177175                        ignoredErrors.add(line);
     
    181179                } catch (final IOException e) {
    182180                    Main.error(e);
    183                 } finally {
    184                     Utils.close(in);
    185181                }
    186182            }
     
    197193
    198194    public static void saveIgnoredErrors() {
    199         PrintWriter out = null;
    200         try {
    201             out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(getValidatorDir() + "ignorederrors"), Utils.UTF_8), false);
     195        try (PrintWriter out = new PrintWriter(new OutputStreamWriter(
     196                new FileOutputStream(getValidatorDir() + "ignorederrors"), Utils.UTF_8), false)) {
    202197            for (String e : ignoredErrors) {
    203198                out.println(e);
     
    205200        } catch (IOException e) {
    206201            Main.error(e);
    207         } finally {
    208             Utils.close(out);
    209202        }
    210203    }
  • trunk/src/org/openstreetmap/josm/data/validation/tests/MapCSSTagChecker.java

    r7027 r7033  
    453453                    Main.info(tr("Adding {0} to tag checker", i));
    454454                }
    455                 MirroredInputStream s = new MirroredInputStream(i);
    456                 try {
     455                try (MirroredInputStream s = new MirroredInputStream(i)) {
    457456                    addMapCSS(new BufferedReader(UTFInputStreamReader.create(s)));
    458                 } finally {
    459                     Utils.close(s);
    460457                }
    461458            } catch (IOException ex) {
  • trunk/src/org/openstreetmap/josm/data/validation/tests/OpeningHourTest.java

    r7005 r7033  
    55
    66import java.io.InputStreamReader;
     7import java.io.Reader;
    78import java.util.ArrayList;
    89import java.util.Arrays;
     
    5152        super.initialize();
    5253        if (ENGINE != null) {
    53             ENGINE.eval(new InputStreamReader(new MirroredInputStream("resource://data/validator/opening_hours.js"), Utils.UTF_8));
    54             // fake country/state to not get errors on holidays
    55             ENGINE.eval("var nominatimJSON = {address: {state: 'Bayern', country_code: 'de'}};");
    56             ENGINE.eval(
    57                     "var oh = function (value, mode) {" +
    58                     " try {" +
    59                     "    var r= new opening_hours(value, nominatimJSON, mode);" +
    60                     "    r.getErrors = function() {return [];};" +
    61                     "    return r;" +
    62                     "  } catch(err) {" +
    63                     "    return {" +
    64                     "      getWarnings: function() {return [];}," +
    65                     "      getErrors: function() {return [err.toString()]}" +
    66                     "    };" +
    67                     "  }" +
    68                     "};");
     54            try (Reader reader = new InputStreamReader(
     55                    new MirroredInputStream("resource://data/validator/opening_hours.js"), Utils.UTF_8)) {
     56                ENGINE.eval(reader);
     57                // fake country/state to not get errors on holidays
     58                ENGINE.eval("var nominatimJSON = {address: {state: 'Bayern', country_code: 'de'}};");
     59                ENGINE.eval(
     60                        "var oh = function (value, mode) {" +
     61                        " try {" +
     62                        "    var r= new opening_hours(value, nominatimJSON, mode);" +
     63                        "    r.getErrors = function() {return [];};" +
     64                        "    return r;" +
     65                        "  } catch(err) {" +
     66                        "    return {" +
     67                        "      getWarnings: function() {return [];}," +
     68                        "      getErrors: function() {return [err.toString()]}" +
     69                        "    };" +
     70                        "  }" +
     71                        "};");
     72            }
    6973        } else {
    7074            Main.warn("Unable to initialize OpeningHourTest because no JavaScript engine has been found");
  • trunk/src/org/openstreetmap/josm/data/validation/tests/TagChecker.java

    r7025 r7033  
    5454import org.openstreetmap.josm.tools.GBC;
    5555import org.openstreetmap.josm.tools.MultiMap;
    56 import org.openstreetmap.josm.tools.Utils;
    5756
    5857/**
     
    165164        String errorSources = "";
    166165        for (String source : Main.pref.getCollection(PREF_SOURCES, DEFAULT_SOURCES)) {
    167             BufferedReader reader = null;
    168             try {
     166            try (
    169167                MirroredInputStream s = new MirroredInputStream(source);
    170                 reader = new BufferedReader(UTFInputStreamReader.create(s));
    171 
     168                BufferedReader reader = new BufferedReader(UTFInputStreamReader.create(s));
     169            ) {
    172170                String okValue = null;
    173171                boolean tagcheckerfile = false;
     
    242240            } catch (IOException e) {
    243241                errorSources += source + "\n";
    244             } finally {
    245                 Utils.close(reader);
    246242            }
    247243        }
Note: See TracChangeset for help on using the changeset viewer.