Changeset 7033 in josm for trunk/src/org
- Timestamp:
- 2014-05-01T02:34:43+02:00 (11 years ago)
- Location:
- trunk/src/org/openstreetmap/josm
- Files:
-
- 72 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/src/org/openstreetmap/josm/actions/ImageryAdjustAction.java
r6890 r7033 17 17 import java.awt.event.MouseListener; 18 18 import java.awt.event.MouseMotionListener; 19 import java.util.Formatter; 20 import java.util.Locale; 19 21 20 22 import javax.swing.JLabel; … … 236 238 int precision = Main.getProjection().getDefaultZoomInPPD() >= 1.0 ? 2 : 7; 237 239 // 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( 239 242 "%1." + precision + "f; %1." + precision + "f", 240 243 layer.getDx(), layer.getDy()).toString()); 244 } 241 245 } 242 246 -
trunk/src/org/openstreetmap/josm/actions/OpenFileAction.java
r7026 r7033 292 292 293 293 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))) { 296 295 String line; 297 296 while ((line = reader.readLine()) != null) { -
trunk/src/org/openstreetmap/josm/actions/SessionLoadAction.java
r7004 r7033 153 153 file = File.createTempFile("session_", ".joz", Utils.getJosmTempDir()); 154 154 tempFile = true; 155 FileOutputStream out = new FileOutputStream(file); 156 try { 155 try (FileOutputStream out = new FileOutputStream(file)) { 157 156 Utils.copyStream(is, out); 158 } finally {159 Utils.close(out);160 157 } 161 158 } -
trunk/src/org/openstreetmap/josm/data/AutosaveTask.java
r7029 r7033 157 157 try { 158 158 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")) { 162 161 ps.println(ManagementFactory.getRuntimeMXBean().getName()); 163 Utils.close(ps);164 162 } catch (Throwable t) { 165 163 Main.error(t); … … 305 303 File pidFile = getPidFile(file); 306 304 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))) { 309 306 try { 310 307 String jvmId = reader.readLine(); -
trunk/src/org/openstreetmap/josm/data/CustomConfigurator.java
r7027 r7033 427 427 String fileDir = file.getParentFile().getAbsolutePath(); 428 428 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 } 430 432 } catch (Exception ex) { 431 433 log("Error reading custom preferences: " + ex.getMessage()); … … 445 447 } catch (Exception ex) { 446 448 log("Error reading custom preferences: "+ex.getMessage()); 447 } finally {448 Utils.close(is);449 449 } 450 450 log("-- Reading complete --"); … … 460 460 engine.eval("homeDir='"+normalizeDirName(Main.pref.getPreferencesDir()) +"';"); 461 461 engine.eval("josmVersion="+Version.getInstance().getVersion()+";"); 462 String className = 462 String className = CustomConfigurator.class.getName(); 463 463 engine.eval("API.messageBox="+className+".messageBox"); 464 464 engine.eval("API.askText=function(text) { return String("+className+".askForText(text));}"); -
trunk/src/org/openstreetmap/josm/data/Preferences.java
r7027 r7033 11 11 import java.io.FileOutputStream; 12 12 import java.io.IOException; 13 import java.io.InputStream; 13 14 import java.io.InputStreamReader; 14 15 import java.io.OutputStreamWriter; … … 719 720 720 721 /** 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. 723 723 */ 724 724 public void save() throws IOException { … … 736 736 } 737 737 738 finalPrintWriter 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 } 742 742 743 743 File tmpFile = new File(prefFile + "_tmp"); … … 748 748 setCorrectPermissions(backupFile); 749 749 } 750 751 750 752 751 private void setCorrectPermissions(File file) { … … 761 760 settingsMap.clear(); 762 761 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))) { 765 763 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))) { 768 766 fromXML(in); 769 } finally {770 Utils.close(in);771 767 } 772 768 updateSystemProperties(); … … 1359 1355 public void validateXML(Reader in) throws Exception { 1360 1356 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 } 1364 1362 } 1365 1363 -
trunk/src/org/openstreetmap/josm/data/Version.java
r7005 r7033 38 38 String s = null; 39 39 try { 40 BufferedReader in = Utils.openURLReader(resource);41 40 StringBuilder sb = new StringBuilder(); 42 try {41 try (BufferedReader in = Utils.openURLReader(resource)) { 43 42 for (String line = in.readLine(); line != null; line = in.readLine()) { 44 43 sb.append(line).append("\n"); 45 44 } 46 } finally {47 Utils.close(in);48 45 } 49 46 s = sb.toString(); -
trunk/src/org/openstreetmap/josm/data/imagery/WmsCache.java
r7028 r7033 111 111 private String getCacheDirectory(String url) { 112 112 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, ""); 123 144 } catch (IOException e) { 124 Main.error("Unable to load layersindex for wms cache");145 Main.error("Unable to save layer index for wms cache"); 125 146 Main.error(e); 126 147 } 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);157 148 } 158 149 … … 181 172 WmsCacheType.class.getClassLoader()); 182 173 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 } 184 178 totalFileSize = cacheEntries.getTotalFileSize(); 185 179 if (cacheEntries.getTileSize() != tileSize) { … … 292 286 WmsCacheType.class.getClassLoader()); 293 287 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 } 295 291 } catch (Exception e) { 296 292 Main.error("Failed to save wms-cache file"); … … 302 298 return new File(cacheDir, projection.cacheDirectory + "/" + entry.filename); 303 299 } 304 305 300 306 301 private BufferedImage loadImage(ProjectionEntries projectionEntries, CacheEntry entry) throws IOException { … … 524 519 totalFileSize += imageFile.length(); 525 520 } else { 526 OutputStream os = new BufferedOutputStream(new FileOutputStream(imageFile)); 527 try { 521 try (OutputStream os = new BufferedOutputStream(new FileOutputStream(imageFile))) { 528 522 totalFileSize += Utils.copyStream(imageData, os); 529 } finally {530 Utils.close(os);531 523 } 532 524 } -
trunk/src/org/openstreetmap/josm/data/projection/Projections.java
r7005 r7033 132 132 private static void loadInits() { 133 133 Pattern epsgPattern = Pattern.compile("<(\\d+)>(.*)<>"); 134 BufferedReader r = null; 135 try { 134 try ( 136 135 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 ) { 138 138 String line, lastline = ""; 139 139 while ((line = r.readLine()) != null) { 140 140 line = line.trim(); 141 141 if (!line.startsWith("#") && !line.isEmpty()) { 142 if (!lastline.startsWith("#")) throw new AssertionError( );142 if (!lastline.startsWith("#")) throw new AssertionError("EPSG file seems corrupted"); 143 143 String name = lastline.substring(1).trim(); 144 144 Matcher m = epsgPattern.matcher(line); … … 153 153 } catch (IOException ex) { 154 154 throw new RuntimeException(ex); 155 } finally {156 Utils.close(r);157 155 } 158 156 } -
trunk/src/org/openstreetmap/josm/data/projection/datum/NTV2GridShiftFileWrapper.java
r6883 r7033 48 48 public NTV2GridShiftFile getShiftFile() { 49 49 if (instance == null) { 50 try { 51 InputStream is = new MirroredInputStream(gridFileName); 50 try (InputStream is = new MirroredInputStream(gridFileName)) { 52 51 instance = new NTV2GridShiftFile(); 53 52 instance.loadGridShiftFile(is, false); … … 58 57 return instance; 59 58 } 60 61 59 } -
trunk/src/org/openstreetmap/josm/data/validation/OsmValidator.java
r7005 r7033 171 171 File file = new File(getValidatorDir() + "ignorederrors"); 172 172 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))) { 176 174 for (String line = in.readLine(); line != null; line = in.readLine()) { 177 175 ignoredErrors.add(line); … … 181 179 } catch (final IOException e) { 182 180 Main.error(e); 183 } finally {184 Utils.close(in);185 181 } 186 182 } … … 197 193 198 194 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)) { 202 197 for (String e : ignoredErrors) { 203 198 out.println(e); … … 205 200 } catch (IOException e) { 206 201 Main.error(e); 207 } finally {208 Utils.close(out);209 202 } 210 203 } -
trunk/src/org/openstreetmap/josm/data/validation/tests/MapCSSTagChecker.java
r7027 r7033 453 453 Main.info(tr("Adding {0} to tag checker", i)); 454 454 } 455 MirroredInputStream s = new MirroredInputStream(i); 456 try { 455 try (MirroredInputStream s = new MirroredInputStream(i)) { 457 456 addMapCSS(new BufferedReader(UTFInputStreamReader.create(s))); 458 } finally {459 Utils.close(s);460 457 } 461 458 } catch (IOException ex) { -
trunk/src/org/openstreetmap/josm/data/validation/tests/OpeningHourTest.java
r7005 r7033 5 5 6 6 import java.io.InputStreamReader; 7 import java.io.Reader; 7 8 import java.util.ArrayList; 8 9 import java.util.Arrays; … … 51 52 super.initialize(); 52 53 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 } 69 73 } else { 70 74 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 54 54 import org.openstreetmap.josm.tools.GBC; 55 55 import org.openstreetmap.josm.tools.MultiMap; 56 import org.openstreetmap.josm.tools.Utils;57 56 58 57 /** … … 165 164 String errorSources = ""; 166 165 for (String source : Main.pref.getCollection(PREF_SOURCES, DEFAULT_SOURCES)) { 167 BufferedReader reader = null; 168 try { 166 try ( 169 167 MirroredInputStream s = new MirroredInputStream(source); 170 reader = new BufferedReader(UTFInputStreamReader.create(s));171 168 BufferedReader reader = new BufferedReader(UTFInputStreamReader.create(s)); 169 ) { 172 170 String okValue = null; 173 171 boolean tagcheckerfile = false; … … 242 240 } catch (IOException e) { 243 241 errorSources += source + "\n"; 244 } finally {245 Utils.close(reader);246 242 } 247 243 } -
trunk/src/org/openstreetmap/josm/gui/MainApplication.java
r7005 r7033 13 13 import java.awt.event.WindowEvent; 14 14 import java.io.File; 15 import java.io.InputStream; 15 16 import java.net.Authenticator; 16 17 import java.net.ProxySelector; … … 339 340 for (String i : args.get(Option.LOAD_PREFERENCES)) { 340 341 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); 343 344 } catch (Exception ex) { 344 345 throw new RuntimeException(ex); -
trunk/src/org/openstreetmap/josm/gui/dialogs/MapPaintDialog.java
r7030 r7033 24 24 import java.io.InputStream; 25 25 import java.io.InputStreamReader; 26 import java.io.OutputStream; 26 27 import java.util.ArrayList; 27 28 import java.util.Arrays; … … 516 517 getProgressMonitor().indeterminateSubTask( 517 518 tr("Save style ''{0}'' as ''{1}''", s.getDisplayString(), file.getPath())); 518 BufferedInputStream bis = null;519 BufferedOutputStream bos = null;520 519 try { 521 520 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 ) { 525 525 byte[] buffer = new byte[4096]; 526 526 int length; … … 533 533 } catch (IOException e) { 534 534 error = true; 535 } finally {536 Utils.close(bis);537 Utils.close(bos);538 535 } 539 536 } -
trunk/src/org/openstreetmap/josm/gui/download/PlaceSelection.java
r7017 r7033 15 15 import java.io.InputStream; 16 16 import java.io.InputStreamReader; 17 import java.io.Reader; 17 18 import java.net.HttpURLConnection; 18 19 import java.net.URL; … … 368 369 } 369 370 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 } 375 380 } catch(Exception e) { 376 381 if (canceled) -
trunk/src/org/openstreetmap/josm/gui/help/HelpBrowser.java
r6995 r7033 135 135 protected StyleSheet buildStyleSheet() { 136 136 StyleSheet ss = new StyleSheet(); 137 BufferedReader reader = new BufferedReader( 137 StringBuilder css = new StringBuilder(); 138 try (BufferedReader reader = new BufferedReader( 138 139 new InputStreamReader( 139 getClass().getResourceAsStream("/data/help-browser.css"), 140 Utils.UTF_8 140 getClass().getResourceAsStream("/data/help-browser.css"), Utils.UTF_8 141 141 ) 142 ); 143 StringBuilder css = new StringBuilder(); 144 try { 142 )) { 145 143 String line = null; 146 144 while ((line = reader.readLine()) != null) { … … 148 146 css.append("\n"); 149 147 } 150 } catch (Exception e) {148 } catch (Exception e) { 151 149 Main.error(tr("Failed to read CSS file ''help-browser.css''. Exception is: {0}", e.toString())); 152 150 Main.error(e); 153 151 return ss; 154 } finally {155 Utils.close(reader);156 152 } 157 153 ss.addRule(css.toString()); -
trunk/src/org/openstreetmap/josm/gui/io/DownloadFileTask.java
r6643 r7033 83 83 */ 84 84 public void download() throws DownloadException { 85 OutputStream out = null;86 InputStream in = null;87 85 try { 88 86 if (mkdir) { … … 105 103 progressMonitor.subTask(tr("Downloading File {0}: {1} bytes...", file.getName(),size)); 106 104 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 } 120 121 } 121 122 } 122 Utils.close(out);123 123 if (!canceled) { 124 124 Main.info(tr("Download finished")); … … 139 139 } finally { 140 140 closeConnectionIfNeeded(); 141 Utils.close(out);142 141 } 143 142 } … … 170 169 */ 171 170 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(); 179 173 while (es.hasMoreElements()) { 180 ze = (ZipEntry)es.nextElement();174 ZipEntry ze = es.nextElement(); 181 175 File newFile = new File(dir, ze.getName()); 182 176 if (ze.isDirectory()) { 183 177 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 ) { 187 182 byte[] buffer = new byte[8192]; 188 183 int read; … … 190 185 os.write(buffer, 0, read); 191 186 } 192 Utils.close(os);193 Utils.close(is);194 187 } 195 188 } 196 } finally {197 Utils.close(zf);198 189 } 199 190 } 200 191 } 201 -
trunk/src/org/openstreetmap/josm/gui/layer/TMSLayer.java
r7024 r7033 326 326 protected byte[] updateData() throws IOException { 327 327 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 } 333 333 } 334 334 } -
trunk/src/org/openstreetmap/josm/gui/layer/geoimage/CorrelateGpxWithImages.java
r7025 r7033 21 21 import java.io.File; 22 22 import java.io.FileInputStream; 23 import java.io.FileNotFoundException; 23 24 import java.io.IOException; 24 25 import java.io.InputStream; … … 171 172 } 172 173 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)) { 180 175 GpxReader reader = new GpxReader(iStream); 181 176 reader.parse(false); … … 211 206 } finally { 212 207 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); 213 216 } 214 217 } -
trunk/src/org/openstreetmap/josm/gui/mappaint/mapcss/MapCSSStyleSource.java
r7005 r7033 75 75 init(); 76 76 rules.clear(); 77 try { 78 InputStream in = getSourceInputStream(); 77 try (InputStream in = getSourceInputStream()) { 79 78 try { 80 79 // evaluate @media { ... } blocks -
trunk/src/org/openstreetmap/josm/gui/mappaint/xml/XmlStyleSource.java
r7005 r7033 75 75 init(); 76 76 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 ) { 80 81 XmlObjectParser parser = new XmlObjectParser(new XmlStyleSourceHandler(this)); 81 82 parser.startWithValidation(reader, … … 83 84 "resource://data/mappaint-style.xsd"); 84 85 while (parser.hasNext()); 85 } finally { 86 closeSourceInputStream(in); 87 } 88 86 } 89 87 } catch (IOException e) { 90 88 Main.warn(tr("Failed to load Mappaint styles from ''{0}''. Exception was: {1}", url, e.toString())); … … 377 375 } 378 376 } 379 380 377 } -
trunk/src/org/openstreetmap/josm/gui/tagging/TaggingPresetReader.java
r7005 r7033 225 225 public static Collection<TaggingPreset> readAll(String source, boolean validate) throws SAXException, IOException { 226 226 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) { 231 233 zipIcons = s.getFile(); 232 234 } 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)) { 235 236 tp = readAll(new BufferedReader(r), validate); 236 } finally { 237 Utils.close(r); 238 } 239 } finally { 240 Utils.close(s); 237 } 241 238 } 242 239 return tp; -
trunk/src/org/openstreetmap/josm/io/BoundingBoxDownloader.java
r6474 r7033 12 12 import org.openstreetmap.josm.gui.progress.ProgressMonitor; 13 13 import org.openstreetmap.josm.tools.CheckParameterUtil; 14 import org.openstreetmap.josm.tools.Utils;15 14 import org.xml.sax.SAXException; 16 15 … … 48 47 for (int i = 0;!done;++i) { 49 48 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 } 53 64 } 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);66 65 activeConnection = null; 67 66 } 68 result.fromServer = true; 67 if (result != null) { 68 result.fromServer = true; 69 } 69 70 return result; 70 71 } … … 113 114 public DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException { 114 115 progressMonitor.beginTask(tr("Contacting OSM Server..."), 10); 115 InputStream in = null;116 116 try { 117 117 DataSet ds = null; … … 119 119 if (crosses180th) { 120 120 // 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; 125 122 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 } 130 134 if (ds2 == null) 131 135 return null; … … 134 138 } else { 135 139 // 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 } 140 145 } 141 146 return ds; … … 146 151 } finally { 147 152 progressMonitor.finishTask(); 148 Utils.close(in);149 153 activeConnection = null; 150 154 } -
trunk/src/org/openstreetmap/josm/io/CacheCustomContent.java
r7026 r7033 145 145 */ 146 146 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))) { 150 148 this.data = new byte[input.available()]; 151 149 input.read(this.data); 152 150 } catch (IOException e) { 153 151 this.data = updateForce(); 154 } finally {155 Utils.close(input);156 152 } 157 153 } … … 161 157 */ 162 158 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))) { 166 160 output.write(this.data); 167 161 output.flush(); 168 } catch (Exception e) {162 } catch (IOException e) { 169 163 Main.error(e); 170 } finally {171 Utils.close(output);172 164 } 173 165 } -
trunk/src/org/openstreetmap/josm/io/CacheFiles.java
r7005 r7033 114 114 115 115 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 } 117 119 return bytes; 118 120 } catch (Exception e) { … … 135 137 } 136 138 // 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")) { 139 140 raf.write(data); 140 } finally {141 Utils.close(raf);142 141 } 143 142 } catch (Exception e) { -
trunk/src/org/openstreetmap/josm/io/Compression.java
r6882 r7033 75 75 * @throws IOException 76 76 */ 77 @SuppressWarnings("resource") 77 78 public static InputStream getUncompressedFileInputStream(File file) throws IOException { 78 79 return byExtension(file.getName()).getUncompressedInputStream(new FileInputStream(file)); … … 114 115 * @throws IOException 115 116 */ 117 @SuppressWarnings("resource") 116 118 public static OutputStream getCompressedFileOutputStream(File file) throws IOException { 117 119 return byExtension(file.getName()).getCompressedOutputStream(new FileOutputStream(file)); -
trunk/src/org/openstreetmap/josm/io/GeoJSONExporter.java
r6552 r7033 21 21 "json,geojson", "json", tr("GeoJSON Files") + " (*.json *.geojson)"); 22 22 23 /** 24 * Constructs a new {@code GeoJSONExporter}. 25 */ 23 26 public GeoJSONExporter() { 24 27 super(FILE_FILTER); … … 29 32 if (layer instanceof OsmDataLayer) { 30 33 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))) { 33 35 out.write(json); 34 } finally {35 Utils.close(out);36 36 } 37 37 } else { -
trunk/src/org/openstreetmap/josm/io/GpxImporter.java
r6798 r7033 76 76 @Override 77 77 public void importData(File file, ProgressMonitor progressMonitor) throws IOException { 78 final InputStream is = Compression.getUncompressedFileInputStream(file);79 78 final String fileName = file.getName(); 80 79 81 try {80 try (InputStream is = Compression.getUncompressedFileInputStream(file)) { 82 81 GpxReader r = new GpxReader(is); 83 82 boolean parsedProperly = r.parse(true); -
trunk/src/org/openstreetmap/josm/io/GpxReader.java
r7012 r7033 507 507 508 508 /** 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 510 511 * 511 512 * @param source the source input stream 512 513 * @throws IOException if an IO error occurs, e.g. the input stream is closed. 513 514 */ 515 @SuppressWarnings("resource") 514 516 public GpxReader(InputStream source) throws IOException { 515 517 Reader utf8stream = UTFInputStreamReader.create(source); -
trunk/src/org/openstreetmap/josm/io/GpxWriter.java
r6889 r7033 11 11 import java.util.Map; 12 12 import java.util.Map.Entry; 13 14 import javax.xml.XMLConstants; 13 15 14 16 import org.openstreetmap.josm.data.Bounds; … … 67 69 out.println("<gpx version=\"1.1\" creator=\"JOSM GPX export\" xmlns=\"http://www.topografix.com/GPX/1/1\"\n" + 68 70 (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" + 70 72 " xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">"); 71 73 indent = " "; -
trunk/src/org/openstreetmap/josm/io/MirroredInputStream.java
r7026 r7033 11 11 import java.io.IOException; 12 12 import java.io.InputStream; 13 import java.io.OutputStream; 13 14 import java.net.HttpURLConnection; 14 15 import java.net.MalformedURLException; … … 184 185 } 185 186 187 @SuppressWarnings("resource") 186 188 private Pair<String, InputStream> findZipEntryImpl(String extension, String namepart) { 187 189 if (file == null) … … 293 295 String localPath = "mirror_" + a; 294 296 destDirFile = new File(destDir, localPath + ".tmp"); 295 BufferedOutputStream bos = null;296 BufferedInputStream bis = null;297 297 try { 298 298 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 } 312 310 localFile = new File(destDir, localPath); 313 311 if(Main.platform.rename(destDirFile, localFile)) { … … 325 323 throw e; 326 324 } 327 } finally {328 Utils.close(bis);329 Utils.close(bos);330 325 } 331 326 -
trunk/src/org/openstreetmap/josm/io/MultiFetchServerObjectReader.java
r7005 r7033 5 5 import static org.openstreetmap.josm.tools.I18n.trn; 6 6 7 import java.io.IOException; 7 8 import java.io.InputStream; 8 9 import java.net.HttpURLConnection; … … 506 507 protected FetchResult multiGetIdPackage(OsmPrimitiveType type, Set<Long> pkg, ProgressMonitor progressMonitor) throws OsmTransferException { 507 508 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; 516 522 } 517 523 … … 527 533 protected DataSet singleGetId(OsmPrimitiveType type, long id, ProgressMonitor progressMonitor) throws OsmTransferException { 528 534 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; 537 548 } 538 549 -
trunk/src/org/openstreetmap/josm/io/NMEAImporter.java
r6798 r7033 7 7 import java.io.FileInputStream; 8 8 import java.io.IOException; 9 import java.io.InputStream; 9 10 10 11 import javax.swing.JOptionPane; … … 35 36 public void importData(File file, ProgressMonitor progressMonitor) throws IOException { 36 37 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 } 51 54 } 52 55 } 53 } 54 }); 56 }); 57 } 58 showNmeaInfobox(r.getNumberOfCoordinates() > 0, r); 55 59 } 56 showNmeaInfobox(r.getNumberOfCoordinates() > 0, r);57 60 } 58 61 -
trunk/src/org/openstreetmap/josm/io/OsmApi.java
r7030 r7033 290 290 private String toXml(IPrimitive o, boolean addBody) { 291 291 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 } 300 303 return swriter.toString(); 301 304 } … … 308 311 private String toXml(Changeset s) { 309 312 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 } 316 322 return swriter.toString(); 317 323 } … … 657 663 // If the API returned an error code like 403 forbidden, getInputStream 658 664 // 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(); 665 666 if (i != null) { 666 667 // the input stream can be null if both the input and the error stream … … 722 723 } 723 724 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 724 734 /** 725 735 * Replies the API capabilities -
trunk/src/org/openstreetmap/josm/io/OsmChangesetContentParser.java
r7012 r7033 123 123 * @throws IllegalArgumentException if source is {@code null}. 124 124 */ 125 @SuppressWarnings("resource") 125 126 public OsmChangesetContentParser(InputStream source) { 126 127 CheckParameterUtil.ensureParameterNotNull(source, "source"); -
trunk/src/org/openstreetmap/josm/io/OsmChangesetParser.java
r7012 r7033 41 41 */ 42 42 public final class OsmChangesetParser { 43 private List<Changeset> changesets;43 private final List<Changeset> changesets; 44 44 45 45 private OsmChangesetParser() { … … 219 219 * @throws IllegalDataException thrown if the an error was found while parsing the data from the source 220 220 */ 221 @SuppressWarnings("resource") 221 222 public static List<Changeset> parse(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException { 222 223 OsmChangesetParser parser = new OsmChangesetParser(); -
trunk/src/org/openstreetmap/josm/io/OsmExporter.java
r7029 r7033 23 23 public class OsmExporter extends FileExporter { 24 24 25 /** 26 * Constructs a new {@code OsmExporter}. 27 */ 25 28 public OsmExporter() { 26 29 super(OsmImporter.FILE_FILTER); … … 67 70 68 71 // 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 } 79 83 } 80 // FIXME - how to close?81 84 if (noBackup || !Main.pref.getBoolean("save.keepbackup", false)) { 82 85 if (tmpFile != null) { -
trunk/src/org/openstreetmap/josm/io/OsmReader.java
r7025 r7033 587 587 progressMonitor.indeterminateSubTask(tr("Parsing OSM data...")); 588 588 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 } 593 594 progressMonitor.worked(1); 594 595 -
trunk/src/org/openstreetmap/josm/io/OsmServerBackreferenceReader.java
r7005 r7033 18 18 import org.openstreetmap.josm.gui.progress.ProgressMonitor; 19 19 import org.openstreetmap.josm.tools.CheckParameterUtil; 20 import org.openstreetmap.josm.tools.Utils;21 20 22 21 /** … … 131 130 */ 132 131 protected DataSet getReferringWays(ProgressMonitor progressMonitor) throws OsmTransferException { 133 InputStream in = null;134 132 progressMonitor.beginTask(null, 2); 135 133 try { … … 139 137 .append("/").append(id).append("/ways"); 140 138 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 } 146 145 } catch(OsmTransferException e) { 147 146 throw e; … … 152 151 } finally { 153 152 progressMonitor.finishTask(); 154 Utils.close(in);155 153 activeConnection = null; 156 154 } … … 165 163 */ 166 164 protected DataSet getReferringRelations(ProgressMonitor progressMonitor) throws OsmTransferException { 167 InputStream in = null;168 165 progressMonitor.beginTask(null, 2); 169 166 try { … … 173 170 .append("/").append(id).append("/relations"); 174 171 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 } 180 178 } catch(OsmTransferException e) { 181 179 throw e; … … 186 184 } finally { 187 185 progressMonitor.finishTask(); 188 Utils.close(in);189 186 activeConnection = null; 190 187 } -
trunk/src/org/openstreetmap/josm/io/OsmServerChangesetReader.java
r7005 r7033 5 5 import static org.openstreetmap.josm.tools.I18n.trn; 6 6 7 import java.io.IOException; 7 8 import java.io.InputStream; 8 9 import java.text.MessageFormat; … … 12 13 import java.util.List; 13 14 15 import org.openstreetmap.josm.Main; 14 16 import org.openstreetmap.josm.data.osm.Changeset; 15 17 import org.openstreetmap.josm.data.osm.ChangesetDataSet; … … 53 55 public List<Changeset> queryChangesets(ChangesetQuery query, ProgressMonitor monitor) throws OsmTransferException { 54 56 CheckParameterUtil.ensureParameterNotNull(query, "query"); 57 List<Changeset> result = null; 55 58 if (monitor == null) { 56 59 monitor = NullProgressMonitor.INSTANCE; … … 60 63 StringBuilder sb = new StringBuilder(); 61 64 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 } 67 73 } catch(OsmTransferException e) { 68 74 throw e; … … 72 78 monitor.finishTask(); 73 79 } 80 return result; 74 81 } 75 82 … … 89 96 monitor = NullProgressMonitor.INSTANCE; 90 97 } 98 Changeset result = null; 91 99 try { 92 100 monitor.beginTask(tr("Reading changeset {0} ...",id)); 93 101 StringBuilder sb = new StringBuilder(); 94 102 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 } 103 114 } catch(OsmTransferException e) { 104 115 throw e; … … 108 119 monitor.finishTask(); 109 120 } 121 return result; 110 122 } 111 123 … … 137 149 StringBuilder sb = new StringBuilder(); 138 150 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); 146 162 } 147 ret.addAll(changesets);148 163 monitor.worked(1); 149 164 } … … 173 188 monitor = NullProgressMonitor.INSTANCE; 174 189 } 190 ChangesetDataSet result = null; 175 191 try { 176 192 monitor.beginTask(tr("Downloading changeset content")); 177 193 StringBuilder sb = new StringBuilder(); 178 194 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 } 185 204 } catch(XmlParsingException e) { 186 205 throw new OsmTransferException(e); … … 188 207 monitor.finishTask(); 189 208 } 209 return result; 190 210 } 191 211 } -
trunk/src/org/openstreetmap/josm/io/OsmServerHistoryReader.java
r6822 r7033 12 12 import org.openstreetmap.josm.gui.progress.ProgressMonitor; 13 13 import org.openstreetmap.josm.tools.CheckParameterUtil; 14 import org.openstreetmap.josm.tools.Utils;15 14 16 15 /** … … 56 55 */ 57 56 public HistoryDataSet parseHistory(ProgressMonitor progressMonitor) throws OsmTransferException { 58 InputStream in = null;59 57 progressMonitor.beginTask(""); 60 58 try { … … 64 62 .append("/").append(id).append("/history"); 65 63 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 } 72 71 } catch(OsmTransferException e) { 73 72 throw e; … … 78 77 } finally { 79 78 progressMonitor.finishTask(); 80 Utils.close(in);81 79 activeConnection = null; 82 80 } -
trunk/src/org/openstreetmap/josm/io/OsmServerObjectReader.java
r6830 r7033 14 14 import org.openstreetmap.josm.gui.progress.ProgressMonitor; 15 15 import org.openstreetmap.josm.tools.CheckParameterUtil; 16 import org.openstreetmap.josm.tools.Utils;17 16 18 17 /** … … 116 115 } 117 116 progressMonitor.beginTask("", 1); 118 InputStream in = null;119 117 try { 120 118 progressMonitor.indeterminateSubTask(tr("Downloading OSM data...")); … … 129 127 } 130 128 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 } 135 134 } catch(OsmTransferException e) { 136 135 if (cancel) return null; … … 141 140 } finally { 142 141 progressMonitor.finishTask(); 143 Utils.close(in);144 142 activeConnection = null; 145 143 } -
trunk/src/org/openstreetmap/josm/io/OsmServerReader.java
r6995 r7033 114 114 * @throws OsmTransferException thrown if data transfer errors occur 115 115 */ 116 @SuppressWarnings("resource") 116 117 protected InputStream getInputStreamRaw(String urlStr, ProgressMonitor progressMonitor, String reason, boolean uncompressAccordingToContentDisposition) throws OsmTransferException { 117 118 try { -
trunk/src/org/openstreetmap/josm/io/OsmServerUserInfoReader.java
r7005 r7033 167 167 monitor.beginTask(""); 168 168 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 } 173 174 } catch(OsmTransferException e) { 174 175 throw e; -
trunk/src/org/openstreetmap/josm/io/WMSLayerExporter.java
r6070 r7033 10 10 import org.openstreetmap.josm.gui.layer.WMSLayer; 11 11 import org.openstreetmap.josm.tools.CheckParameterUtil; 12 import org.openstreetmap.josm.tools.Utils;13 12 14 13 /** … … 31 30 CheckParameterUtil.ensureParameterNotNull(layer, "layer"); 32 31 if (layer instanceof WMSLayer) { 33 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file)); 34 try { 32 try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) { 35 33 ((WMSLayer)layer).writeExternal(oos); 36 } finally {37 Utils.close(oos);38 34 } 39 35 } -
trunk/src/org/openstreetmap/josm/io/WMSLayerImporter.java
r6070 r7033 15 15 import org.openstreetmap.josm.gui.util.GuiHelper; 16 16 import org.openstreetmap.josm.tools.CheckParameterUtil; 17 import org.openstreetmap.josm.tools.Utils;18 17 19 18 /** … … 50 49 public void importData(File file, ProgressMonitor progressMonitor) throws IOException, IllegalDataException { 51 50 CheckParameterUtil.ensureParameterNotNull(file, "file"); 52 ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file)); 53 try { 51 try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) { 54 52 wmsLayer.readExternal(ois); 55 53 } catch (ClassNotFoundException e) { 56 54 throw new IllegalDataException(e); 57 } finally {58 Utils.close(ois);59 55 } 60 56 -
trunk/src/org/openstreetmap/josm/io/imagery/ImageryReader.java
r7012 r7033 51 51 SAXParserFactory factory = SAXParserFactory.newInstance(); 52 52 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 } 57 58 } catch (SAXException e) { 58 59 throw e; -
trunk/src/org/openstreetmap/josm/io/imagery/WMSGrabber.java
r7012 r7033 173 173 174 174 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 175 InputStream is = new ProgressInputStream(conn, null); 176 try { 175 try (InputStream is = new ProgressInputStream(conn, null)) { 177 176 Utils.copyStream(is, baos); 178 } finally {179 Utils.close(is);180 177 } 181 178 … … 190 187 StringBuilder exception = new StringBuilder(); 191 188 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))) { 194 190 String line = null; 195 191 while( (line = br.readLine()) != null) { … … 199 195 } 200 196 return exception.toString(); 201 } finally {202 Utils.close(br);203 197 } 204 198 } -
trunk/src/org/openstreetmap/josm/io/imagery/WMSImagery.java
r7030 r7033 140 140 Main.info("GET " + getCapabilitiesUrl.toString()); 141 141 URLConnection openConnection = Utils.openHttpConnection(getCapabilitiesUrl); 142 InputStream inputStream = openConnection.getInputStream();143 142 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 ) { 145 148 String line; 146 149 while ((line = br.readLine()) != null) { … … 178 181 return x.getTextContent(); 179 182 } 180 } 181 ),new Predicate<String>() {183 }), 184 new Predicate<String>() { 182 185 @Override 183 186 public boolean evaluate(String format) { … … 209 212 throw new WMSGetCapabilitiesException(e, incomingData); 210 213 } 211 212 214 } 213 215 -
trunk/src/org/openstreetmap/josm/io/remotecontrol/RemoteControlHttpServer.java
r6643 r7033 83 83 Integer.toString(server.getLocalPort())); 84 84 while (true) { 85 try { 86 Socket request = server.accept(); 85 try (Socket request = server.accept()) { 87 86 RequestProcessor.processRequest(request); 88 } catch (SocketException se) {89 if ( !server.isClosed())87 } catch (SocketException se) { 88 if (!server.isClosed()) 90 89 Main.error(se); 91 90 } catch (IOException ioe) { -
trunk/src/org/openstreetmap/josm/io/remotecontrol/RemoteControlHttpsServer.java
r7004 r7033 56 56 57 57 // 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; 66 89 } 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;89 90 } 90 91 } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | … … 175 176 Integer.toString(server.getLocalPort())); 176 177 while (true) { 177 try { 178 Socket request = server.accept(); 178 try (Socket request = server.accept()) { 179 179 if (Main.isDebugEnabled() && request instanceof SSLSocket) { 180 180 SSLSocket sslSocket = (SSLSocket) request; -
trunk/src/org/openstreetmap/josm/io/session/GpxTracksSessionExporter.java
r7029 r7033 179 179 } 180 180 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 } 186 189 } 187 188 190 } -
trunk/src/org/openstreetmap/josm/io/session/GpxTracksSessionImporter.java
r6087 r7033 37 37 } 38 38 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 } 44 45 45 46 } catch (XPathExpressionException e) { … … 47 48 } 48 49 } 49 50 50 } -
trunk/src/org/openstreetmap/josm/io/session/MarkerSessionExporter.java
r7029 r7033 84 84 } 85 85 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 } 91 94 } 92 95 -
trunk/src/org/openstreetmap/josm/io/session/MarkerSessionImporter.java
r6093 r7033 41 41 } 42 42 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 } 54 55 } 56 57 MarkerLayer markerLayer = importData.getMarkerLayer(); 58 markerLayer.fromLayer = gpxLayer; 59 60 return markerLayer; 55 61 } 56 57 MarkerLayer markerLayer = importData.getMarkerLayer();58 markerLayer.fromLayer = gpxLayer;59 60 return markerLayer;61 62 62 } catch (XPathExpressionException e) { 63 63 throw new RuntimeException(e); -
trunk/src/org/openstreetmap/josm/io/session/OsmDataSessionExporter.java
r7029 r7033 212 212 } 213 213 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 } 223 226 } 224 227 } -
trunk/src/org/openstreetmap/josm/io/session/OsmDataSessionImporter.java
r6087 r7033 39 39 40 40 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 } 47 47 } catch (XPathExpressionException e) { 48 48 throw new RuntimeException(e); -
trunk/src/org/openstreetmap/josm/io/session/SessionReader.java
r7005 r7033 553 553 } 554 554 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 { 557 561 if (zip) { 558 562 try { 559 563 zipFile = new ZipFile(sessionFile); 560 josIS =getZipInputStream(zipFile);564 return getZipInputStream(zipFile); 561 565 } catch (ZipException ze) { 562 566 throw new IOException(ze); … … 564 568 } else { 565 569 try { 566 josIS =new FileInputStream(sessionFile);570 return new FileInputStream(sessionFile); 567 571 } catch (FileNotFoundException ex) { 568 572 throw new IOException(ex); 569 573 } 570 574 } 571 572 loadSession(josIS, sessionFile.toURI(), zip, progressMonitor);573 575 } 574 576 -
trunk/src/org/openstreetmap/josm/io/session/SessionWriter.java
r7005 r7033 240 240 241 241 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); 245 244 } catch (FileNotFoundException e) { 246 245 throw new IOException(e); 247 246 } 248 write(out);249 247 } 250 248 … … 262 260 writeJos(doc, new BufferedOutputStream(out)); 263 261 } 264 Utils.close(out);265 262 } 266 263 } -
trunk/src/org/openstreetmap/josm/plugins/Plugin.java
r6615 r7033 110 110 pluginDir.mkdirs(); 111 111 } 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 ) { 117 116 if (in == null) { 118 117 throw new IOException("Resource not found: "+from); … … 122 121 out.write(buffer, 0, len); 123 122 } 124 } finally {125 Utils.close(in);126 Utils.close(out);127 123 } 128 124 } -
trunk/src/org/openstreetmap/josm/plugins/PluginDownloadTask.java
r7005 r7033 24 24 import org.openstreetmap.josm.io.MirroredInputStream; 25 25 import org.openstreetmap.josm.tools.CheckParameterUtil; 26 import org.openstreetmap.josm.tools.Utils;27 26 import org.xml.sax.SAXException; 28 27 … … 118 117 throw new PluginDownloadException(tr("Download skipped")); 119 118 } 120 OutputStream out = null;121 InputStream in = null;122 119 try { 123 120 if (pi.downloadlink == null) { … … 130 127 downloadConnection = MirroredInputStream.connectFollowingRedirect(url, PLUGIN_MIME_TYPES); 131 128 } 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 } 137 137 } 138 138 } catch (MalformedURLException e) { … … 145 145 throw new PluginDownloadException(e); 146 146 } finally { 147 Utils.close(in);148 147 synchronized(this) { 149 148 downloadConnection = null; 150 149 } 151 Utils.close(out);152 150 } 153 151 } -
trunk/src/org/openstreetmap/josm/plugins/PluginInformation.java
r7005 r7033 107 107 this.name = name; 108 108 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 ) { 114 113 Manifest manifest = jar.getManifest(); 115 114 if (manifest == null) … … 119 118 } catch (IOException e) { 120 119 throw new PluginException(name, e); 121 } finally {122 Utils.close(jar);123 Utils.close(fis);124 120 } 125 121 } … … 380 376 String name = pluginName; 381 377 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 } 385 385 386 386 Collection<String> locations = getPluginLocations(); -
trunk/src/org/openstreetmap/josm/plugins/ReadLocalPluginInformationTask.java
r7005 r7033 172 172 173 173 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)) { 177 175 List<PluginInformation> pis = new PluginListParser().parse(fin); 178 176 for (PluginInformation pi : pis) { … … 185 183 } catch(IOException e) { 186 184 throw new PluginListParseException(e); 187 } finally {188 Utils.close(fin);189 185 } 190 186 } -
trunk/src/org/openstreetmap/josm/plugins/ReadRemotePluginInformationTask.java
r7005 r7033 203 203 204 204 private void handleIOException(final ProgressMonitor monitor, IOException e, final String title, final String firstMessage, boolean displayMsg) { 205 InputStream errStream = connection.getErrorStream();206 205 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); 221 224 } 222 225 final String msg = e.getMessage(); … … 265 268 */ 266 269 protected void downloadPluginIcons(String site, File destFile, ProgressMonitor monitor) { 267 InputStream in = null;268 OutputStream out = null;269 270 try { 270 271 site = site.replaceAll("%<(.*)>", ""); … … 278 279 connection.setRequestProperty("Cache-Control", "no-cache"); 279 280 } 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 } 285 289 } 286 290 } catch (MalformedURLException e) { … … 293 297 return; 294 298 } finally { 295 Utils.close(out);296 299 synchronized(this) { 297 300 if (connection != null) { … … 300 303 connection = null; 301 304 } 302 Utils.close(in);303 305 monitor.finishTask(); 304 306 } … … 321 323 */ 322 324 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))) { 332 332 writer.write(list); 333 writer.flush(); 333 334 } catch(IOException e) { 334 335 // just failed to write the cache file. No big deal, but log the exception anyway 335 336 Main.error(e); 336 } finally {337 if (writer != null) {338 writer.flush();339 Utils.close(writer);340 }341 337 } 342 338 } -
trunk/src/org/openstreetmap/josm/tools/AudioUtil.java
r7029 r7033 31 31 */ 32 32 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())))) { 36 35 AudioFormat audioFormat = audioInputStream.getFormat(); 37 36 long filesize = wavFile.length(); -
trunk/src/org/openstreetmap/josm/tools/I18n.java
r7012 r7033 397 397 if ("en".equals(loadedCode)) 398 398 return; 399 FileInputStream fis = null;400 JarInputStream jar = null;401 FileInputStream fisTrans = null;402 JarInputStream jarTrans = null;403 399 String enfile = "data/en.lang"; 404 400 String langfile = "data/"+loadedCode+".lang"; 405 try 406 { 401 try ( 402 FileInputStream fis = new FileInputStream(source); 403 JarInputStream jar = new JarInputStream(fis) 404 ) { 407 405 ZipEntry e; 408 fis = new FileInputStream(source);409 jar = new JarInputStream(fis);410 406 boolean found = false; 411 while(!found && (e = jar.getNextEntry()) != null) 412 { 407 while (!found && (e = jar.getNextEntry()) != null) { 413 408 String name = e.getName(); 414 409 if(name.equals(enfile)) 415 410 found = true; 416 411 } 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); 427 425 } 428 if(found) 429 load(jar, jarTrans, true); 430 } 431 } catch(IOException e) { 426 } 427 } catch (IOException e) { 432 428 // Ignore 433 } finally {434 Utils.close(jar);435 Utils.close(fis);436 Utils.close(jarTrans);437 Utils.close(fisTrans);438 429 } 439 430 } … … 460 451 return false; 461 452 } 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 ) { 467 457 if (load(enStream, trStream, false)) { 468 458 pluralMode = languages.get(l); … … 470 460 return true; 471 461 } 472 } catch (IOException e) {462 } catch (IOException e) { 473 463 // Ignore exception 474 } finally {475 Utils.close(trStream);476 Utils.close(enStream);477 464 } 478 465 return false; -
trunk/src/org/openstreetmap/josm/tools/ImageProvider.java
r7025 r7033 504 504 505 505 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())) { 510 508 switch (type) { 511 509 case SVG: … … 526 524 } catch (IOException e) { 527 525 return null; 528 } finally {529 Utils.close(is);530 526 } 531 527 } … … 603 599 604 600 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)) { 608 602 if (inArchiveDir == null || ".".equals(inArchiveDir)) { 609 603 inArchiveDir = ""; … … 613 607 String entryName = inArchiveDir + fullName; 614 608 ZipEntry entry = zipFile.getEntry(entryName); 615 if(entry != null) 616 { 609 if (entry != null) { 617 610 int size = (int)entry.getSize(); 618 611 int offs = 0; 619 612 byte[] buf = new byte[size]; 620 InputStream is = null; 621 try { 622 is = zipFile.getInputStream(entry); 613 try (InputStream is = zipFile.getInputStream(entry)) { 623 614 switch (type) { 624 615 case SVG: … … 641 632 return img == null ? null : new ImageResource(img); 642 633 default: 643 throw new AssertionError( );634 throw new AssertionError("Unknown ImageType: "+type); 644 635 } 645 } finally {646 Utils.close(is);647 636 } 648 637 } 649 638 } catch (Exception e) { 650 639 Main.warn(tr("Failed to handle zip file ''{0}''. Exception was: {1}", archive.getName(), e.toString())); 651 } finally {652 Utils.close(zipFile);653 640 } 654 641 return null; … … 785 772 }); 786 773 787 parser.parse(new InputSource(new MirroredInputStream(774 try (InputStream is = new MirroredInputStream( 788 775 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 } 791 780 } catch (SAXReturnException r) { 792 781 return r.getResult(); -
trunk/src/org/openstreetmap/josm/tools/PlatformHookUnixoid.java
r7012 r7033 283 283 File file = new File(path); 284 284 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))) { 288 286 String id = null; 289 287 String release = null; … … 313 311 } catch (IOException e) { 314 312 // Ignore 315 } finally {316 Utils.close(reader);317 313 } 318 314 } -
trunk/src/org/openstreetmap/josm/tools/WikiReader.java
r6898 r7033 43 43 public String read(String url) throws IOException { 44 44 URL u = new URL(url); 45 BufferedReader in = Utils.openURLReader(u); 46 try { 45 try (BufferedReader in = Utils.openURLReader(u)) { 47 46 if (url.startsWith(baseurl) && !url.endsWith("?format=txt")) 48 47 return readFromTrac(in, u); 49 48 return readNormal(in); 50 } finally {51 Utils.close(in);52 49 } 53 50 } … … 84 81 85 82 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); 89 85 } catch (IOException e) { 90 86 Main.addNetworkError(url, Utils.getRootCause(e)); 91 87 throw e; 92 }93 try {94 return readFromTrac(in, url);95 } finally {96 Utils.close(in);97 88 } 98 89 } -
trunk/src/org/openstreetmap/josm/tools/XmlObjectParser.java
r7012 r7033 5 5 6 6 import java.io.IOException; 7 import java.io.InputStream; 7 8 import java.io.Reader; 8 9 import java.lang.reflect.Field; … … 17 18 import java.util.Stack; 18 19 20 import javax.xml.XMLConstants; 19 21 import javax.xml.parsers.ParserConfigurationException; 20 22 import javax.xml.parsers.SAXParser; … … 278 280 279 281 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)); 283 285 ValidatorHandler validator = schema.newValidatorHandler(); 284 286 validator.setContentHandler(parser);
Note:
See TracChangeset
for help on using the changeset viewer.