Changeset 7033 in josm


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
Files:
79 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/org/openstreetmap/josm/actions/ImageryAdjustAction.java

    r6890 r7033  
    1717import java.awt.event.MouseListener;
    1818import java.awt.event.MouseMotionListener;
     19import java.util.Formatter;
     20import java.util.Locale;
    1921
    2022import javax.swing.JLabel;
     
    236238            int precision = Main.getProjection().getDefaultZoomInPPD() >= 1.0 ? 2 : 7;
    237239            // US locale to force decimal separator to be '.'
    238             tOffset.setText(new java.util.Formatter(java.util.Locale.US).format(
     240            try (Formatter us = new Formatter(Locale.US)) {
     241                tOffset.setText(us.format(
    239242                    "%1." + precision + "f; %1." + precision + "f",
    240243                    layer.getDx(), layer.getDy()).toString());
     244            }
    241245        }
    242246
  • trunk/src/org/openstreetmap/josm/actions/OpenFileAction.java

    r7026 r7033  
    292292
    293293                for (File urlFile: urlFiles) {
    294                     try {
    295                         BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(urlFile), Utils.UTF_8));
     294                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(urlFile), Utils.UTF_8))) {
    296295                        String line;
    297296                        while ((line = reader.readLine()) != null) {
  • trunk/src/org/openstreetmap/josm/actions/SessionLoadAction.java

    r7004 r7033  
    153153                        file = File.createTempFile("session_", ".joz", Utils.getJosmTempDir());
    154154                        tempFile = true;
    155                         FileOutputStream out = new FileOutputStream(file);
    156                         try {
     155                        try (FileOutputStream out = new FileOutputStream(file)) {
    157156                            Utils.copyStream(is, out);
    158                         } finally {
    159                             Utils.close(out);
    160157                        }
    161158                    }
  • 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        }
  • trunk/src/org/openstreetmap/josm/gui/MainApplication.java

    r7005 r7033  
    1313import java.awt.event.WindowEvent;
    1414import java.io.File;
     15import java.io.InputStream;
    1516import java.net.Authenticator;
    1617import java.net.ProxySelector;
     
    339340            for (String i : args.get(Option.LOAD_PREFERENCES)) {
    340341                info("Reading preferences from " + i);
    341                 try {
    342                     config.openAndReadXML(Utils.openURL(new URL(i)));
     342                try (InputStream is = Utils.openURL(new URL(i))) {
     343                    config.openAndReadXML(is);
    343344                } catch (Exception ex) {
    344345                    throw new RuntimeException(ex);
  • trunk/src/org/openstreetmap/josm/gui/dialogs/MapPaintDialog.java

    r7030 r7033  
    2424import java.io.InputStream;
    2525import java.io.InputStreamReader;
     26import java.io.OutputStream;
    2627import java.util.ArrayList;
    2728import java.util.Arrays;
     
    516517                getProgressMonitor().indeterminateSubTask(
    517518                        tr("Save style ''{0}'' as ''{1}''", s.getDisplayString(), file.getPath()));
    518                 BufferedInputStream bis = null;
    519                 BufferedOutputStream bos = null;
    520519                try {
    521520                    InputStream in = s.getSourceInputStream();
    522                     try {
    523                         bis = new BufferedInputStream(in);
    524                         bos = new BufferedOutputStream(new FileOutputStream(file));
     521                    try (
     522                        InputStream bis = new BufferedInputStream(in);
     523                        OutputStream bos = new BufferedOutputStream(new FileOutputStream(file))
     524                    ) {
    525525                        byte[] buffer = new byte[4096];
    526526                        int length;
     
    533533                } catch (IOException e) {
    534534                    error = true;
    535                 } finally {
    536                     Utils.close(bis);
    537                     Utils.close(bos);
    538535                }
    539536            }
  • trunk/src/org/openstreetmap/josm/gui/download/PlaceSelection.java

    r7017 r7033  
    1515import java.io.InputStream;
    1616import java.io.InputStreamReader;
     17import java.io.Reader;
    1718import java.net.HttpURLConnection;
    1819import java.net.URL;
     
    368369                }
    369370                connection.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
    370                 InputStream inputStream = connection.getInputStream();
    371                 InputSource inputSource = new InputSource(new InputStreamReader(inputStream, Utils.UTF_8));
    372                 NameFinderResultParser parser = new NameFinderResultParser();
    373                 SAXParserFactory.newInstance().newSAXParser().parse(inputSource, parser);
    374                 this.data = parser.getResult();
     371                try (
     372                    InputStream inputStream = connection.getInputStream();
     373                    Reader reader = new InputStreamReader(inputStream, Utils.UTF_8);
     374                ) {
     375                    InputSource inputSource = new InputSource(reader);
     376                    NameFinderResultParser parser = new NameFinderResultParser();
     377                    SAXParserFactory.newInstance().newSAXParser().parse(inputSource, parser);
     378                    this.data = parser.getResult();
     379                }
    375380            } catch(Exception e) {
    376381                if (canceled)
  • trunk/src/org/openstreetmap/josm/gui/help/HelpBrowser.java

    r6995 r7033  
    135135    protected StyleSheet buildStyleSheet() {
    136136        StyleSheet ss = new StyleSheet();
    137         BufferedReader reader = new BufferedReader(
     137        StringBuilder css = new StringBuilder();
     138        try (BufferedReader reader = new BufferedReader(
    138139                new InputStreamReader(
    139                         getClass().getResourceAsStream("/data/help-browser.css"),
    140                         Utils.UTF_8
     140                        getClass().getResourceAsStream("/data/help-browser.css"), Utils.UTF_8
    141141                )
    142         );
    143         StringBuilder css = new StringBuilder();
    144         try {
     142        )) {
    145143            String line = null;
    146144            while ((line = reader.readLine()) != null) {
     
    148146                css.append("\n");
    149147            }
    150         } catch(Exception e) {
     148        } catch (Exception e) {
    151149            Main.error(tr("Failed to read CSS file ''help-browser.css''. Exception is: {0}", e.toString()));
    152150            Main.error(e);
    153151            return ss;
    154         } finally {
    155             Utils.close(reader);
    156152        }
    157153        ss.addRule(css.toString());
  • trunk/src/org/openstreetmap/josm/gui/io/DownloadFileTask.java

    r6643 r7033  
    8383     */
    8484    public void download() throws DownloadException {
    85         OutputStream out = null;
    86         InputStream in = null;
    8785        try {
    8886            if (mkdir) {
     
    105103            progressMonitor.subTask(tr("Downloading File {0}: {1} bytes...", file.getName(),size));
    106104
    107             in = downloadConnection.getInputStream();
    108             out = new FileOutputStream(file);
    109             byte[] buffer = new byte[32768];
    110             int count=0;
    111             int p1=0, p2=0;
    112             for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
    113                 out.write(buffer, 0, read);
    114                 count+=read;
    115                 if (canceled) break;
    116                 p2 = 100 * count / size;
    117                 if (p2!=p1) {
    118                     progressMonitor.setTicks(p2);
    119                     p1=p2;
     105            try (
     106                InputStream in = downloadConnection.getInputStream();
     107                OutputStream out = new FileOutputStream(file)
     108            ) {
     109                byte[] buffer = new byte[32768];
     110                int count=0;
     111                int p1=0, p2=0;
     112                for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
     113                    out.write(buffer, 0, read);
     114                    count+=read;
     115                    if (canceled) break;
     116                    p2 = 100 * count / size;
     117                    if (p2!=p1) {
     118                        progressMonitor.setTicks(p2);
     119                        p1=p2;
     120                    }
    120121                }
    121122            }
    122             Utils.close(out);
    123123            if (!canceled) {
    124124                Main.info(tr("Download finished"));
     
    139139        } finally {
    140140            closeConnectionIfNeeded();
    141             Utils.close(out);
    142141        }
    143142    }
     
    170169     */
    171170    public static void unzipFileRecursively(File file, String dir) throws IOException {
    172         OutputStream os = null;
    173         InputStream is = null;
    174         ZipFile zf = null;
    175         try {
    176             zf = new ZipFile(file);
    177             Enumeration<?> es = zf.entries();
    178             ZipEntry ze;
     171        try (ZipFile zf = new ZipFile(file)) {
     172            Enumeration<? extends ZipEntry> es = zf.entries();
    179173            while (es.hasMoreElements()) {
    180                 ze = (ZipEntry) es.nextElement();
     174                ZipEntry ze = es.nextElement();
    181175                File newFile = new File(dir, ze.getName());
    182176                if (ze.isDirectory()) {
    183177                    newFile.mkdirs();
    184                 } else {
    185                     is = zf.getInputStream(ze);
    186                     os = new BufferedOutputStream(new FileOutputStream(newFile));
     178                } else try (
     179                    InputStream is = zf.getInputStream(ze);
     180                    OutputStream os = new BufferedOutputStream(new FileOutputStream(newFile))
     181                ) {
    187182                    byte[] buffer = new byte[8192];
    188183                    int read;
     
    190185                        os.write(buffer, 0, read);
    191186                    }
    192                     Utils.close(os);
    193                     Utils.close(is);
    194187                }
    195188            }
    196         } finally {
    197             Utils.close(zf);
    198189        }
    199190    }
    200191}
    201 
  • trunk/src/org/openstreetmap/josm/gui/layer/TMSLayer.java

    r7024 r7033  
    326326            protected byte[] updateData() throws IOException {
    327327                URL u = getAttributionUrl();
    328                 UTFInputStreamReader in = UTFInputStreamReader.create(Utils.openURL(u));
    329                 String r = new Scanner(in).useDelimiter("\\A").next();
    330                 Utils.close(in);
    331                 Main.info("Successfully loaded Bing attribution data.");
    332                 return r.getBytes("utf-8");
     328                try (Scanner scanner = new Scanner(UTFInputStreamReader.create(Utils.openURL(u)))) {
     329                    String r = scanner.useDelimiter("\\A").next();
     330                    Main.info("Successfully loaded Bing attribution data.");
     331                    return r.getBytes("UTF-8");
     332                }
    333333            }
    334334        }
  • trunk/src/org/openstreetmap/josm/gui/layer/geoimage/CorrelateGpxWithImages.java

    r7025 r7033  
    2121import java.io.File;
    2222import java.io.FileInputStream;
     23import java.io.FileNotFoundException;
    2324import java.io.IOException;
    2425import java.io.InputStream;
     
    171172                }
    172173                GpxData data = null;
    173                 try {
    174                     InputStream iStream;
    175                     if (sel.getName().toLowerCase().endsWith(".gpx.gz")) {
    176                         iStream = new GZIPInputStream(new FileInputStream(sel));
    177                     } else {
    178                         iStream = new FileInputStream(sel);
    179                     }
     174                try (InputStream iStream = createInputStream(sel)) {
    180175                    GpxReader reader = new GpxReader(iStream);
    181176                    reader.parse(false);
     
    211206            } finally {
    212207                outerPanel.setCursor(Cursor.getDefaultCursor());
     208            }
     209        }
     210
     211        private InputStream createInputStream(File sel) throws IOException, FileNotFoundException {
     212            if (sel.getName().toLowerCase().endsWith(".gpx.gz")) {
     213                return new GZIPInputStream(new FileInputStream(sel));
     214            } else {
     215                return new FileInputStream(sel);
    213216            }
    214217        }
  • trunk/src/org/openstreetmap/josm/gui/mappaint/mapcss/MapCSSStyleSource.java

    r7005 r7033  
    7575        init();
    7676        rules.clear();
    77         try {
    78             InputStream in = getSourceInputStream();
     77        try (InputStream in = getSourceInputStream()) {
    7978            try {
    8079                // evaluate @media { ... } blocks
  • trunk/src/org/openstreetmap/josm/gui/mappaint/xml/XmlStyleSource.java

    r7005 r7033  
    7575        init();
    7676        try {
    77             InputStream in = getSourceInputStream();
    78             try {
    79                 InputStreamReader reader = new InputStreamReader(in, Utils.UTF_8);
     77            try (
     78                InputStream in = getSourceInputStream();
     79                InputStreamReader reader = new InputStreamReader(in, Utils.UTF_8)
     80            ) {
    8081                XmlObjectParser parser = new XmlObjectParser(new XmlStyleSourceHandler(this));
    8182                parser.startWithValidation(reader,
     
    8384                        "resource://data/mappaint-style.xsd");
    8485                while (parser.hasNext());
    85             } finally {
    86                 closeSourceInputStream(in);
    87             }
    88 
     86            }
    8987        } catch (IOException e) {
    9088            Main.warn(tr("Failed to load Mappaint styles from ''{0}''. Exception was: {1}", url, e.toString()));
     
    377375        }
    378376    }
    379 
    380377}
  • trunk/src/org/openstreetmap/josm/gui/tagging/TaggingPresetReader.java

    r7005 r7033  
    225225    public static Collection<TaggingPreset> readAll(String source, boolean validate) throws SAXException, IOException {
    226226        Collection<TaggingPreset> tp;
    227         MirroredInputStream s = new MirroredInputStream(source, null, PRESET_MIME_TYPES);
    228         try {
    229             InputStream zip = s.findZipEntryInputStream("xml","preset");
    230             if(zip != null) {
     227        try (
     228            MirroredInputStream s = new MirroredInputStream(source, null, PRESET_MIME_TYPES);
     229            // zip may be null, but Java 7 allows it: https://blogs.oracle.com/darcy/entry/project_coin_null_try_with
     230            InputStream zip = s.findZipEntryInputStream("xml", "preset")
     231        ) {
     232            if (zip != null) {
    231233                zipIcons = s.getFile();
    232234            }
    233             InputStreamReader r = new InputStreamReader(zip == null ? s : zip, Utils.UTF_8);
    234             try {
     235            try (InputStreamReader r = new InputStreamReader(zip == null ? s : zip, Utils.UTF_8)) {
    235236                tp = readAll(new BufferedReader(r), validate);
    236             } finally {
    237                 Utils.close(r);
    238             }
    239         } finally {
    240             Utils.close(s);
     237            }
    241238        }
    242239        return tp;
  • trunk/src/org/openstreetmap/josm/io/BoundingBoxDownloader.java

    r6474 r7033  
    1212import org.openstreetmap.josm.gui.progress.ProgressMonitor;
    1313import org.openstreetmap.josm.tools.CheckParameterUtil;
    14 import org.openstreetmap.josm.tools.Utils;
    1514import org.xml.sax.SAXException;
    1615
     
    4847        for (int i = 0;!done;++i) {
    4948            progressMonitor.subTask(tr("Downloading points {0} to {1}...", i * 5000, ((i + 1) * 5000)));
    50             InputStream in = getInputStream(url+i, progressMonitor.createSubTaskMonitor(1, true));
    51             if (in == null) {
    52                 break;
     49            try (InputStream in = getInputStream(url+i, progressMonitor.createSubTaskMonitor(1, true))) {
     50                if (in == null) {
     51                    break;
     52                }
     53                progressMonitor.setTicks(0);
     54                GpxReader reader = new GpxReader(in);
     55                gpxParsedProperly = reader.parse(false);
     56                GpxData currentGpx = reader.getGpxData();
     57                if (result == null) {
     58                    result = currentGpx;
     59                } else if (currentGpx.hasTrackPoints()) {
     60                    result.mergeFrom(currentGpx);
     61                } else{
     62                    done = true;
     63                }
    5364            }
    54             progressMonitor.setTicks(0);
    55             GpxReader reader = new GpxReader(in);
    56             gpxParsedProperly = reader.parse(false);
    57             GpxData currentGpx = reader.getGpxData();
    58             if (result == null) {
    59                 result = currentGpx;
    60             } else if (currentGpx.hasTrackPoints()) {
    61                 result.mergeFrom(currentGpx);
    62             } else{
    63                 done = true;
    64             }
    65             Utils.close(in);
    6665            activeConnection = null;
    6766        }
    68         result.fromServer = true;
     67        if (result != null) {
     68            result.fromServer = true;
     69        }
    6970        return result;
    7071    }
     
    113114    public DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException {
    114115        progressMonitor.beginTask(tr("Contacting OSM Server..."), 10);
    115         InputStream in = null;
    116116        try {
    117117            DataSet ds = null;
     
    119119            if (crosses180th) {
    120120                // API 0.6 does not support requests crossing the 180th meridian, so make two requests
    121                 in = getInputStream(getRequestForBbox(lon1, lat1, 180.0, lat2), progressMonitor.createSubTaskMonitor(9, false));
    122                 if (in == null)
    123                     return null;
    124                 ds = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
     121                DataSet ds2 = null;
    125122
    126                 in = getInputStream(getRequestForBbox(-180.0, lat1, lon2, lat2), progressMonitor.createSubTaskMonitor(9, false));
    127                 if (in == null)
    128                     return null;
    129                 DataSet ds2 = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
     123                try (InputStream in = getInputStream(getRequestForBbox(lon1, lat1, 180.0, lat2), progressMonitor.createSubTaskMonitor(9, false))) {
     124                    if (in == null)
     125                        return null;
     126                    ds = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
     127                }
     128
     129                try (InputStream in = getInputStream(getRequestForBbox(-180.0, lat1, lon2, lat2), progressMonitor.createSubTaskMonitor(9, false))) {
     130                    if (in == null)
     131                        return null;
     132                    ds2 = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
     133                }
    130134                if (ds2 == null)
    131135                    return null;
     
    134138            } else {
    135139                // Simple request
    136                 in = getInputStream(getRequestForBbox(lon1, lat1, lon2, lat2), progressMonitor.createSubTaskMonitor(9, false));
    137                 if (in == null)
    138                     return null;
    139                 ds = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
     140                try (InputStream in = getInputStream(getRequestForBbox(lon1, lat1, lon2, lat2), progressMonitor.createSubTaskMonitor(9, false))) {
     141                    if (in == null)
     142                        return null;
     143                    ds = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
     144                }
    140145            }
    141146            return ds;
     
    146151        } finally {
    147152            progressMonitor.finishTask();
    148             Utils.close(in);
    149153            activeConnection = null;
    150154        }
  • trunk/src/org/openstreetmap/josm/io/CacheCustomContent.java

    r7026 r7033  
    145145     */
    146146    private void loadFromDisk() throws T {
    147         BufferedInputStream input = null;
    148         try {
    149             input = new BufferedInputStream(new FileInputStream(path));
     147        try (BufferedInputStream input = new BufferedInputStream(new FileInputStream(path))) {
    150148            this.data = new byte[input.available()];
    151149            input.read(this.data);
    152150        } catch (IOException e) {
    153151            this.data = updateForce();
    154         } finally {
    155             Utils.close(input);
    156152        }
    157153    }
     
    161157     */
    162158    private void saveToDisk() {
    163         BufferedOutputStream output = null;
    164         try {
    165             output = new BufferedOutputStream(new FileOutputStream(path));
     159        try (BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(path))) {
    166160            output.write(this.data);
    167161            output.flush();
    168         } catch(Exception e) {
     162        } catch (IOException e) {
    169163            Main.error(e);
    170         } finally {
    171             Utils.close(output);
    172164        }
    173165    }
  • trunk/src/org/openstreetmap/josm/io/CacheFiles.java

    r7005 r7033  
    114114
    115115            byte[] bytes = new byte[(int) data.length()];
    116             new RandomAccessFile(data, "r").readFully(bytes);
     116            try (RandomAccessFile raf = new RandomAccessFile(data, "r")) {
     117                raf.readFully(bytes);
     118            }
    117119            return bytes;
    118120        } catch (Exception e) {
     
    135137            }
    136138            // rws also updates the file meta-data, i.e. last mod time
    137             RandomAccessFile raf = new RandomAccessFile(f, "rws");
    138             try {
     139            try (RandomAccessFile raf = new RandomAccessFile(f, "rws")) {
    139140                raf.write(data);
    140             } finally {
    141                 Utils.close(raf);
    142141            }
    143142        } catch (Exception e) {
  • trunk/src/org/openstreetmap/josm/io/Compression.java

    r6882 r7033  
    7575     * @throws IOException
    7676     */
     77    @SuppressWarnings("resource")
    7778    public static InputStream getUncompressedFileInputStream(File file) throws IOException {
    7879        return byExtension(file.getName()).getUncompressedInputStream(new FileInputStream(file));
     
    114115     * @throws IOException
    115116     */
     117    @SuppressWarnings("resource")
    116118    public static OutputStream getCompressedFileOutputStream(File file) throws IOException {
    117119        return byExtension(file.getName()).getCompressedOutputStream(new FileOutputStream(file));
  • trunk/src/org/openstreetmap/josm/io/GeoJSONExporter.java

    r6552 r7033  
    2121            "json,geojson", "json", tr("GeoJSON Files") + " (*.json *.geojson)");
    2222
     23    /**
     24     * Constructs a new {@code GeoJSONExporter}.
     25     */
    2326    public GeoJSONExporter() {
    2427        super(FILE_FILTER);
     
    2932        if (layer instanceof OsmDataLayer) {
    3033            String json = new GeoJSONWriter((OsmDataLayer) layer).write();
    31             Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), Utils.UTF_8));
    32             try {
     34            try (Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), Utils.UTF_8))) {
    3335                out.write(json);
    34             } finally {
    35                 Utils.close(out);
    3636            }
    3737        } else {
  • trunk/src/org/openstreetmap/josm/io/GpxImporter.java

    r6798 r7033  
    7676    @Override
    7777    public void importData(File file, ProgressMonitor progressMonitor) throws IOException {
    78         final InputStream is = Compression.getUncompressedFileInputStream(file);
    7978        final String fileName = file.getName();
    8079
    81         try {
     80        try (InputStream is = Compression.getUncompressedFileInputStream(file)) {
    8281            GpxReader r = new GpxReader(is);
    8382            boolean parsedProperly = r.parse(true);
  • trunk/src/org/openstreetmap/josm/io/GpxReader.java

    r7012 r7033  
    507507
    508508    /**
    509      * Parse the input stream and store the result in trackData and markerData
     509     * Constructs a new {@code GpxReader}, which can later parse the input stream
     510     * and store the result in trackData and markerData
    510511     *
    511512     * @param source the source input stream
    512513     * @throws IOException if an IO error occurs, e.g. the input stream is closed.
    513514     */
     515    @SuppressWarnings("resource")
    514516    public GpxReader(InputStream source) throws IOException {
    515517        Reader utf8stream = UTFInputStreamReader.create(source);
  • trunk/src/org/openstreetmap/josm/io/GpxWriter.java

    r6889 r7033  
    1111import java.util.Map;
    1212import java.util.Map.Entry;
     13
     14import javax.xml.XMLConstants;
    1315
    1416import org.openstreetmap.josm.data.Bounds;
     
    6769        out.println("<gpx version=\"1.1\" creator=\"JOSM GPX export\" xmlns=\"http://www.topografix.com/GPX/1/1\"\n" +
    6870                (hasExtensions ? String.format("    xmlns:josm=\"%s\"%n", JOSM_EXTENSIONS_NAMESPACE_URI) : "") +
    69                 "    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" +
     71                "    xmlns:xsi=\""+XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI+"\" \n" +
    7072                "    xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">");
    7173        indent = "  ";
  • trunk/src/org/openstreetmap/josm/io/MirroredInputStream.java

    r7026 r7033  
    1111import java.io.IOException;
    1212import java.io.InputStream;
     13import java.io.OutputStream;
    1314import java.net.HttpURLConnection;
    1415import java.net.MalformedURLException;
     
    184185    }
    185186
     187    @SuppressWarnings("resource")
    186188    private Pair<String, InputStream> findZipEntryImpl(String extension, String namepart) {
    187189        if (file == null)
     
    293295        String localPath = "mirror_" + a;
    294296        destDirFile = new File(destDir, localPath + ".tmp");
    295         BufferedOutputStream bos = null;
    296         BufferedInputStream bis = null;
    297297        try {
    298298            HttpURLConnection con = connectFollowingRedirect(url, httpAccept);
    299             bis = new BufferedInputStream(con.getInputStream());
    300             FileOutputStream fos = new FileOutputStream(destDirFile);
    301             bos = new BufferedOutputStream(fos);
    302             byte[] buffer = new byte[4096];
    303             int length;
    304             while ((length = bis.read(buffer)) > -1) {
    305                 bos.write(buffer, 0, length);
    306             }
    307             Utils.close(bos);
    308             bos = null;
    309             /* close fos as well to be sure! */
    310             Utils.close(fos);
    311             fos = null;
     299            try (
     300                InputStream bis = new BufferedInputStream(con.getInputStream());
     301                OutputStream fos = new FileOutputStream(destDirFile);
     302                OutputStream bos = new BufferedOutputStream(fos)
     303            ) {
     304                byte[] buffer = new byte[4096];
     305                int length;
     306                while ((length = bis.read(buffer)) > -1) {
     307                    bos.write(buffer, 0, length);
     308                }
     309            }
    312310            localFile = new File(destDir, localPath);
    313311            if(Main.platform.rename(destDirFile, localFile)) {
     
    325323                throw e;
    326324            }
    327         } finally {
    328             Utils.close(bis);
    329             Utils.close(bos);
    330325        }
    331326
  • trunk/src/org/openstreetmap/josm/io/MultiFetchServerObjectReader.java

    r7005 r7033  
    55import static org.openstreetmap.josm.tools.I18n.trn;
    66
     7import java.io.IOException;
    78import java.io.InputStream;
    89import java.net.HttpURLConnection;
     
    506507        protected FetchResult multiGetIdPackage(OsmPrimitiveType type, Set<Long> pkg, ProgressMonitor progressMonitor) throws OsmTransferException {
    507508            String request = buildRequestString(type, pkg);
    508             final InputStream in = getInputStream(request, NullProgressMonitor.INSTANCE);
    509             if (in == null) return null;
    510             progressMonitor.subTask(tr("Downloading OSM data..."));
    511             try {
    512                 return new FetchResult(OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(pkg.size(), false)), null);
    513             } catch (Exception e) {
    514                 throw new OsmTransferException(e);
    515             }
     509            FetchResult result = null;
     510            try (InputStream in = getInputStream(request, NullProgressMonitor.INSTANCE)) {
     511                if (in == null) return null;
     512                progressMonitor.subTask(tr("Downloading OSM data..."));
     513                try {
     514                    result = new FetchResult(OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(pkg.size(), false)), null);
     515                } catch (Exception e) {
     516                    throw new OsmTransferException(e);
     517                }
     518            } catch (IOException ex) {
     519                Main.warn(ex);
     520            }
     521            return result;
    516522        }
    517523
     
    527533        protected DataSet singleGetId(OsmPrimitiveType type, long id, ProgressMonitor progressMonitor) throws OsmTransferException {
    528534            String request = buildRequestString(type, id);
    529             final InputStream in = getInputStream(request, NullProgressMonitor.INSTANCE);
    530             if (in == null) return null;
    531             progressMonitor.subTask(tr("Downloading OSM data..."));
    532             try {
    533                 return OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
    534             } catch (Exception e) {
    535                 throw new OsmTransferException(e);
    536             }
     535            DataSet result = null;
     536            try (InputStream in = getInputStream(request, NullProgressMonitor.INSTANCE)) {
     537                if (in == null) return null;
     538                progressMonitor.subTask(tr("Downloading OSM data..."));
     539                try {
     540                    result = OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
     541                } catch (Exception e) {
     542                    throw new OsmTransferException(e);
     543                }
     544            } catch (IOException ex) {
     545                Main.warn(ex);
     546            }
     547            return result;
    537548        }
    538549
  • trunk/src/org/openstreetmap/josm/io/NMEAImporter.java

    r6798 r7033  
    77import java.io.FileInputStream;
    88import java.io.IOException;
     9import java.io.InputStream;
    910
    1011import javax.swing.JOptionPane;
     
    3536    public void importData(File file, ProgressMonitor progressMonitor) throws IOException {
    3637        final String fn = file.getName();
    37         final NmeaReader r = new NmeaReader(new FileInputStream(file));
    38         if (r.getNumberOfCoordinates() > 0) {
    39             r.data.storageFile = file;
    40             final GpxLayer gpxLayer = new GpxLayer(r.data, fn, true);
    41             final File fileFinal = file;
    42 
    43             GuiHelper.runInEDT(new Runnable() {
    44                 @Override
    45                 public void run() {
    46                     Main.main.addLayer(gpxLayer);
    47                     if (Main.pref.getBoolean("marker.makeautomarkers", true)) {
    48                         MarkerLayer ml = new MarkerLayer(r.data, tr("Markers from {0}", fn), fileFinal, gpxLayer);
    49                         if (!ml.data.isEmpty()) {
    50                             Main.main.addLayer(ml);
     38        try (InputStream fis = new FileInputStream(file)) {
     39            final NmeaReader r = new NmeaReader(fis);
     40            if (r.getNumberOfCoordinates() > 0) {
     41                r.data.storageFile = file;
     42                final GpxLayer gpxLayer = new GpxLayer(r.data, fn, true);
     43                final File fileFinal = file;
     44   
     45                GuiHelper.runInEDT(new Runnable() {
     46                    @Override
     47                    public void run() {
     48                        Main.main.addLayer(gpxLayer);
     49                        if (Main.pref.getBoolean("marker.makeautomarkers", true)) {
     50                            MarkerLayer ml = new MarkerLayer(r.data, tr("Markers from {0}", fn), fileFinal, gpxLayer);
     51                            if (!ml.data.isEmpty()) {
     52                                Main.main.addLayer(ml);
     53                            }
    5154                        }
    5255                    }
    53                 }
    54             });
     56                });
     57            }
     58            showNmeaInfobox(r.getNumberOfCoordinates() > 0, r);
    5559        }
    56         showNmeaInfobox(r.getNumberOfCoordinates() > 0, r);
    5760    }
    5861
  • trunk/src/org/openstreetmap/josm/io/OsmApi.java

    r7030 r7033  
    290290    private String toXml(IPrimitive o, boolean addBody) {
    291291        StringWriter swriter = new StringWriter();
    292         OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version);
    293         swriter.getBuffer().setLength(0);
    294         osmWriter.setWithBody(addBody);
    295         osmWriter.setChangeset(changeset);
    296         osmWriter.header();
    297         o.accept(osmWriter);
    298         osmWriter.footer();
    299         osmWriter.flush();
     292        try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version)) {
     293            swriter.getBuffer().setLength(0);
     294            osmWriter.setWithBody(addBody);
     295            osmWriter.setChangeset(changeset);
     296            osmWriter.header();
     297            o.accept(osmWriter);
     298            osmWriter.footer();
     299            osmWriter.flush();
     300        } catch (IOException e) {
     301            Main.warn(e);
     302        }
    300303        return swriter.toString();
    301304    }
     
    308311    private String toXml(Changeset s) {
    309312        StringWriter swriter = new StringWriter();
    310         OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version);
    311         swriter.getBuffer().setLength(0);
    312         osmWriter.header();
    313         osmWriter.visit(s);
    314         osmWriter.footer();
    315         osmWriter.flush();
     313        try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version)) {
     314            swriter.getBuffer().setLength(0);
     315            osmWriter.header();
     316            osmWriter.visit(s);
     317            osmWriter.footer();
     318            osmWriter.flush();
     319        } catch (IOException e) {
     320            Main.warn(e);
     321        }
    316322        return swriter.toString();
    317323    }
     
    657663                // If the API returned an error code like 403 forbidden, getInputStream
    658664                // will fail with an IOException.
    659                 InputStream i = null;
    660                 try {
    661                     i = activeConnection.getInputStream();
    662                 } catch (IOException ioe) {
    663                     i = activeConnection.getErrorStream();
    664                 }
     665                InputStream i = getConnectionStream();
    665666                if (i != null) {
    666667                    // the input stream can be null if both the input and the error stream
     
    722723    }
    723724
     725    private InputStream getConnectionStream() {
     726        try {
     727            return activeConnection.getInputStream();
     728        } catch (IOException ioe) {
     729            Main.warn(ioe);
     730            return activeConnection.getErrorStream();
     731        }
     732    }
     733
    724734    /**
    725735     * Replies the API capabilities
  • trunk/src/org/openstreetmap/josm/io/OsmChangesetContentParser.java

    r7012 r7033  
    123123     * @throws IllegalArgumentException if source is {@code null}.
    124124     */
     125    @SuppressWarnings("resource")
    125126    public OsmChangesetContentParser(InputStream source) {
    126127        CheckParameterUtil.ensureParameterNotNull(source, "source");
  • trunk/src/org/openstreetmap/josm/io/OsmChangesetParser.java

    r7012 r7033  
    4141 */
    4242public final class OsmChangesetParser {
    43     private List<Changeset> changesets;
     43    private final List<Changeset> changesets;
    4444
    4545    private OsmChangesetParser() {
     
    219219     * @throws IllegalDataException thrown if the an error was found while parsing the data from the source
    220220     */
     221    @SuppressWarnings("resource")
    221222    public static List<Changeset> parse(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException {
    222223        OsmChangesetParser parser = new OsmChangesetParser();
  • trunk/src/org/openstreetmap/josm/io/OsmExporter.java

    r7029 r7033  
    2323public class OsmExporter extends FileExporter {
    2424
     25    /**
     26     * Constructs a new {@code OsmExporter}.
     27     */
    2528    public OsmExporter() {
    2629        super(OsmImporter.FILE_FILTER);
     
    6770
    6871            // create outputstream and wrap it with gzip or bzip, if necessary
    69             OutputStream out = getOutputStream(file);
    70             Writer writer = new OutputStreamWriter(out, Utils.UTF_8);
    71 
    72             OsmWriter w = OsmWriterFactory.createOsmWriter(new PrintWriter(writer), false, layer.data.getVersion());
    73             layer.data.getReadLock().lock();
    74             try {
    75                 w.writeLayer(layer);
    76             } finally {
    77                 Utils.close(w);
    78                 layer.data.getReadLock().unlock();
     72            try (
     73                OutputStream out = getOutputStream(file);
     74                Writer writer = new OutputStreamWriter(out, Utils.UTF_8);
     75                OsmWriter w = OsmWriterFactory.createOsmWriter(new PrintWriter(writer), false, layer.data.getVersion());
     76            ) {
     77                layer.data.getReadLock().lock();
     78                try {
     79                    w.writeLayer(layer);
     80                } finally {
     81                    layer.data.getReadLock().unlock();
     82                }
    7983            }
    80             // FIXME - how to close?
    8184            if (noBackup || !Main.pref.getBoolean("save.keepbackup", false)) {
    8285                if (tmpFile != null) {
  • trunk/src/org/openstreetmap/josm/io/OsmReader.java

    r7025 r7033  
    587587            progressMonitor.indeterminateSubTask(tr("Parsing OSM data..."));
    588588
    589             InputStreamReader ir = UTFInputStreamReader.create(source);
    590             XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(ir);
    591             setParser(parser);
    592             parse();
     589            try (InputStreamReader ir = UTFInputStreamReader.create(source)) {
     590                XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(ir);
     591                setParser(parser);
     592                parse();
     593            }
    593594            progressMonitor.worked(1);
    594595
  • trunk/src/org/openstreetmap/josm/io/OsmServerBackreferenceReader.java

    r7005 r7033  
    1818import org.openstreetmap.josm.gui.progress.ProgressMonitor;
    1919import org.openstreetmap.josm.tools.CheckParameterUtil;
    20 import org.openstreetmap.josm.tools.Utils;
    2120
    2221/**
     
    131130     */
    132131    protected DataSet getReferringWays(ProgressMonitor progressMonitor) throws OsmTransferException {
    133         InputStream in = null;
    134132        progressMonitor.beginTask(null, 2);
    135133        try {
     
    139137            .append("/").append(id).append("/ways");
    140138
    141             in = getInputStream(sb.toString(), progressMonitor.createSubTaskMonitor(1, true));
    142             if (in == null)
    143                 return null;
    144             progressMonitor.subTask(tr("Downloading referring ways ..."));
    145             return OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, true));
     139            try (InputStream in = getInputStream(sb.toString(), progressMonitor.createSubTaskMonitor(1, true))) {
     140                if (in == null)
     141                    return null;
     142                progressMonitor.subTask(tr("Downloading referring ways ..."));
     143                return OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, true));
     144            }
    146145        } catch(OsmTransferException e) {
    147146            throw e;
     
    152151        } finally {
    153152            progressMonitor.finishTask();
    154             Utils.close(in);
    155153            activeConnection = null;
    156154        }
     
    165163     */
    166164    protected DataSet getReferringRelations(ProgressMonitor progressMonitor) throws OsmTransferException {
    167         InputStream in = null;
    168165        progressMonitor.beginTask(null, 2);
    169166        try {
     
    173170            .append("/").append(id).append("/relations");
    174171
    175             in = getInputStream(sb.toString(), progressMonitor.createSubTaskMonitor(1, true));
    176             if (in == null)
    177                 return null;
    178             progressMonitor.subTask(tr("Downloading referring relations ..."));
    179             return OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, true));
     172            try (InputStream in = getInputStream(sb.toString(), progressMonitor.createSubTaskMonitor(1, true))) {
     173                if (in == null)
     174                    return null;
     175                progressMonitor.subTask(tr("Downloading referring relations ..."));
     176                return OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(1, true));
     177            }
    180178        } catch(OsmTransferException e) {
    181179            throw e;
     
    186184        } finally {
    187185            progressMonitor.finishTask();
    188             Utils.close(in);
    189186            activeConnection = null;
    190187        }
  • trunk/src/org/openstreetmap/josm/io/OsmServerChangesetReader.java

    r7005 r7033  
    55import static org.openstreetmap.josm.tools.I18n.trn;
    66
     7import java.io.IOException;
    78import java.io.InputStream;
    89import java.text.MessageFormat;
     
    1213import java.util.List;
    1314
     15import org.openstreetmap.josm.Main;
    1416import org.openstreetmap.josm.data.osm.Changeset;
    1517import org.openstreetmap.josm.data.osm.ChangesetDataSet;
     
    5355    public List<Changeset> queryChangesets(ChangesetQuery query, ProgressMonitor monitor) throws OsmTransferException {
    5456        CheckParameterUtil.ensureParameterNotNull(query, "query");
     57        List<Changeset> result = null;
    5558        if (monitor == null) {
    5659            monitor = NullProgressMonitor.INSTANCE;
     
    6063            StringBuilder sb = new StringBuilder();
    6164            sb.append("changesets?").append(query.getQueryString());
    62             InputStream in = getInputStream(sb.toString(), monitor.createSubTaskMonitor(1, true));
    63             if (in == null)
    64                 return null;
    65             monitor.indeterminateSubTask(tr("Downloading changesets ..."));
    66             return OsmChangesetParser.parse(in, monitor.createSubTaskMonitor(1, true));
     65            try (InputStream in = getInputStream(sb.toString(), monitor.createSubTaskMonitor(1, true))) {
     66                if (in == null)
     67                    return null;
     68                monitor.indeterminateSubTask(tr("Downloading changesets ..."));
     69                result = OsmChangesetParser.parse(in, monitor.createSubTaskMonitor(1, true));
     70            } catch (IOException e) {
     71                Main.warn(e);
     72            }
    6773        } catch(OsmTransferException e) {
    6874            throw e;
     
    7278            monitor.finishTask();
    7379        }
     80        return result;
    7481    }
    7582
     
    8996            monitor = NullProgressMonitor.INSTANCE;
    9097        }
     98        Changeset result = null;
    9199        try {
    92100            monitor.beginTask(tr("Reading changeset {0} ...",id));
    93101            StringBuilder sb = new StringBuilder();
    94102            sb.append("changeset/").append(id);
    95             InputStream in = getInputStream(sb.toString(), monitor.createSubTaskMonitor(1, true));
    96             if (in == null)
    97                 return null;
    98             monitor.indeterminateSubTask(tr("Downloading changeset {0} ...", id));
    99             List<Changeset> changesets = OsmChangesetParser.parse(in, monitor.createSubTaskMonitor(1, true));
    100             if (changesets == null || changesets.isEmpty())
    101                 return null;
    102             return changesets.get(0);
     103            try (InputStream in = getInputStream(sb.toString(), monitor.createSubTaskMonitor(1, true))) {
     104                if (in == null)
     105                    return null;
     106                monitor.indeterminateSubTask(tr("Downloading changeset {0} ...", id));
     107                List<Changeset> changesets = OsmChangesetParser.parse(in, monitor.createSubTaskMonitor(1, true));
     108                if (changesets == null || changesets.isEmpty())
     109                    return null;
     110                result = changesets.get(0);
     111            } catch (IOException e) {
     112                Main.warn(e);
     113            }
    103114        } catch(OsmTransferException e) {
    104115            throw e;
     
    108119            monitor.finishTask();
    109120        }
     121        return result;
    110122    }
    111123
     
    137149                StringBuilder sb = new StringBuilder();
    138150                sb.append("changeset/").append(id);
    139                 InputStream in = getInputStream(sb.toString(), monitor.createSubTaskMonitor(1, true));
    140                 if (in == null)
    141                     return null;
    142                 monitor.indeterminateSubTask(tr("({0}/{1}) Downloading changeset {2} ...", i, ids.size(), id));
    143                 List<Changeset> changesets = OsmChangesetParser.parse(in, monitor.createSubTaskMonitor(1, true));
    144                 if (changesets == null || changesets.isEmpty()) {
    145                     continue;
     151                try (InputStream in = getInputStream(sb.toString(), monitor.createSubTaskMonitor(1, true))) {
     152                    if (in == null)
     153                        return null;
     154                    monitor.indeterminateSubTask(tr("({0}/{1}) Downloading changeset {2} ...", i, ids.size(), id));
     155                    List<Changeset> changesets = OsmChangesetParser.parse(in, monitor.createSubTaskMonitor(1, true));
     156                    if (changesets == null || changesets.isEmpty()) {
     157                        continue;
     158                    }
     159                    ret.addAll(changesets);
     160                } catch (IOException e) {
     161                    Main.warn(e);
    146162                }
    147                 ret.addAll(changesets);
    148163                monitor.worked(1);
    149164            }
     
    173188            monitor = NullProgressMonitor.INSTANCE;
    174189        }
     190        ChangesetDataSet result = null;
    175191        try {
    176192            monitor.beginTask(tr("Downloading changeset content"));
    177193            StringBuilder sb = new StringBuilder();
    178194            sb.append("changeset/").append(id).append("/download");
    179             InputStream in = getInputStream(sb.toString(), monitor.createSubTaskMonitor(1, true));
    180             if (in == null)
    181                 return null;
    182             monitor.setCustomText(tr("Downloading content for changeset {0} ...", id));
    183             OsmChangesetContentParser parser = new OsmChangesetContentParser(in);
    184             return parser.parse(monitor.createSubTaskMonitor(1, true));
     195            try (InputStream in = getInputStream(sb.toString(), monitor.createSubTaskMonitor(1, true))) {
     196                if (in == null)
     197                    return null;
     198                monitor.setCustomText(tr("Downloading content for changeset {0} ...", id));
     199                OsmChangesetContentParser parser = new OsmChangesetContentParser(in);
     200                result = parser.parse(monitor.createSubTaskMonitor(1, true));
     201            } catch (IOException e) {
     202                Main.warn(e);
     203            }
    185204        } catch(XmlParsingException e) {
    186205            throw new OsmTransferException(e);
     
    188207            monitor.finishTask();
    189208        }
     209        return result;
    190210    }
    191211}
  • trunk/src/org/openstreetmap/josm/io/OsmServerHistoryReader.java

    r6822 r7033  
    1212import org.openstreetmap.josm.gui.progress.ProgressMonitor;
    1313import org.openstreetmap.josm.tools.CheckParameterUtil;
    14 import org.openstreetmap.josm.tools.Utils;
    1514
    1615/**
     
    5655     */
    5756    public HistoryDataSet parseHistory(ProgressMonitor progressMonitor) throws OsmTransferException {
    58         InputStream in = null;
    5957        progressMonitor.beginTask("");
    6058        try {
     
    6462            .append("/").append(id).append("/history");
    6563
    66             in = getInputStream(sb.toString(), progressMonitor.createSubTaskMonitor(1, true));
    67             if (in == null)
    68                 return null;
    69             progressMonitor.indeterminateSubTask(tr("Downloading history..."));
    70             final OsmHistoryReader reader = new OsmHistoryReader(in);
    71             return reader.parse(progressMonitor.createSubTaskMonitor(1, true));
     64            try (InputStream in = getInputStream(sb.toString(), progressMonitor.createSubTaskMonitor(1, true))) {
     65                if (in == null)
     66                    return null;
     67                progressMonitor.indeterminateSubTask(tr("Downloading history..."));
     68                OsmHistoryReader reader = new OsmHistoryReader(in);
     69                return reader.parse(progressMonitor.createSubTaskMonitor(1, true));
     70            }
    7271        } catch(OsmTransferException e) {
    7372            throw e;
     
    7877        } finally {
    7978            progressMonitor.finishTask();
    80             Utils.close(in);
    8179            activeConnection = null;
    8280        }
  • trunk/src/org/openstreetmap/josm/io/OsmServerObjectReader.java

    r6830 r7033  
    1414import org.openstreetmap.josm.gui.progress.ProgressMonitor;
    1515import org.openstreetmap.josm.tools.CheckParameterUtil;
    16 import org.openstreetmap.josm.tools.Utils;
    1716
    1817/**
     
    116115        }
    117116        progressMonitor.beginTask("", 1);
    118         InputStream in = null;
    119117        try {
    120118            progressMonitor.indeterminateSubTask(tr("Downloading OSM data..."));
     
    129127            }
    130128
    131             in = getInputStream(sb.toString(), progressMonitor.createSubTaskMonitor(1, true));
    132             if (in == null)
    133                 return null;
    134             return OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
     129            try (InputStream in = getInputStream(sb.toString(), progressMonitor.createSubTaskMonitor(1, true))) {
     130                if (in == null)
     131                    return null;
     132                return OsmReader.parseDataSet(in, progressMonitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
     133            }
    135134        } catch(OsmTransferException e) {
    136135            if (cancel) return null;
     
    141140        } finally {
    142141            progressMonitor.finishTask();
    143             Utils.close(in);
    144142            activeConnection = null;
    145143        }
  • trunk/src/org/openstreetmap/josm/io/OsmServerReader.java

    r6995 r7033  
    114114     * @throws OsmTransferException thrown if data transfer errors occur
    115115     */
     116    @SuppressWarnings("resource")
    116117    protected InputStream getInputStreamRaw(String urlStr, ProgressMonitor progressMonitor, String reason, boolean uncompressAccordingToContentDisposition) throws OsmTransferException {
    117118        try {
  • trunk/src/org/openstreetmap/josm/io/OsmServerUserInfoReader.java

    r7005 r7033  
    167167            monitor.beginTask("");
    168168            monitor.indeterminateSubTask(tr("Reading user info ..."));
    169             InputStream in = getInputStream("user/details", monitor.createSubTaskMonitor(1, true), reason);
    170             return buildFromXML(
    171                     DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in)
    172             );
     169            try (InputStream in = getInputStream("user/details", monitor.createSubTaskMonitor(1, true), reason)) {
     170                return buildFromXML(
     171                        DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in)
     172                );
     173            }
    173174        } catch(OsmTransferException e) {
    174175            throw e;
  • trunk/src/org/openstreetmap/josm/io/WMSLayerExporter.java

    r6070 r7033  
    1010import org.openstreetmap.josm.gui.layer.WMSLayer;
    1111import org.openstreetmap.josm.tools.CheckParameterUtil;
    12 import org.openstreetmap.josm.tools.Utils;
    1312
    1413/**
     
    3130        CheckParameterUtil.ensureParameterNotNull(layer, "layer");
    3231        if (layer instanceof WMSLayer) {
    33             ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
    34             try {
     32            try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
    3533                ((WMSLayer)layer).writeExternal(oos);
    36             } finally {
    37                 Utils.close(oos);
    3834            }
    3935        }
  • trunk/src/org/openstreetmap/josm/io/WMSLayerImporter.java

    r6070 r7033  
    1515import org.openstreetmap.josm.gui.util.GuiHelper;
    1616import org.openstreetmap.josm.tools.CheckParameterUtil;
    17 import org.openstreetmap.josm.tools.Utils;
    1817
    1918/**
     
    5049    public void importData(File file, ProgressMonitor progressMonitor) throws IOException, IllegalDataException {
    5150        CheckParameterUtil.ensureParameterNotNull(file, "file");
    52         ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
    53         try {
     51        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
    5452            wmsLayer.readExternal(ois);
    5553        } catch (ClassNotFoundException e) {
    5654            throw new IllegalDataException(e);
    57         } finally {
    58             Utils.close(ois);
    5955        }
    6056
  • trunk/src/org/openstreetmap/josm/io/imagery/ImageryReader.java

    r7012 r7033  
    5151            SAXParserFactory factory = SAXParserFactory.newInstance();
    5252            factory.setNamespaceAware(true);
    53             InputStream in = new MirroredInputStream(source);
    54             InputSource is = new InputSource(UTFInputStreamReader.create(in));
    55             factory.newSAXParser().parse(is, parser);
    56             return parser.entries;
     53            try (InputStream in = new MirroredInputStream(source)) {
     54                InputSource is = new InputSource(UTFInputStreamReader.create(in));
     55                factory.newSAXParser().parse(is, parser);
     56                return parser.entries;
     57            }
    5758        } catch (SAXException e) {
    5859            throw e;
  • trunk/src/org/openstreetmap/josm/io/imagery/WMSGrabber.java

    r7012 r7033  
    173173
    174174        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    175         InputStream is = new ProgressInputStream(conn, null);
    176         try {
     175        try (InputStream is = new ProgressInputStream(conn, null)) {
    177176            Utils.copyStream(is, baos);
    178         } finally {
    179             Utils.close(is);
    180177        }
    181178
     
    190187        StringBuilder exception = new StringBuilder();
    191188        InputStream in = conn.getInputStream();
    192         BufferedReader br = new BufferedReader(new InputStreamReader(in, Utils.UTF_8));
    193         try {
     189        try (BufferedReader br = new BufferedReader(new InputStreamReader(in, Utils.UTF_8))) {
    194190            String line = null;
    195191            while( (line = br.readLine()) != null) {
     
    199195            }
    200196            return exception.toString();
    201         } finally {
    202             Utils.close(br);
    203197        }
    204198    }
  • trunk/src/org/openstreetmap/josm/io/imagery/WMSImagery.java

    r7030 r7033  
    140140        Main.info("GET " + getCapabilitiesUrl.toString());
    141141        URLConnection openConnection = Utils.openHttpConnection(getCapabilitiesUrl);
    142         InputStream inputStream = openConnection.getInputStream();
    143142        StringBuilder ba = new StringBuilder();
    144         try (BufferedReader br = new BufferedReader(UTFInputStreamReader.create(inputStream))) {
     143       
     144        try (
     145            InputStream inputStream = openConnection.getInputStream();
     146            BufferedReader br = new BufferedReader(UTFInputStreamReader.create(inputStream))
     147        ) {
    145148            String line;
    146149            while ((line = br.readLine()) != null) {
     
    178181                            return x.getTextContent();
    179182                        }
    180                     }
    181                     ), new Predicate<String>() {
     183                    }),
     184                    new Predicate<String>() {
    182185                        @Override
    183186                        public boolean evaluate(String format) {
     
    209212            throw new WMSGetCapabilitiesException(e, incomingData);
    210213        }
    211 
    212214    }
    213215
  • trunk/src/org/openstreetmap/josm/io/remotecontrol/RemoteControlHttpServer.java

    r6643 r7033  
    8383             Integer.toString(server.getLocalPort()));
    8484        while (true) {
    85             try {
    86                 Socket request = server.accept();
     85            try (Socket request = server.accept()) {
    8786                RequestProcessor.processRequest(request);
    88             } catch( SocketException se) {
    89                 if( !server.isClosed() )
     87            } catch (SocketException se) {
     88                if (!server.isClosed())
    9089                    Main.error(se);
    9190            } catch (IOException ioe) {
  • trunk/src/org/openstreetmap/josm/io/remotecontrol/RemoteControlHttpsServer.java

    r7004 r7033  
    5656               
    5757                // Load keystore
    58                 InputStream in = RemoteControlHttpsServer.class.getResourceAsStream(KEYSTORE_PATH);
    59                 if (in == null) {
    60                     Main.error(tr("Unable to find JOSM keystore at {0}. Remote control will not be available on HTTPS.", KEYSTORE_PATH));
    61                 } else {
    62                     try {
    63                         ks.load(in, password);
    64                     } finally {
    65                         Utils.close(in);
     58                try (InputStream in = RemoteControlHttpsServer.class.getResourceAsStream(KEYSTORE_PATH)) {
     59                    if (in == null) {
     60                        Main.error(tr("Unable to find JOSM keystore at {0}. Remote control will not be available on HTTPS.", KEYSTORE_PATH));
     61                    } else {
     62                        try {
     63                            ks.load(in, password);
     64                        } finally {
     65                            Utils.close(in);
     66                        }
     67                       
     68                        if (Main.isDebugEnabled()) {
     69                            for (Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements();) {
     70                                Main.debug("Alias in keystore: "+aliases.nextElement());
     71                            }
     72                        }
     73   
     74                        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
     75                        kmf.init(ks, password);
     76                       
     77                        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
     78                        tmf.init(ks);
     79                       
     80                        sslContext = SSLContext.getInstance("TLS");
     81                        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
     82                       
     83                        if (Main.isDebugEnabled()) {
     84                            Main.debug("SSL Context protocol: " + sslContext.getProtocol());
     85                            Main.debug("SSL Context provider: " + sslContext.getProvider());
     86                        }
     87                       
     88                        initOK = true;
    6689                    }
    67                    
    68                     if (Main.isDebugEnabled()) {
    69                         for (Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements();) {
    70                             Main.debug("Alias in keystore: "+aliases.nextElement());
    71                         }
    72                     }
    73 
    74                     KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    75                     kmf.init(ks, password);
    76                    
    77                     TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    78                     tmf.init(ks);
    79                    
    80                     sslContext = SSLContext.getInstance("TLS");
    81                     sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    82                    
    83                     if (Main.isDebugEnabled()) {
    84                         Main.debug("SSL Context protocol: " + sslContext.getProtocol());
    85                         Main.debug("SSL Context provider: " + sslContext.getProvider());
    86                     }
    87                    
    88                     initOK = true;
    8990                }
    9091            } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException |
     
    175176             Integer.toString(server.getLocalPort()));
    176177        while (true) {
    177             try {
    178                 Socket request = server.accept();
     178            try (Socket request = server.accept()) {
    179179                if (Main.isDebugEnabled() && request instanceof SSLSocket) {
    180180                    SSLSocket sslSocket = (SSLSocket) request;
  • trunk/src/org/openstreetmap/josm/io/session/GpxTracksSessionExporter.java

    r7029 r7033  
    179179    }
    180180
    181     protected void addDataFile(OutputStream out) {
    182         Writer writer = new OutputStreamWriter(out, Utils.UTF_8);
    183         GpxWriter w = new GpxWriter(new PrintWriter(writer));
    184         w.write(layer.data);
    185         w.flush();
     181    protected void addDataFile(OutputStream out) throws IOException {
     182        try (
     183            Writer writer = new OutputStreamWriter(out, Utils.UTF_8);
     184            GpxWriter w = new GpxWriter(new PrintWriter(writer))
     185        ) {
     186            w.write(layer.data);
     187            w.flush();
     188        }
    186189    }
    187 
    188190}
  • trunk/src/org/openstreetmap/josm/io/session/GpxTracksSessionImporter.java

    r6087 r7033  
    3737            }
    3838
    39             InputStream in = support.getInputStream(fileStr);
    40             GpxImporter.GpxImporterData importData = GpxImporter.loadLayers(in, support.getFile(fileStr), support.getLayerName(), null, progressMonitor);
    41 
    42             support.addPostLayersTask(importData.getPostLayerTask());
    43             return importData.getGpxLayer();
     39            try (InputStream in = support.getInputStream(fileStr)) {
     40                GpxImporter.GpxImporterData importData = GpxImporter.loadLayers(in, support.getFile(fileStr), support.getLayerName(), null, progressMonitor);
     41   
     42                support.addPostLayersTask(importData.getPostLayerTask());
     43                return importData.getGpxLayer();
     44            }
    4445
    4546        } catch (XPathExpressionException e) {
     
    4748        }
    4849    }
    49 
    5050}
  • trunk/src/org/openstreetmap/josm/io/session/MarkerSessionExporter.java

    r7029 r7033  
    8484    }
    8585
    86     protected void addDataFile(OutputStream out) {
    87         Writer writer = new OutputStreamWriter(out, Utils.UTF_8);
    88         MarkerWriter w = new MarkerWriter(new PrintWriter(writer));
    89         w.write(layer);
    90         w.flush();
     86    protected void addDataFile(OutputStream out) throws IOException {
     87        try (
     88            Writer writer = new OutputStreamWriter(out, Utils.UTF_8);
     89            MarkerWriter w = new MarkerWriter(new PrintWriter(writer))
     90        ) {
     91            w.write(layer);
     92            w.flush();
     93        }
    9194    }
    9295
  • trunk/src/org/openstreetmap/josm/io/session/MarkerSessionImporter.java

    r6093 r7033  
    4141            }
    4242
    43             InputStream in = support.getInputStream(fileStr);
    44             GpxImporter.GpxImporterData importData = GpxImporter.loadLayers(in, support.getFile(fileStr), support.getLayerName(), null, progressMonitor);
    45 
    46             support.addPostLayersTask(importData.getPostLayerTask());
    47 
    48             GpxLayer gpxLayer = null;
    49             List<SessionReader.LayerDependency> deps = support.getLayerDependencies();
    50             if (!deps.isEmpty()) {
    51                 Layer layer = deps.iterator().next().getLayer();
    52                 if (layer instanceof GpxLayer) {
    53                     gpxLayer = (GpxLayer) layer;
     43            try (InputStream in = support.getInputStream(fileStr)) {
     44                GpxImporter.GpxImporterData importData = GpxImporter.loadLayers(in, support.getFile(fileStr), support.getLayerName(), null, progressMonitor);
     45   
     46                support.addPostLayersTask(importData.getPostLayerTask());
     47   
     48                GpxLayer gpxLayer = null;
     49                List<SessionReader.LayerDependency> deps = support.getLayerDependencies();
     50                if (!deps.isEmpty()) {
     51                    Layer layer = deps.iterator().next().getLayer();
     52                    if (layer instanceof GpxLayer) {
     53                        gpxLayer = (GpxLayer) layer;
     54                    }
    5455                }
     56   
     57                MarkerLayer markerLayer = importData.getMarkerLayer();
     58                markerLayer.fromLayer = gpxLayer;
     59   
     60                return markerLayer;
    5561            }
    56 
    57             MarkerLayer markerLayer = importData.getMarkerLayer();
    58             markerLayer.fromLayer = gpxLayer;
    59 
    60             return markerLayer;
    61 
    6262        } catch (XPathExpressionException e) {
    6363            throw new RuntimeException(e);
  • trunk/src/org/openstreetmap/josm/io/session/OsmDataSessionExporter.java

    r7029 r7033  
    212212    }
    213213
    214     protected void addDataFile(OutputStream out) {
    215         Writer writer = new OutputStreamWriter(out, Utils.UTF_8);
    216         OsmWriter w = OsmWriterFactory.createOsmWriter(new PrintWriter(writer), false, layer.data.getVersion());
    217         layer.data.getReadLock().lock();
    218         try {
    219             w.writeLayer(layer);
    220             w.flush();
    221         } finally {
    222             layer.data.getReadLock().unlock();
     214    protected void addDataFile(OutputStream out) throws IOException {
     215        try (
     216            Writer writer = new OutputStreamWriter(out, Utils.UTF_8);
     217            OsmWriter w = OsmWriterFactory.createOsmWriter(new PrintWriter(writer), false, layer.data.getVersion())
     218        ) {
     219            layer.data.getReadLock().lock();
     220            try {
     221                w.writeLayer(layer);
     222                w.flush();
     223            } finally {
     224                layer.data.getReadLock().unlock();
     225            }
    223226        }
    224227    }
  • trunk/src/org/openstreetmap/josm/io/session/OsmDataSessionImporter.java

    r6087 r7033  
    3939
    4040            OsmImporter importer = new OsmImporter();
    41             InputStream in = support.getInputStream(fileStr);
    42             OsmImporter.OsmImporterData importData = importer.loadLayer(in, support.getFile(fileStr), support.getLayerName(), progressMonitor);
    43 
    44             support.addPostLayersTask(importData.getPostLayerTask());
    45             return importData.getLayer();
    46 
     41            try (InputStream in = support.getInputStream(fileStr)) {
     42                OsmImporter.OsmImporterData importData = importer.loadLayer(in, support.getFile(fileStr), support.getLayerName(), progressMonitor);
     43   
     44                support.addPostLayersTask(importData.getPostLayerTask());
     45                return importData.getLayer();
     46            }
    4747        } catch (XPathExpressionException e) {
    4848            throw new RuntimeException(e);
  • trunk/src/org/openstreetmap/josm/io/session/SessionReader.java

    r7005 r7033  
    553553        }
    554554
    555         InputStream josIS = null;
    556 
     555        try (InputStream josIS = createInputStream(sessionFile, zip)) {
     556            loadSession(josIS, sessionFile.toURI(), zip, progressMonitor);
     557        }
     558    }
     559
     560    private InputStream createInputStream(File sessionFile, boolean zip) throws IOException, IllegalDataException {
    557561        if (zip) {
    558562            try {
    559563                zipFile = new ZipFile(sessionFile);
    560                 josIS = getZipInputStream(zipFile);
     564                return getZipInputStream(zipFile);
    561565            } catch (ZipException ze) {
    562566                throw new IOException(ze);
     
    564568        } else {
    565569            try {
    566                 josIS = new FileInputStream(sessionFile);
     570                return new FileInputStream(sessionFile);
    567571            } catch (FileNotFoundException ex) {
    568572                throw new IOException(ex);
    569573            }
    570574        }
    571 
    572         loadSession(josIS, sessionFile.toURI(), zip, progressMonitor);
    573575    }
    574576
  • trunk/src/org/openstreetmap/josm/io/session/SessionWriter.java

    r7005 r7033  
    240240
    241241    public void write(File f) throws IOException {
    242         OutputStream out = null;
    243         try {
    244             out = new FileOutputStream(f);
     242        try (OutputStream out = new FileOutputStream(f)) {
     243            write(out);
    245244        } catch (FileNotFoundException e) {
    246245            throw new IOException(e);
    247246        }
    248         write(out);
    249247    }
    250248
     
    262260            writeJos(doc, new BufferedOutputStream(out));
    263261        }
    264         Utils.close(out);
    265262    }
    266263}
  • trunk/src/org/openstreetmap/josm/plugins/Plugin.java

    r6615 r7033  
    110110            pluginDir.mkdirs();
    111111        }
    112         FileOutputStream out = null;
    113         InputStream in = null;
    114         try {
    115             out = new FileOutputStream(new File(pluginDirName, to));
    116             in = getClass().getResourceAsStream(from);
     112        try (
     113            FileOutputStream out = new FileOutputStream(new File(pluginDirName, to));
     114            InputStream in = getClass().getResourceAsStream(from)
     115        ) {
    117116            if (in == null) {
    118117                throw new IOException("Resource not found: "+from);
     
    122121                out.write(buffer, 0, len);
    123122            }
    124         } finally {
    125             Utils.close(in);
    126             Utils.close(out);
    127123        }
    128124    }
  • trunk/src/org/openstreetmap/josm/plugins/PluginDownloadTask.java

    r7005 r7033  
    2424import org.openstreetmap.josm.io.MirroredInputStream;
    2525import org.openstreetmap.josm.tools.CheckParameterUtil;
    26 import org.openstreetmap.josm.tools.Utils;
    2726import org.xml.sax.SAXException;
    2827
     
    118117                throw new PluginDownloadException(tr("Download skipped"));
    119118        }
    120         OutputStream out = null;
    121         InputStream in = null;
    122119        try {
    123120            if (pi.downloadlink == null) {
     
    130127                downloadConnection = MirroredInputStream.connectFollowingRedirect(url, PLUGIN_MIME_TYPES);
    131128            }
    132             in = downloadConnection.getInputStream();
    133             out = new FileOutputStream(file);
    134             byte[] buffer = new byte[8192];
    135             for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
    136                 out.write(buffer, 0, read);
     129            try (
     130                InputStream in = downloadConnection.getInputStream();
     131                OutputStream out = new FileOutputStream(file)
     132            ) {
     133                byte[] buffer = new byte[8192];
     134                for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
     135                    out.write(buffer, 0, read);
     136                }
    137137            }
    138138        } catch (MalformedURLException e) {
     
    145145            throw new PluginDownloadException(e);
    146146        } finally {
    147             Utils.close(in);
    148147            synchronized(this) {
    149148                downloadConnection = null;
    150149            }
    151             Utils.close(out);
    152150        }
    153151    }
  • trunk/src/org/openstreetmap/josm/plugins/PluginInformation.java

    r7005 r7033  
    107107        this.name = name;
    108108        this.file = file;
    109         FileInputStream fis = null;
    110         JarInputStream jar = null;
    111         try {
    112             fis = new FileInputStream(file);
    113             jar = new JarInputStream(fis);
     109        try (
     110            FileInputStream fis = new FileInputStream(file);
     111            JarInputStream jar = new JarInputStream(fis)
     112        ) {
    114113            Manifest manifest = jar.getManifest();
    115114            if (manifest == null)
     
    119118        } catch (IOException e) {
    120119            throw new PluginException(name, e);
    121         } finally {
    122             Utils.close(jar);
    123             Utils.close(fis);
    124120        }
    125121    }
     
    380376        String name = pluginName;
    381377        name = name.replaceAll("[-. ]", "");
    382         InputStream manifestStream = PluginInformation.class.getResourceAsStream("/org/openstreetmap/josm/plugins/"+name+"/MANIFEST.MF");
    383         if (manifestStream != null)
    384             return new PluginInformation(manifestStream, pluginName, null);
     378        try (InputStream manifestStream = PluginInformation.class.getResourceAsStream("/org/openstreetmap/josm/plugins/"+name+"/MANIFEST.MF")) {
     379            if (manifestStream != null) {
     380                return new PluginInformation(manifestStream, pluginName, null);
     381            }
     382        } catch (IOException e) {
     383            Main.warn(e);
     384        }
    385385
    386386        Collection<String> locations = getPluginLocations();
  • trunk/src/org/openstreetmap/josm/plugins/ReadLocalPluginInformationTask.java

    r7005 r7033  
    172172
    173173    protected void processLocalPluginInformationFile(File file) throws PluginListParseException{
    174         FileInputStream fin = null;
    175         try {
    176             fin = new FileInputStream(file);
     174        try (FileInputStream fin = new FileInputStream(file)) {
    177175            List<PluginInformation> pis = new PluginListParser().parse(fin);
    178176            for (PluginInformation pi : pis) {
     
    185183        } catch(IOException e) {
    186184            throw new PluginListParseException(e);
    187         } finally {
    188             Utils.close(fin);
    189185        }
    190186    }
  • trunk/src/org/openstreetmap/josm/plugins/ReadRemotePluginInformationTask.java

    r7005 r7033  
    203203
    204204    private void handleIOException(final ProgressMonitor monitor, IOException e, final String title, final String firstMessage, boolean displayMsg) {
    205         InputStream errStream = connection.getErrorStream();
    206205        StringBuilder sb = new StringBuilder();
    207         if (errStream != null) {
    208             BufferedReader err = null;
    209             try {
    210                 String line;
    211                 err = new BufferedReader(new InputStreamReader(errStream, Utils.UTF_8));
    212                 while ((line = err.readLine()) != null) {
    213                     sb.append(line).append("\n");
    214                 }
    215             } catch (Exception ex) {
    216                 Main.error(e);
    217                 Main.error(ex);
    218             } finally {
    219                 Utils.close(err);
    220             }
     206        try (InputStream errStream = connection.getErrorStream()) {
     207            if (errStream != null) {
     208                BufferedReader err = null;
     209                try {
     210                    String line;
     211                    err = new BufferedReader(new InputStreamReader(errStream, Utils.UTF_8));
     212                    while ((line = err.readLine()) != null) {
     213                        sb.append(line).append("\n");
     214                    }
     215                } catch (Exception ex) {
     216                    Main.error(e);
     217                    Main.error(ex);
     218                } finally {
     219                    Utils.close(err);
     220                }
     221            }
     222        } catch (IOException ex) {
     223            Main.warn(ex);
    221224        }
    222225        final String msg = e.getMessage();
     
    265268     */
    266269    protected void downloadPluginIcons(String site, File destFile, ProgressMonitor monitor) {
    267         InputStream in = null;
    268         OutputStream out = null;
    269270        try {
    270271            site = site.replaceAll("%<(.*)>", "");
     
    278279                connection.setRequestProperty("Cache-Control", "no-cache");
    279280            }
    280             in = connection.getInputStream();
    281             out = new FileOutputStream(destFile);
    282             byte[] buffer = new byte[8192];
    283             for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
    284                 out.write(buffer, 0, read);
     281            try (
     282                InputStream in = connection.getInputStream();
     283                OutputStream out = new FileOutputStream(destFile)
     284            ) {
     285                byte[] buffer = new byte[8192];
     286                for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
     287                    out.write(buffer, 0, read);
     288                }
    285289            }
    286290        } catch (MalformedURLException e) {
     
    293297            return;
    294298        } finally {
    295             Utils.close(out);
    296299            synchronized(this) {
    297300                if (connection != null) {
     
    300303                connection = null;
    301304            }
    302             Utils.close(in);
    303305            monitor.finishTask();
    304306        }
     
    321323     */
    322324    protected void cachePluginList(String site, String list) {
    323         PrintWriter writer = null;
    324         try {
    325             File pluginDir = Main.pref.getPluginsDirectory();
    326             if (!pluginDir.exists() && !pluginDir.mkdirs()) {
    327                 Main.warn(tr("Failed to create plugin directory ''{0}''. Cannot cache plugin list from plugin site ''{1}''.", pluginDir.toString(), site));
    328             }
    329             File cacheFile = createSiteCacheFile(pluginDir, site, CacheType.PLUGIN_LIST);
    330             getProgressMonitor().subTask(tr("Writing plugin list to local cache ''{0}''", cacheFile.toString()));
    331             writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(cacheFile), Utils.UTF_8));
     325        File pluginDir = Main.pref.getPluginsDirectory();
     326        if (!pluginDir.exists() && !pluginDir.mkdirs()) {
     327            Main.warn(tr("Failed to create plugin directory ''{0}''. Cannot cache plugin list from plugin site ''{1}''.", pluginDir.toString(), site));
     328        }
     329        File cacheFile = createSiteCacheFile(pluginDir, site, CacheType.PLUGIN_LIST);
     330        getProgressMonitor().subTask(tr("Writing plugin list to local cache ''{0}''", cacheFile.toString()));
     331        try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(cacheFile), Utils.UTF_8))) {
    332332            writer.write(list);
     333            writer.flush();
    333334        } catch(IOException e) {
    334335            // just failed to write the cache file. No big deal, but log the exception anyway
    335336            Main.error(e);
    336         } finally {
    337             if (writer != null) {
    338                 writer.flush();
    339                 Utils.close(writer);
    340             }
    341337        }
    342338    }
  • trunk/src/org/openstreetmap/josm/tools/AudioUtil.java

    r7029 r7033  
    3131     */
    3232    public static double getCalibratedDuration(File wavFile) {
    33         try {
    34             AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(
    35                 new URL("file:".concat(wavFile.getAbsolutePath())));
     33        try (AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(
     34                new URL("file:".concat(wavFile.getAbsolutePath())))) {
    3635            AudioFormat audioFormat = audioInputStream.getFormat();
    3736            long filesize = wavFile.length();
  • trunk/src/org/openstreetmap/josm/tools/I18n.java

    r7012 r7033  
    397397        if ("en".equals(loadedCode))
    398398            return;
    399         FileInputStream fis = null;
    400         JarInputStream jar = null;
    401         FileInputStream fisTrans = null;
    402         JarInputStream jarTrans = null;
    403399        String enfile = "data/en.lang";
    404400        String langfile = "data/"+loadedCode+".lang";
    405         try
    406         {
     401        try (
     402            FileInputStream fis = new FileInputStream(source);
     403            JarInputStream jar = new JarInputStream(fis)
     404        ) {
    407405            ZipEntry e;
    408             fis = new FileInputStream(source);
    409             jar = new JarInputStream(fis);
    410406            boolean found = false;
    411             while(!found && (e = jar.getNextEntry()) != null)
    412             {
     407            while (!found && (e = jar.getNextEntry()) != null) {
    413408                String name = e.getName();
    414409                if(name.equals(enfile))
    415410                    found = true;
    416411            }
    417             if(found)
    418             {
    419                 fisTrans = new FileInputStream(source);
    420                 jarTrans = new JarInputStream(fisTrans);
    421                 found = false;
    422                 while(!found && (e = jarTrans.getNextEntry()) != null)
    423                 {
    424                     String name = e.getName();
    425                     if(name.equals(langfile))
    426                         found = true;
     412            if (found) {
     413                try (
     414                    FileInputStream fisTrans = new FileInputStream(source);
     415                    JarInputStream jarTrans = new JarInputStream(fisTrans)
     416                ) {
     417                    found = false;
     418                    while(!found && (e = jarTrans.getNextEntry()) != null) {
     419                        String name = e.getName();
     420                        if (name.equals(langfile))
     421                            found = true;
     422                    }
     423                    if (found)
     424                        load(jar, jarTrans, true);
    427425                }
    428                 if(found)
    429                     load(jar, jarTrans, true);
    430             }
    431         } catch(IOException e) {
     426            }
     427        } catch (IOException e) {
    432428            // Ignore
    433         } finally {
    434             Utils.close(jar);
    435             Utils.close(fis);
    436             Utils.close(jarTrans);
    437             Utils.close(fisTrans);
    438429        }
    439430    }
     
    460451                return false;
    461452        }
    462         InputStream enStream = null;
    463         InputStream trStream = null;
    464         try {
    465             enStream = en.openStream();
    466             trStream = tr.openStream();
     453        try (
     454            InputStream enStream = en.openStream();
     455            InputStream trStream = tr.openStream()
     456        ) {
    467457            if (load(enStream, trStream, false)) {
    468458                pluralMode = languages.get(l);
     
    470460                return true;
    471461            }
    472         } catch(IOException e) {
     462        } catch (IOException e) {
    473463            // Ignore exception
    474         } finally {
    475             Utils.close(trStream);
    476             Utils.close(enStream);
    477464        }
    478465        return false;
  • trunk/src/org/openstreetmap/josm/tools/ImageProvider.java

    r7025 r7033  
    504504
    505505    private static ImageResource getIfAvailableHttp(String url, ImageType type) {
    506         MirroredInputStream is = null;
    507         try {
    508             is = new MirroredInputStream(url,
    509                     new File(Main.pref.getCacheDirectory(), "images").getPath());
     506        try (MirroredInputStream is = new MirroredInputStream(url,
     507                    new File(Main.pref.getCacheDirectory(), "images").getPath())) {
    510508            switch (type) {
    511509            case SVG:
     
    526524        } catch (IOException e) {
    527525            return null;
    528         } finally {
    529             Utils.close(is);
    530526        }
    531527    }
     
    603599
    604600    private static ImageResource getIfAvailableZip(String fullName, File archive, String inArchiveDir, ImageType type) {
    605         ZipFile zipFile = null;
    606         try {
    607             zipFile = new ZipFile(archive);
     601        try (ZipFile zipFile = new ZipFile(archive)) {
    608602            if (inArchiveDir == null || ".".equals(inArchiveDir)) {
    609603                inArchiveDir = "";
     
    613607            String entryName = inArchiveDir + fullName;
    614608            ZipEntry entry = zipFile.getEntry(entryName);
    615             if(entry != null)
    616             {
     609            if (entry != null) {
    617610                int size = (int)entry.getSize();
    618611                int offs = 0;
    619612                byte[] buf = new byte[size];
    620                 InputStream is = null;
    621                 try {
    622                     is = zipFile.getInputStream(entry);
     613                try (InputStream is = zipFile.getInputStream(entry)) {
    623614                    switch (type) {
    624615                    case SVG:
     
    641632                        return img == null ? null : new ImageResource(img);
    642633                    default:
    643                         throw new AssertionError();
     634                        throw new AssertionError("Unknown ImageType: "+type);
    644635                    }
    645                 } finally {
    646                     Utils.close(is);
    647636                }
    648637            }
    649638        } catch (Exception e) {
    650639            Main.warn(tr("Failed to handle zip file ''{0}''. Exception was: {1}", archive.getName(), e.toString()));
    651         } finally {
    652             Utils.close(zipFile);
    653640        }
    654641        return null;
     
    785772            });
    786773
    787             parser.parse(new InputSource(new MirroredInputStream(
     774            try (InputStream is = new MirroredInputStream(
    788775                    base + fn,
    789                     new File(Main.pref.getPreferencesDir(), "images").toString()
    790                     )));
     776                    new File(Main.pref.getPreferencesDir(), "images").toString())
     777            ) {
     778                parser.parse(new InputSource(is));
     779            }
    791780        } catch (SAXReturnException r) {
    792781            return r.getResult();
  • trunk/src/org/openstreetmap/josm/tools/PlatformHookUnixoid.java

    r7012 r7033  
    283283                File file = new File(path);
    284284                if (file.exists()) {
    285                     BufferedReader reader = null;
    286                     try {
    287                         reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), Utils.UTF_8));
     285                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), Utils.UTF_8))) {
    288286                        String id = null;
    289287                        String release = null;
     
    313311                    } catch (IOException e) {
    314312                        // Ignore
    315                     } finally {
    316                         Utils.close(reader);
    317313                    }
    318314                }
  • trunk/src/org/openstreetmap/josm/tools/WikiReader.java

    r6898 r7033  
    4343    public String read(String url) throws IOException {
    4444        URL u = new URL(url);
    45         BufferedReader in = Utils.openURLReader(u);
    46         try {
     45        try (BufferedReader in = Utils.openURLReader(u)) {
    4746            if (url.startsWith(baseurl) && !url.endsWith("?format=txt"))
    4847                return readFromTrac(in, u);
    4948            return readNormal(in);
    50         } finally {
    51             Utils.close(in);
    5249        }
    5350    }
     
    8481
    8582    private String readLang(URL url) throws IOException {
    86         BufferedReader in;
    87         try {
    88             in = Utils.openURLReader(url);
     83        try (BufferedReader in = Utils.openURLReader(url)) {
     84            return readFromTrac(in, url);
    8985        } catch (IOException e) {
    9086            Main.addNetworkError(url, Utils.getRootCause(e));
    9187            throw e;
    92         }
    93         try {
    94             return readFromTrac(in, url);
    95         } finally {
    96             Utils.close(in);
    9788        }
    9889    }
  • trunk/src/org/openstreetmap/josm/tools/XmlObjectParser.java

    r7012 r7033  
    55
    66import java.io.IOException;
     7import java.io.InputStream;
    78import java.io.Reader;
    89import java.lang.reflect.Field;
     
    1718import java.util.Stack;
    1819
     20import javax.xml.XMLConstants;
    1921import javax.xml.parsers.ParserConfigurationException;
    2022import javax.xml.parsers.SAXParser;
     
    278280
    279281    public Iterable<Object> startWithValidation(final Reader in, String namespace, String schemaSource) throws SAXException {
    280         try {
    281             SchemaFactory factory =  SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    282             Schema schema = factory.newSchema(new StreamSource(new MirroredInputStream(schemaSource)));
     282        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
     283        try (InputStream mis = new MirroredInputStream(schemaSource)) {
     284            Schema schema = factory.newSchema(new StreamSource(mis));
    283285            ValidatorHandler validator = schema.newValidatorHandler();
    284286            validator.setContentHandler(parser);
  • trunk/test/performance/org/openstreetmap/josm/data/osm/MapPaintVisitorPerformanceTest.java

    r5556 r7033  
    55import java.awt.image.BufferedImage;
    66import java.io.FileInputStream;
     7import java.io.InputStream;
    78
    89import org.junit.BeforeClass;
     
    4243        MapPaintStyles.readFromPreferences();
    4344
    44         dsRestriction = OsmReader.parseDataSet(new FileInputStream("data_nodist/restriction.osm"), NullProgressMonitor.INSTANCE);
    45         dsMultipolygon = OsmReader.parseDataSet(new FileInputStream("data_nodist/multipolygon.osm"), NullProgressMonitor.INSTANCE);
    46         dsCity = OsmReader.parseDataSet(new FileInputStream("data_nodist/neubrandenburg.osm"), NullProgressMonitor.INSTANCE);
     45        try (
     46            InputStream fisR = new FileInputStream("data_nodist/restriction.osm");
     47            InputStream fisM = new FileInputStream("data_nodist/multipolygon.osm");
     48            InputStream fisC = new FileInputStream("data_nodist/neubrandenburg.osm");
     49        ) {
     50            dsRestriction = OsmReader.parseDataSet(fisR, NullProgressMonitor.INSTANCE);
     51            dsMultipolygon = OsmReader.parseDataSet(fisM, NullProgressMonitor.INSTANCE);
     52            dsCity = OsmReader.parseDataSet(fisC, NullProgressMonitor.INSTANCE);
     53        }
    4754
    4855        // Warm up
     
    103110        test(200, dsCity, new Bounds(53.56, 13.295, 53.57, 13.30));
    104111    }
    105 
    106 
    107 
    108112}
  • trunk/test/unit/org/openstreetmap/josm/data/osm/FilterTest.java

    r7005 r7033  
    55
    66import java.io.FileInputStream;
    7 import java.io.FileNotFoundException;
     7import java.io.IOException;
     8import java.io.InputStream;
    89import java.util.Arrays;
    910import java.util.Collection;
     
    6364
    6465    @Test
    65     public void filter_test() throws ParseError, IllegalDataException, FileNotFoundException {
     66    public void filter_test() throws ParseError, IllegalDataException, IOException {
    6667        for (int i : new int [] {1,2,3, 11,12,13,14, 15}) {
    67             DataSet ds = OsmReader.parseDataSet(new FileInputStream("data_nodist/filterTests.osm"), NullProgressMonitor.INSTANCE);
     68            DataSet ds;
     69            try (InputStream is = new FileInputStream("data_nodist/filterTests.osm")) {
     70                ds = OsmReader.parseDataSet(is, NullProgressMonitor.INSTANCE);
     71            }
    6872
    6973            List<Filter> filters = new LinkedList<>();
  • trunk/test/unit/org/openstreetmap/josm/data/osm/QuadBucketsTest.java

    r7005 r7033  
    33
    44import java.io.FileInputStream;
     5import java.io.InputStream;
    56import java.util.ArrayList;
    67import java.util.Collection;
     
    6667    public void testRemove() throws Exception {
    6768        Main.setProjection(Projections.getProjectionByCode("EPSG:3857")); // Mercator
    68         DataSet ds = OsmReader.parseDataSet(new FileInputStream("data_nodist/restriction.osm"), NullProgressMonitor.INSTANCE);
    69         removeAllTest(ds);
     69        try (InputStream fis = new FileInputStream("data_nodist/restriction.osm")) {
     70            DataSet ds = OsmReader.parseDataSet(fis, NullProgressMonitor.INSTANCE);
     71            removeAllTest(ds);
     72        }
    7073    }
    7174
     
    7376    public void testMove() throws Exception {
    7477        Main.setProjection(Projections.getProjectionByCode("EPSG:3857")); // Mercator
    75         DataSet ds = OsmReader.parseDataSet(new FileInputStream("data_nodist/restriction.osm"), NullProgressMonitor.INSTANCE);
    76 
    77         for (Node n: ds.getNodes()) {
    78             n.setCoor(new LatLon(10, 10));
     78        try (InputStream fis = new FileInputStream("data_nodist/restriction.osm")) {
     79            DataSet ds = OsmReader.parseDataSet(fis, NullProgressMonitor.INSTANCE);
     80   
     81            for (Node n: ds.getNodes()) {
     82                n.setCoor(new LatLon(10, 10));
     83            }
     84   
     85            removeAllTest(ds);
    7986        }
    80 
    81         removeAllTest(ds);
    8287    }
    8388}
  • trunk/test/unit/org/openstreetmap/josm/data/projection/ProjectionRefTest.java

    r7005 r7033  
    4949    @Test
    5050    public void test() throws IOException, FileNotFoundException {
    51         BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("data_nodist/projection-reference-data.csv"), Utils.UTF_8));
    52         StringBuilder fail = new StringBuilder();
    53         String line;
    54         while ((line = in.readLine()) != null) {
    55             if (line.startsWith("#")) {
    56                 continue;
    57             }
    58             String[] f = line.split(",");
    59             String code = f[0];
    60             double lat = Double.parseDouble(f[1]);
    61             double lon = Double.parseDouble(f[2]);
    62             double east = Double.parseDouble(f[3]);
    63             double north = Double.parseDouble(f[4]);
    64             Projection p = Projections.getProjectionByCode(code);
    65             {
     51        try (BufferedReader in = new BufferedReader(new InputStreamReader(
     52                new FileInputStream("data_nodist/projection-reference-data.csv"), Utils.UTF_8))) {
     53            StringBuilder fail = new StringBuilder();
     54            String line;
     55            while ((line = in.readLine()) != null) {
     56                if (line.startsWith("#")) {
     57                    continue;
     58                }
     59                String[] f = line.split(",");
     60                String code = f[0];
     61                double lat = Double.parseDouble(f[1]);
     62                double lon = Double.parseDouble(f[2]);
     63                double east = Double.parseDouble(f[3]);
     64                double north = Double.parseDouble(f[4]);
     65                Projection p = Projections.getProjectionByCode(code);
    6666                EastNorth en = p.latlon2eastNorth(new LatLon(lat, lon));
    67                 String error = String.format("%s (%s): Projecting latlon(%s,%s):%n" +
     67                String errorEN = String.format("%s (%s): Projecting latlon(%s,%s):%n" +
    6868                        "        expected: eastnorth(%s,%s),%n" +
    6969                        "        but got:  eastnorth(%s,%s)!%n",
    7070                        p.toString(), code, lat, lon, east, north, en.east(), en.north());
    71                 double EPSILON = 1e-3; // 1 mm accuracy
    72                 if (Math.abs(east - en.east()) > EPSILON || Math.abs(north - en.north()) > EPSILON) {
    73                     fail.append(error);
     71                double EPSILON_EN = 1e-3; // 1 mm accuracy
     72                if (Math.abs(east - en.east()) > EPSILON_EN || Math.abs(north - en.north()) > EPSILON_EN) {
     73                    fail.append(errorEN);
    7474                }
    75             }
    76             {
    7775                LatLon ll = p.eastNorth2latlon(new EastNorth(east, north));
    78                 String error = String.format("%s (%s): Inverse projecting eastnorth(%s,%s):%n" +
     76                String errorLL = String.format("%s (%s): Inverse projecting eastnorth(%s,%s):%n" +
    7977                        "        expected: latlon(%s,%s),%n" +
    8078                        "        but got:  latlon(%s,%s)!%n",
    8179                        p.toString(), code, east, north, lat, lon, ll.lat(), ll.lon());
    82                 double EPSILON = Math.toDegrees(1e-3 / 6378137); // 1 mm accuracy (or better)
    83                 if (Math.abs(lat - ll.lat()) > EPSILON || Math.abs(lon - ll.lon()) > EPSILON) {
     80                double EPSILON_LL = Math.toDegrees(1e-3 / 6378137); // 1 mm accuracy (or better)
     81                if (Math.abs(lat - ll.lat()) > EPSILON_LL || Math.abs(lon - ll.lon()) > EPSILON_LL) {
    8482                    if (!("yes".equals(System.getProperty("suppressPermanentFailure")) && code.equals("EPSG:21781"))) {
    85                         fail.append(error);
     83                        fail.append(errorLL);
    8684                    }
    8785                }
    8886            }
    89         }
    90         Utils.close(in);
    91         if (fail.length() > 0) {
    92             System.err.println(fail.toString());
    93             throw new AssertionError(fail.toString());
     87            if (fail.length() > 0) {
     88                System.err.println(fail.toString());
     89                throw new AssertionError(fail.toString());
     90            }
    9491        }
    9592    }
  • trunk/test/unit/org/openstreetmap/josm/data/validation/tests/UnconnectedWaysTest.java

    r6881 r7033  
    66
    77import java.io.FileInputStream;
     8import java.io.InputStream;
    89
    910import org.junit.Before;
     
    3334    @Test
    3435    public void testTicket6313() throws Exception {
    35         final DataSet ds = OsmReader.parseDataSet(new FileInputStream("data_nodist/UnconnectedWaysTest.osm"), NullProgressMonitor.INSTANCE);
    36         bib.visit(ds.allPrimitives());
    37         bib.endTest();
    38         assertThat(bib.getErrors(), isEmpty());
     36        try (InputStream fis = new FileInputStream("data_nodist/UnconnectedWaysTest.osm")) {
     37            final DataSet ds = OsmReader.parseDataSet(fis, NullProgressMonitor.INSTANCE);
     38            bib.visit(ds.allPrimitives());
     39            bib.endTest();
     40            assertThat(bib.getErrors(), isEmpty());
     41        }
    3942    }
    4043}
  • trunk/test/unit/org/openstreetmap/josm/gui/dialogs/relation/sort/RelationSorterTest.java

    r7005 r7033  
    33
    44import java.io.FileInputStream;
    5 import java.io.FileNotFoundException;
     5import java.io.IOException;
     6import java.io.InputStream;
    67import java.util.List;
    78
     
    2425
    2526    @BeforeClass
    26     public static void loadData() throws FileNotFoundException, IllegalDataException {
     27    public static void loadData() throws IllegalDataException, IOException {
    2728        Main.initApplicationPreferences();
    2829        Main.setProjection(Projections.getProjectionByCode("EPSG:3857")); // Mercator
    29         testDataset = OsmReader.parseDataSet(new FileInputStream("data_nodist/relation_sort.osm"), NullProgressMonitor.INSTANCE);
     30        try (InputStream fis = new FileInputStream("data_nodist/relation_sort.osm")) {
     31            testDataset = OsmReader.parseDataSet(fis, NullProgressMonitor.INSTANCE);
     32        }
    3033    }
    3134
  • trunk/test/unit/org/openstreetmap/josm/gui/dialogs/relation/sort/WayConnectionTypeCalculatorTest.java

    r7005 r7033  
    33
    44import java.io.FileInputStream;
    5 import java.io.FileNotFoundException;
     5import java.io.IOException;
     6import java.io.InputStream;
    67import java.util.Arrays;
    78import java.util.List;
     
    2526
    2627    @BeforeClass
    27     public static void loadData() throws FileNotFoundException, IllegalDataException {
     28    public static void loadData() throws IllegalDataException, IOException {
    2829        Main.initApplicationPreferences();
    2930        Main.setProjection(Projections.getProjectionByCode("EPSG:3857")); // Mercator
    30         testDataset = OsmReader.parseDataSet(new FileInputStream("data_nodist/relation_sort.osm"), NullProgressMonitor.INSTANCE);
     31        try (InputStream fis = new FileInputStream("data_nodist/relation_sort.osm")) {
     32            testDataset = OsmReader.parseDataSet(fis, NullProgressMonitor.INSTANCE);
     33        }
    3134    }
    3235
Note: See TracChangeset for help on using the changeset viewer.