diff --git a/cli/src/main/java/hudson/cli/PrivateKeyProvider.java b/cli/src/main/java/hudson/cli/PrivateKeyProvider.java index 834bb72342..5fe402afc6 100644 --- a/cli/src/main/java/hudson/cli/PrivateKeyProvider.java +++ b/cli/src/main/java/hudson/cli/PrivateKeyProvider.java @@ -127,15 +127,11 @@ public class PrivateKeyProvider { } private static String readPemFile(File f) throws IOException{ - FileInputStream is = new FileInputStream(f); - try { - DataInputStream dis = new DataInputStream(is); + try (FileInputStream is = new FileInputStream(f); + DataInputStream dis = new DataInputStream(is)) { byte[] bytes = new byte[(int) f.length()]; dis.readFully(bytes); - dis.close(); return new String(bytes); - } finally { - is.close(); } } diff --git a/core/src/main/java/hudson/ClassicPluginStrategy.java b/core/src/main/java/hudson/ClassicPluginStrategy.java index ff933347c3..792e02a0b7 100644 --- a/core/src/main/java/hudson/ClassicPluginStrategy.java +++ b/core/src/main/java/hudson/ClassicPluginStrategy.java @@ -107,11 +107,8 @@ public class ClassicPluginStrategy implements PluginStrategy { if (isLinked(archive)) { manifest = loadLinkedManifest(archive); } else { - JarFile jf = new JarFile(archive, false); - try { + try (JarFile jf = new JarFile(archive, false)) { manifest = jf.getManifest(); - } finally { - jf.close(); } } return PluginWrapper.computeShortName(manifest, archive.getName()); @@ -176,11 +173,8 @@ public class ClassicPluginStrategy implements PluginStrategy { "Plugin installation failed. No manifest at " + manifestFile); } - FileInputStream fin = new FileInputStream(manifestFile); - try { + try (FileInputStream fin = new FileInputStream(manifestFile)) { manifest = new Manifest(fin); - } finally { - fin.close(); } } @@ -646,14 +640,13 @@ public class ClassicPluginStrategy implements PluginStrategy { final long dirTime = archive.lastModified(); // this ZipOutputStream is reused and not created for each directory - final ZipOutputStream wrappedZOut = new ZipOutputStream(new NullOutputStream()) { + try (ZipOutputStream wrappedZOut = new ZipOutputStream(new NullOutputStream()) { @Override public void putNextEntry(ZipEntry ze) throws IOException { ze.setTime(dirTime+1999); // roundup super.putNextEntry(ze); } - }; - try { + }) { Zip z = new Zip() { /** * Forces the fixed timestamp for directories to make sure @@ -672,8 +665,6 @@ public class ClassicPluginStrategy implements PluginStrategy { z.setDestFile(classesJar); z.add(mapper); z.execute(); - } finally { - wrappedZOut.close(); } } diff --git a/core/src/main/java/hudson/FilePath.java b/core/src/main/java/hudson/FilePath.java index 6b2529eabe..361e907ba4 100644 --- a/core/src/main/java/hudson/FilePath.java +++ b/core/src/main/java/hudson/FilePath.java @@ -389,11 +389,8 @@ public final class FilePath implements Serializable { } public void zip(FilePath dst) throws IOException, InterruptedException { - OutputStream os = dst.write(); - try { + try (OutputStream os = dst.write()) { zip(os); - } finally { - os.close(); } } @@ -594,11 +591,8 @@ public final class FilePath implements Serializable { if (p != null) { mkdirs(p); } - InputStream input = zip.getInputStream(e); - try { + try (InputStream input = zip.getInputStream(e)) { IOUtils.copy(input, writing(f)); - } finally { - input.close(); } try { FilePath target = new FilePath(f); @@ -868,8 +862,7 @@ public final class FilePath implements Serializable { this.archive = archive; } @Override public Void invoke(File dir, VirtualChannel channel) throws IOException, InterruptedException { - InputStream in = archive.openStream(); - try { + try (InputStream in = archive.openStream()) { CountingInputStream cis = new CountingInputStream(in); try { if (archive.toExternalForm().endsWith(".zip")) { @@ -880,8 +873,6 @@ public final class FilePath implements Serializable { } catch (IOException x) { throw new IOException(String.format("Failed to unpack %s (%d bytes read)", archive, cis.getByteCount()), x); } - } finally { - in.close(); } return null; } @@ -894,11 +885,8 @@ public final class FilePath implements Serializable { * @since 1.293 */ public void copyFrom(URL url) throws IOException, InterruptedException { - InputStream in = url.openStream(); - try { + try (InputStream in = url.openStream()) { copyFrom(in); - } finally { - in.close(); } } @@ -908,11 +896,8 @@ public final class FilePath implements Serializable { * @since 1.293 */ public void copyFrom(InputStream in) throws IOException, InterruptedException { - OutputStream os = write(); - try { + try (OutputStream os = write()) { org.apache.commons.io.IOUtils.copy(in, os); - } finally { - os.close(); } } @@ -938,16 +923,9 @@ public final class FilePath implements Serializable { throw new IOException(e); } } else { - InputStream i = file.getInputStream(); - OutputStream o = write(); - try { + try (InputStream i = file.getInputStream(); + OutputStream o = write()) { org.apache.commons.io.IOUtils.copy(i,o); - } finally { - try { - o.close(); - } finally { - i.close(); - } } } } @@ -1396,11 +1374,8 @@ public final class FilePath implements Serializable { throw new IOException("Failed to create a temporary directory in "+dir,e); } - Writer w = new FileWriter(writing(f)); - try { + try (Writer w = new FileWriter(writing(f))) { w.write(contents); - } finally { - w.close(); } return f.getAbsolutePath(); @@ -1877,11 +1852,8 @@ public final class FilePath implements Serializable { * Reads this file into a string, by using the current system encoding. */ public String readToString() throws IOException, InterruptedException { - InputStream in = read(); - try { + try (InputStream in = read()) { return org.apache.commons.io.IOUtils.toString(in); - } finally { - in.close(); } } @@ -1931,11 +1903,8 @@ public final class FilePath implements Serializable { public Void invoke(File f, VirtualChannel channel) throws IOException { mkdirs(f.getParentFile()); FileOutputStream fos = new FileOutputStream(writing(f)); - Writer w = encoding != null ? new OutputStreamWriter(fos, encoding) : new OutputStreamWriter(fos); - try { + try (Writer w = encoding != null ? new OutputStreamWriter(fos, encoding) : new OutputStreamWriter(fos)) { w.write(content); - } finally { - w.close(); } return null; } @@ -2008,11 +1977,8 @@ public final class FilePath implements Serializable { */ public void copyTo(FilePath target) throws IOException, InterruptedException { try { - OutputStream out = target.write(); - try { + try (OutputStream out = target.write()) { copyTo(out); - } finally { - out.close(); } } catch (IOException e) { throw new IOException("Failed to copy "+this+" to "+target,e); @@ -2198,11 +2164,9 @@ public final class FilePath implements Serializable { Future future = target.actAsync(new SecureFileCallable() { private static final long serialVersionUID = 1L; public Void invoke(File f, VirtualChannel channel) throws IOException { - try { - readFromTar(remote + '/' + description, f,TarCompression.GZIP.extract(pipe.getIn())); + try (InputStream in = pipe.getIn()) { + readFromTar(remote + '/' + description, f,TarCompression.GZIP.extract(in)); return null; - } finally { - pipe.getIn().close(); } } }); @@ -2226,10 +2190,8 @@ public final class FilePath implements Serializable { Future future = actAsync(new SecureFileCallable() { private static final long serialVersionUID = 1L; public Integer invoke(File f, VirtualChannel channel) throws IOException { - try { - return writeToTar(f, scanner, TarCompression.GZIP.compress(pipe.getOut())); - } finally { - pipe.getOut().close(); + try (OutputStream out = pipe.getOut()) { + return writeToTar(f, scanner, TarCompression.GZIP.compress(out)); } } }); @@ -2298,14 +2260,13 @@ public final class FilePath implements Serializable { * @since TODO supports large files > 10 GB, migration to commons-compress */ private void readFromTar(String name, File baseDir, InputStream in) throws IOException { - TarArchiveInputStream t = new TarArchiveInputStream(in); - + // TarInputStream t = new TarInputStream(in); - try { + try (TarArchiveInputStream t = new TarArchiveInputStream(in)) { TarArchiveEntry te; while ((te = t.getNextTarEntry()) != null) { - File f = new File(baseDir,te.getName()); - if(te.isDirectory()) { + File f = new File(baseDir, te.getName()); + if (te.isDirectory()) { mkdirs(f); } else { File parent = f.getParentFile(); @@ -2315,22 +2276,20 @@ public final class FilePath implements Serializable { if (te.isSymbolicLink()) { new FilePath(f).symlinkTo(te.getLinkName(), TaskListener.NULL); } else { - IOUtils.copy(t,f); + IOUtils.copy(t, f); f.setLastModified(te.getModTime().getTime()); - int mode = te.getMode()&0777; - if(mode!=0 && !Functions.isWindows()) // be defensive - _chmod(f,mode); + int mode = te.getMode() & 0777; + if (mode != 0 && !Functions.isWindows()) // be defensive + _chmod(f, mode); } } } - } catch(IOException e) { - throw new IOException("Failed to extract "+name,e); + } catch (IOException e) { + throw new IOException("Failed to extract " + name, e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // process this later - throw new IOException("Failed to extract "+name,e); - } finally { - t.close(); + throw new IOException("Failed to extract " + name, e); } } diff --git a/core/src/main/java/hudson/FileSystemProvisioner.java b/core/src/main/java/hudson/FileSystemProvisioner.java index 60978a0048..8b9967e2bb 100644 --- a/core/src/main/java/hudson/FileSystemProvisioner.java +++ b/core/src/main/java/hudson/FileSystemProvisioner.java @@ -215,11 +215,8 @@ public abstract class FileSystemProvisioner implements ExtensionPoint, Describab */ public WorkspaceSnapshot snapshot(AbstractBuild build, FilePath ws, String glob, TaskListener listener) throws IOException, InterruptedException { File wss = new File(build.getRootDir(),"workspace.tgz"); - OutputStream os = new BufferedOutputStream(new FileOutputStream(wss)); - try { - ws.archive(ArchiverFactory.TARGZ,os,glob); - } finally { - os.close(); + try (OutputStream os = new BufferedOutputStream(new FileOutputStream(wss))) { + ws.archive(ArchiverFactory.TARGZ, os, glob); } return new WorkspaceSnapshotImpl(); } diff --git a/core/src/main/java/hudson/PluginWrapper.java b/core/src/main/java/hudson/PluginWrapper.java index 28f91a6740..9c26aae26c 100644 --- a/core/src/main/java/hudson/PluginWrapper.java +++ b/core/src/main/java/hudson/PluginWrapper.java @@ -708,11 +708,8 @@ public class PluginWrapper implements Comparable, ModelObject { File backup = getBackupFile(); if (backup.exists()) { try { - JarFile backupPlugin = new JarFile(backup); - try { + try (JarFile backupPlugin = new JarFile(backup)) { return backupPlugin.getManifest().getMainAttributes().getValue("Plugin-Version"); - } finally { - backupPlugin.close(); } } catch (IOException e) { LOGGER.log(WARNING, "Failed to get backup version from " + backup, e); diff --git a/core/src/main/java/hudson/Util.java b/core/src/main/java/hudson/Util.java index f0afeae5c6..f8e0205889 100644 --- a/core/src/main/java/hudson/Util.java +++ b/core/src/main/java/hudson/Util.java @@ -198,14 +198,11 @@ public class Util { StringBuilder str = new StringBuilder((int)logfile.length()); - BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(logfile),charset)); - try { + try (BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(logfile), charset))) { char[] buf = new char[1024]; int len; - while((len=r.read(buf,0,buf.length))>0) - str.append(buf,0,len); - } finally { - r.close(); + while ((len = r.read(buf, 0, buf.length)) > 0) + str.append(buf, 0, len); } return str.toString(); @@ -768,12 +765,9 @@ public class Util { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] buffer = new byte[1024]; - DigestInputStream in =new DigestInputStream(source,md5); - try { - while(in.read(buffer)>=0) + try (DigestInputStream in = new DigestInputStream(source, md5)) { + while (in.read(buffer) >= 0) ; // simply discard the input - } finally { - in.close(); } return toHexString(md5.digest()); } catch (NoSuchAlgorithmException e) { @@ -806,11 +800,8 @@ public class Util { */ @Nonnull public static String getDigestOf(@Nonnull File file) throws IOException { - InputStream is = new FileInputStream(file); - try { + try (InputStream is = new FileInputStream(file)) { return getDigestOf(new BufferedInputStream(is)); - } finally { - is.close(); } } diff --git a/core/src/main/java/hudson/XmlFile.java b/core/src/main/java/hudson/XmlFile.java index 00eae060e9..0e7f4ee96a 100644 --- a/core/src/main/java/hudson/XmlFile.java +++ b/core/src/main/java/hudson/XmlFile.java @@ -137,15 +137,10 @@ public final class XmlFile { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Reading "+file); } - InputStream in = new BufferedInputStream(new FileInputStream(file)); - try { + try (InputStream in = new BufferedInputStream(new FileInputStream(file))) { return xs.fromXML(in); - } catch (XStreamException e) { + } catch (XStreamException | Error e) { throw new IOException("Unable to read "+file,e); - } catch(Error e) {// mostly reflection errors - throw new IOException("Unable to read "+file,e); - } finally { - in.close(); } } @@ -157,16 +152,12 @@ public final class XmlFile { * if the XML representation is completely new. */ public Object unmarshal( Object o ) throws IOException { - InputStream in = new BufferedInputStream(new FileInputStream(file)); - try { + + try (InputStream in = new BufferedInputStream(new FileInputStream(file))) { // TODO: expose XStream the driver from XStream return xs.unmarshal(DEFAULT_DRIVER.createReader(in), o); - } catch (XStreamException e) { + } catch (XStreamException | Error e) { throw new IOException("Unable to read "+file,e); - } catch(Error e) {// mostly reflection errors - throw new IOException("Unable to read "+file,e); - } finally { - in.close(); } } @@ -224,11 +215,8 @@ public final class XmlFile { * Writer will not be closed by the implementation. */ public void writeRawTo(Writer w) throws IOException { - Reader r = readRaw(); - try { - Util.copyStream(r,w); - } finally { - r.close(); + try (Reader r = readRaw()) { + Util.copyStream(r, w); } } @@ -247,10 +235,10 @@ public final class XmlFile { this.encoding = encoding; } } - InputSource input = new InputSource(file.toURI().toASCIIString()); - input.setByteStream(new FileInputStream(file)); - try { + try (InputStream in = new FileInputStream(file)) { + InputSource input = new InputSource(file.toURI().toASCIIString()); + input.setByteStream(in); JAXP.newSAXParser().parse(input,new DefaultHandler() { private Locator loc; @Override @@ -292,9 +280,6 @@ public final class XmlFile { throw new IOException("Failed to detect encoding of "+file,e); } catch (ParserConfigurationException e) { throw new AssertionError(e); // impossible - } finally { - // some JAXP implementations appear to leak the file handle if we just call parse(File,DefaultHandler) - input.getByteStream().close(); } } diff --git a/core/src/main/java/hudson/cli/ClientAuthenticationCache.java b/core/src/main/java/hudson/cli/ClientAuthenticationCache.java index 7c2127bc6d..fb75441786 100644 --- a/core/src/main/java/hudson/cli/ClientAuthenticationCache.java +++ b/core/src/main/java/hudson/cli/ClientAuthenticationCache.java @@ -51,11 +51,8 @@ public class ClientAuthenticationCache implements Serializable { } }); if (store.exists()) { - InputStream istream = store.read(); - try { + try (InputStream istream = store.read()) { props.load(istream); - } finally { - istream.close(); } } } @@ -109,11 +106,8 @@ public class ClientAuthenticationCache implements Serializable { } private void save() throws IOException, InterruptedException { - OutputStream os = store.write(); - try { - props.store(os,"Credential store"); - } finally { - os.close(); + try (OutputStream os = store.write()) { + props.store(os, "Credential store"); } // try to protect this file from other users, if we can. store.chmod(0600); diff --git a/core/src/main/java/hudson/cli/ConsoleCommand.java b/core/src/main/java/hudson/cli/ConsoleCommand.java index 92fd0e74c6..f4c3f719b5 100644 --- a/core/src/main/java/hudson/cli/ConsoleCommand.java +++ b/core/src/main/java/hudson/cli/ConsoleCommand.java @@ -78,12 +78,9 @@ public class ConsoleCommand extends CLICommand { pos = logText.writeLogTo(pos, w); } while (!logText.isComplete()); } else { - InputStream logInputStream = run.getLogInputStream(); - try { - IOUtils.skip(logInputStream,pos); - org.apache.commons.io.IOUtils.copy(new InputStreamReader(logInputStream,run.getCharset()),w); - } finally { - logInputStream.close(); + try (InputStream logInputStream = run.getLogInputStream()) { + IOUtils.skip(logInputStream, pos); + IOUtils.copy(new InputStreamReader(logInputStream, run.getCharset()), w); } } } finally { diff --git a/core/src/main/java/hudson/cli/util/ScriptLoader.java b/core/src/main/java/hudson/cli/util/ScriptLoader.java index e2252efbd5..8484c1e959 100644 --- a/core/src/main/java/hudson/cli/util/ScriptLoader.java +++ b/core/src/main/java/hudson/cli/util/ScriptLoader.java @@ -35,11 +35,8 @@ public class ScriptLoader extends MasterToSlaveCallable { } catch (MalformedURLException e) { throw new AbortException("Unable to find a script "+script); } - InputStream s = url.openStream(); - try { + try (InputStream s = url.openStream()) { return IOUtils.toString(s); - } finally { - s.close(); } } } diff --git a/core/src/main/java/hudson/console/ConsoleNote.java b/core/src/main/java/hudson/console/ConsoleNote.java index c27fec6364..7ef15fee93 100644 --- a/core/src/main/java/hudson/console/ConsoleNote.java +++ b/core/src/main/java/hudson/console/ConsoleNote.java @@ -170,11 +170,8 @@ public abstract class ConsoleNote implements Serializable, Describable implements Serializable, Describable'+getHudsonWar().getAbsolutePath()+'\n'); - } finally { - w.close(); + try (FileWriter w = new FileWriter(copyFiles, true)) { + w.write(by.getAbsolutePath() + '>' + getHudsonWar().getAbsolutePath() + '\n'); } } diff --git a/core/src/main/java/hudson/model/AbstractItem.java b/core/src/main/java/hudson/model/AbstractItem.java index 3dd2b32603..9bcfb70184 100644 --- a/core/src/main/java/hudson/model/AbstractItem.java +++ b/core/src/main/java/hudson/model/AbstractItem.java @@ -673,9 +673,7 @@ public abstract class AbstractItem extends Actionable implements Item, HttpDelet try { XMLUtils.safeTransform(source, new StreamResult(out)); out.close(); - } catch (TransformerException e) { - throw new IOException("Failed to persist config.xml", e); - } catch (SAXException e) { + } catch (TransformerException | SAXException e) { throw new IOException("Failed to persist config.xml", e); } diff --git a/core/src/main/java/hudson/model/Api.java b/core/src/main/java/hudson/model/Api.java index 258f48ffea..6878a4284a 100644 --- a/core/src/main/java/hudson/model/Api.java +++ b/core/src/main/java/hudson/model/Api.java @@ -169,8 +169,7 @@ public class Api extends AbstractModelObject { } // switch to gzipped output - OutputStream o = rsp.getCompressedOutputStream(req); - try { + try (OutputStream o = rsp.getCompressedOutputStream(req)) { if (isSimpleOutput(result)) { // simple output allowed rsp.setContentType("text/plain;charset=UTF-8"); @@ -182,8 +181,6 @@ public class Api extends AbstractModelObject { // otherwise XML rsp.setContentType("application/xml;charset=UTF-8"); new XMLWriter(o).write(result); - } finally { - o.close(); } } diff --git a/core/src/main/java/hudson/model/Computer.java b/core/src/main/java/hudson/model/Computer.java index 00f52e197c..226ad5fb48 100644 --- a/core/src/main/java/hudson/model/Computer.java +++ b/core/src/main/java/hudson/model/Computer.java @@ -1365,19 +1365,19 @@ public /*transient*/ abstract class Computer extends Actionable implements Acces checkPermission(Jenkins.ADMINISTER); rsp.setContentType("text/plain"); - PrintWriter w = new PrintWriter(rsp.getCompressedWriter(req)); - VirtualChannel vc = getChannel(); - if (vc instanceof Channel) { - w.println("Master to slave"); - ((Channel)vc).dumpExportTable(w); - w.flush(); // flush here once so that even if the dump from the agent fails, the client gets some useful info + try (PrintWriter w = new PrintWriter(rsp.getCompressedWriter(req))) { + VirtualChannel vc = getChannel(); + if (vc instanceof Channel) { + w.println("Master to slave"); + ((Channel) vc).dumpExportTable(w); + w.flush(); // flush here once so that even if the dump from the agent fails, the client gets some useful info - w.println("\n\n\nSlave to master"); - w.print(vc.call(new DumpExportTableTask())); - } else { - w.println(Messages.Computer_BadChannel()); + w.println("\n\n\nSlave to master"); + w.print(vc.call(new DumpExportTableTask())); + } else { + w.println(Messages.Computer_BadChannel()); + } } - w.close(); } private static final class DumpExportTableTask extends MasterToSlaveCallable { diff --git a/core/src/main/java/hudson/model/DirectoryBrowserSupport.java b/core/src/main/java/hudson/model/DirectoryBrowserSupport.java index bf7885030d..418efca879 100644 --- a/core/src/main/java/hudson/model/DirectoryBrowserSupport.java +++ b/core/src/main/java/hudson/model/DirectoryBrowserSupport.java @@ -223,8 +223,7 @@ public final class DirectoryBrowserSupport implements HttpResponse { } if (plain) { rsp.setContentType("text/plain;charset=UTF-8"); - OutputStream os = rsp.getOutputStream(); - try { + try (OutputStream os = rsp.getOutputStream()) { for (VirtualFile kid : baseFile.list()) { os.write(kid.getName().getBytes("UTF-8")); if (kid.isDirectory()) { @@ -233,8 +232,6 @@ public final class DirectoryBrowserSupport implements HttpResponse { os.write('\n'); } os.flush(); - } finally { - os.close(); } return; } @@ -356,33 +353,33 @@ public final class DirectoryBrowserSupport implements HttpResponse { } private static void zip(OutputStream outputStream, VirtualFile dir, String glob) throws IOException { - ZipOutputStream zos = new ZipOutputStream(outputStream); - zos.setEncoding(System.getProperty("file.encoding")); // TODO JENKINS-20663 make this overridable via query parameter - for (String n : dir.list(glob.length() == 0 ? "**" : glob)) { - String relativePath; - if (glob.length() == 0) { - // JENKINS-19947: traditional behavior is to prepend the directory name - relativePath = dir.getName() + '/' + n; - } else { - relativePath = n; + try (ZipOutputStream zos = new ZipOutputStream(outputStream)) { + zos.setEncoding(System.getProperty("file.encoding")); // TODO JENKINS-20663 make this overridable via query parameter + for (String n : dir.list(glob.length() == 0 ? "**" : glob)) { + String relativePath; + if (glob.length() == 0) { + // JENKINS-19947: traditional behavior is to prepend the directory name + relativePath = dir.getName() + '/' + n; + } else { + relativePath = n; + } + // In ZIP archives "All slashes MUST be forward slashes" (http://pkware.com/documents/casestudies/APPNOTE.TXT) + // TODO On Linux file names can contain backslashes which should not treated as file separators. + // Unfortunately, only the file separator char of the master is known (File.separatorChar) + // but not the file separator char of the (maybe remote) "dir". + ZipEntry e = new ZipEntry(relativePath.replace('\\', '/')); + VirtualFile f = dir.child(n); + e.setTime(f.lastModified()); + zos.putNextEntry(e); + InputStream in = f.open(); + try { + Util.copyStream(in, zos); + } finally { + IOUtils.closeQuietly(in); + } + zos.closeEntry(); } - // In ZIP archives "All slashes MUST be forward slashes" (http://pkware.com/documents/casestudies/APPNOTE.TXT) - // TODO On Linux file names can contain backslashes which should not treated as file separators. - // Unfortunately, only the file separator char of the master is known (File.separatorChar) - // but not the file separator char of the (maybe remote) "dir". - ZipEntry e = new ZipEntry(relativePath.replace('\\', '/')); - VirtualFile f = dir.child(n); - e.setTime(f.lastModified()); - zos.putNextEntry(e); - InputStream in = f.open(); - try { - Util.copyStream(in, zos); - } finally { - IOUtils.closeQuietly(in); - } - zos.closeEntry(); } - zos.close(); } /** diff --git a/core/src/main/java/hudson/model/DownloadService.java b/core/src/main/java/hudson/model/DownloadService.java index 52da67e9d3..d7fda884aa 100644 --- a/core/src/main/java/hudson/model/DownloadService.java +++ b/core/src/main/java/hudson/model/DownloadService.java @@ -168,8 +168,7 @@ public class DownloadService extends PageDecorator { */ @Restricted(NoExternalUse.class) public static String loadJSON(URL src) throws IOException { - InputStream is = ProxyConfiguration.open(src).getInputStream(); - try { + try (InputStream is = ProxyConfiguration.open(src).getInputStream()) { String jsonp = IOUtils.toString(is, "UTF-8"); int start = jsonp.indexOf('{'); int end = jsonp.lastIndexOf('}'); @@ -178,8 +177,6 @@ public class DownloadService extends PageDecorator { } else { throw new IOException("Could not find JSON in " + src); } - } finally { - is.close(); } } @@ -191,8 +188,7 @@ public class DownloadService extends PageDecorator { */ @Restricted(NoExternalUse.class) public static String loadJSONHTML(URL src) throws IOException { - InputStream is = ProxyConfiguration.open(src).getInputStream(); - try { + try (InputStream is = ProxyConfiguration.open(src).getInputStream()) { String jsonp = IOUtils.toString(is, "UTF-8"); String preamble = "window.parent.postMessage(JSON.stringify("; int start = jsonp.indexOf(preamble); @@ -202,8 +198,6 @@ public class DownloadService extends PageDecorator { } else { throw new IOException("Could not find JSON in " + src); } - } finally { - is.close(); } } diff --git a/core/src/main/java/hudson/model/Executor.java b/core/src/main/java/hudson/model/Executor.java index df27abaab7..03b146908c 100644 --- a/core/src/main/java/hudson/model/Executor.java +++ b/core/src/main/java/hudson/model/Executor.java @@ -282,19 +282,16 @@ public class Executor extends Thread implements ModelObject { */ private void resetWorkUnit(String reason) { StringWriter writer = new StringWriter(); - PrintWriter pw = new PrintWriter(writer); - try { + try (PrintWriter pw = new PrintWriter(writer)) { pw.printf("%s grabbed %s from queue but %s %s. ", getName(), workUnit, owner.getDisplayName(), reason); if (owner.getTerminatedBy().isEmpty()) { pw.print("No termination trace available."); } else { pw.println("Termination trace follows:"); - for (Computer.TerminationRequest request: owner.getTerminatedBy()) { + for (Computer.TerminationRequest request : owner.getTerminatedBy()) { request.printStackTrace(pw); } } - } finally { - pw.close(); } LOGGER.log(WARNING, writer.toString()); lock.writeLock().lock(); diff --git a/core/src/main/java/hudson/model/FileParameterValue.java b/core/src/main/java/hudson/model/FileParameterValue.java index 930eb41fd8..817b671415 100644 --- a/core/src/main/java/hudson/model/FileParameterValue.java +++ b/core/src/main/java/hudson/model/FileParameterValue.java @@ -266,11 +266,8 @@ public class FileParameterValue extends ParameterValue { public byte[] get() { try { - FileInputStream inputStream = new FileInputStream(file); - try { + try (FileInputStream inputStream = new FileInputStream(file)) { return IOUtils.toByteArray(inputStream); - } finally { - inputStream.close(); } } catch (IOException e) { throw new Error(e); diff --git a/core/src/main/java/hudson/model/LargeText.java b/core/src/main/java/hudson/model/LargeText.java index 4ad5bdf844..705c0242ef 100644 --- a/core/src/main/java/hudson/model/LargeText.java +++ b/core/src/main/java/hudson/model/LargeText.java @@ -26,6 +26,7 @@ package hudson.model; import hudson.util.ByteBuffer; import hudson.util.CharSpool; import hudson.util.LineEndNormalizingWriter; +import org.apache.commons.fileupload.util.Closeable; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.framework.io.WriterOutputStream; @@ -146,27 +147,26 @@ public class LargeText { public long writeLogTo(long start, Writer w) throws IOException { CountingOutputStream os = new CountingOutputStream(new WriterOutputStream(w)); - Session f = source.open(); - f.skip(start); + try (Session f = source.open()) { + f.skip(start); - if(completed) { - // write everything till EOF - byte[] buf = new byte[1024]; - int sz; - while((sz=f.read(buf))>=0) - os.write(buf,0,sz); - } else { - ByteBuf buf = new ByteBuf(null,f); - HeadMark head = new HeadMark(buf); - TailMark tail = new TailMark(buf); + if (completed) { + // write everything till EOF + byte[] buf = new byte[1024]; + int sz; + while ((sz = f.read(buf)) >= 0) + os.write(buf, 0, sz); + } else { + ByteBuf buf = new ByteBuf(null, f); + HeadMark head = new HeadMark(buf); + TailMark tail = new TailMark(buf); - while(tail.moveToNextLine(f)) { - head.moveTo(tail,os); + while (tail.moveToNextLine(f)) { + head.moveTo(tail, os); + } + head.finish(os); } - head.finish(os); } - - f.close(); os.flush(); return os.getCount()+start; @@ -308,7 +308,7 @@ public class LargeText { * Represents the read session of the {@link Source}. * Methods generally follow the contracts of {@link InputStream}. */ - private interface Session { + private interface Session extends AutoCloseable { void close() throws IOException; void skip(long start) throws IOException; int read(byte[] buf) throws IOException; diff --git a/core/src/main/java/hudson/model/Queue.java b/core/src/main/java/hudson/model/Queue.java index 282beb8621..28e24f8f2e 100644 --- a/core/src/main/java/hudson/model/Queue.java +++ b/core/src/main/java/hudson/model/Queue.java @@ -351,16 +351,13 @@ public class Queue extends ResourceController implements Saveable { // first try the old format File queueFile = getQueueFile(); if (queueFile.exists()) { - BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(queueFile))); - try { + try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(queueFile)))) { String line; while ((line = in.readLine()) != null) { AbstractProject j = Jenkins.getInstance().getItemByFullName(line, AbstractProject.class); if (j != null) j.scheduleBuild(); } - } finally { - in.close(); } // discard the queue file now that we are done queueFile.delete(); diff --git a/core/src/main/java/hudson/model/RSS.java b/core/src/main/java/hudson/model/RSS.java index 553a21c85a..bc36830e29 100644 --- a/core/src/main/java/hudson/model/RSS.java +++ b/core/src/main/java/hudson/model/RSS.java @@ -50,14 +50,14 @@ public final class RSS { rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("application/xml; charset=UTF-8"); - PrintWriter pw = rsp.getWriter(); - pw.println(""); - pw.println(""+(url!=null?0:1)+""); - if(url==null) { - pw.println("url must be specified"); + try (PrintWriter pw = rsp.getWriter()) { + pw.println(""); + pw.println("" + (url != null ? 0 : 1) + ""); + if (url == null) { + pw.println("url must be specified"); + } + pw.println(""); } - pw.println(""); - pw.close(); } /** diff --git a/core/src/main/java/hudson/model/Run.java b/core/src/main/java/hudson/model/Run.java index dad840bf3a..74aa283656 100644 --- a/core/src/main/java/hudson/model/Run.java +++ b/core/src/main/java/hudson/model/Run.java @@ -1935,8 +1935,7 @@ public abstract class Run ,RunT extends Run,RunT extends Run maxLines) logLines.remove(0); } - } finally { - reader.close(); } // If the log has been truncated, include that information. diff --git a/core/src/main/java/hudson/model/Slave.java b/core/src/main/java/hudson/model/Slave.java index 76fefa1fe1..4eb813f6eb 100644 --- a/core/src/main/java/hudson/model/Slave.java +++ b/core/src/main/java/hudson/model/Slave.java @@ -394,11 +394,8 @@ public abstract class Slave extends Node implements Serializable { } public byte[] readFully() throws IOException { - InputStream in = connect().getInputStream(); - try { + try (InputStream in = connect().getInputStream()) { return IOUtils.toByteArray(in); - } finally { - in.close(); } } diff --git a/core/src/main/java/hudson/model/UpdateCenter.java b/core/src/main/java/hudson/model/UpdateCenter.java index cd793c9f64..8ecd72dd89 100644 --- a/core/src/main/java/hudson/model/UpdateCenter.java +++ b/core/src/main/java/hudson/model/UpdateCenter.java @@ -752,14 +752,11 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas */ public String getBackupVersion() { try { - JarFile backupWar = new JarFile(new File(Lifecycle.get().getHudsonWar() + ".bak")); - try { + try (JarFile backupWar = new JarFile(new File(Lifecycle.get().getHudsonWar() + ".bak"))) { Attributes attrs = backupWar.getManifest().getMainAttributes(); String v = attrs.getValue("Jenkins-Version"); - if (v==null) v = attrs.getValue("Hudson-Version"); + if (v == null) v = attrs.getValue("Hudson-Version"); return v; - } finally { - backupWar.close(); } } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to read backup version ", e); diff --git a/core/src/main/java/hudson/model/View.java b/core/src/main/java/hudson/model/View.java index abb96724db..cffb079036 100644 --- a/core/src/main/java/hudson/model/View.java +++ b/core/src/main/java/hudson/model/View.java @@ -1156,28 +1156,20 @@ public abstract class View extends AbstractModelObject implements AccessControll // data XMLUtils.safeTransform(source, new StreamResult(out)); out.close(); - } catch (TransformerException e) { - throw new IOException("Failed to persist configuration.xml", e); - } catch (SAXException e) { + } catch (TransformerException|SAXException e) { throw new IOException("Failed to persist configuration.xml", e); } // try to reflect the changes by reloading - InputStream in = new BufferedInputStream(new ByteArrayInputStream(out.toString().getBytes("UTF-8"))); - try { + + try (InputStream in = new BufferedInputStream(new ByteArrayInputStream(out.toString().getBytes("UTF-8")))){ // Do not allow overwriting view name as it might collide with another // view in same ViewGroup and might not satisfy Jenkins.checkGoodName. String oldname = name; Jenkins.XSTREAM.unmarshal(new XppDriver().createReader(in), this); name = oldname; - } catch (StreamException e) { + } catch (StreamException | ConversionException | Error e) {// mostly reflection errors throw new IOException("Unable to read",e); - } catch(ConversionException e) { - throw new IOException("Unable to read",e); - } catch(Error e) {// mostly reflection errors - throw new IOException("Unable to read",e); - } finally { - in.close(); } save(); } @@ -1302,20 +1294,14 @@ public abstract class View extends AbstractModelObject implements AccessControll * @param name Alternative name to use or null to keep the one in xml. */ public static View createViewFromXML(String name, InputStream xml) throws IOException { - InputStream in = new BufferedInputStream(xml); - try { + + try (InputStream in = new BufferedInputStream(xml)) { View v = (View) Jenkins.XSTREAM.fromXML(in); if (name != null) v.name = name; checkGoodName(v.name); return v; - } catch(StreamException e) { + } catch(StreamException|ConversionException|Error e) {// mostly reflection errors throw new IOException("Unable to read",e); - } catch(ConversionException e) { - throw new IOException("Unable to read",e); - } catch(Error e) {// mostly reflection errors - throw new IOException("Unable to read",e); - } finally { - in.close(); } } diff --git a/core/src/main/java/hudson/security/csrf/CrumbIssuer.java b/core/src/main/java/hudson/security/csrf/CrumbIssuer.java index 3d80b1a5b6..349e69a136 100644 --- a/core/src/main/java/hudson/security/csrf/CrumbIssuer.java +++ b/core/src/main/java/hudson/security/csrf/CrumbIssuer.java @@ -211,12 +211,9 @@ public abstract class CrumbIssuer implements Describable, Extension text = null; } if (text != null) { - OutputStream o = rsp.getCompressedOutputStream(req); - try { + try (OutputStream o = rsp.getCompressedOutputStream(req)) { rsp.setContentType("text/plain;charset=UTF-8"); o.write(text.getBytes("UTF-8")); - } finally { - o.close(); } } else { super.doXml(req, rsp, xpath, wrapper, tree, depth); diff --git a/core/src/main/java/hudson/tools/JDKInstaller.java b/core/src/main/java/hudson/tools/JDKInstaller.java index 8a42e7e1ca..c77ce7e957 100644 --- a/core/src/main/java/hudson/tools/JDKInstaller.java +++ b/core/src/main/java/hudson/tools/JDKInstaller.java @@ -273,11 +273,8 @@ public class JDKInstaller extends ToolInstaller { if (r != 0) { out.println(Messages.JDKInstaller_FailedToInstallJDK(r)); // log file is in UTF-16 - InputStreamReader in = new InputStreamReader(fs.read(logFile), "UTF-16"); - try { - IOUtils.copy(in,new OutputStreamWriter(out)); - } finally { - in.close(); + try (InputStreamReader in = new InputStreamReader(fs.read(logFile), "UTF-16")) { + IOUtils.copy(in, new OutputStreamWriter(out)); } throw new AbortException(); } @@ -521,11 +518,8 @@ public class JDKInstaller extends ToolInstaller { File tmp = new File(cache.getPath()+".tmp"); try { tmp.getParentFile().mkdirs(); - FileOutputStream out = new FileOutputStream(tmp); - try { + try (FileOutputStream out = new FileOutputStream(tmp)) { IOUtils.copy(m.getResponseBodyAsStream(), out); - } finally { - out.close(); } tmp.renameTo(cache); diff --git a/core/src/main/java/hudson/util/BootFailure.java b/core/src/main/java/hudson/util/BootFailure.java index eefb4da819..8d1055b1c2 100644 --- a/core/src/main/java/hudson/util/BootFailure.java +++ b/core/src/main/java/hudson/util/BootFailure.java @@ -60,8 +60,7 @@ public abstract class BootFailure extends ErrorObject { File f = getBootFailureFile(home); try { if (f.exists()) { - BufferedReader failureFileReader = new BufferedReader(new FileReader(f)); - try { + try (BufferedReader failureFileReader = new BufferedReader(new FileReader(f))) { String line; while ((line=failureFileReader.readLine())!=null) { try { @@ -70,8 +69,6 @@ public abstract class BootFailure extends ErrorObject { // ignore any parse error } } - } finally { - failureFileReader.close(); } } } catch (IOException e) { diff --git a/core/src/main/java/hudson/util/CompressedFile.java b/core/src/main/java/hudson/util/CompressedFile.java index b6ccf22c30..fb691e298d 100644 --- a/core/src/main/java/hudson/util/CompressedFile.java +++ b/core/src/main/java/hudson/util/CompressedFile.java @@ -138,13 +138,8 @@ public class CompressedFile { compressionThread.submit(new Runnable() { public void run() { try { - InputStream in = read(); - OutputStream out = new GZIPOutputStream(new FileOutputStream(gz)); - try { - Util.copyStream(in,out); - } finally { - in.close(); - out.close(); + try (InputStream in = read(); OutputStream out = new GZIPOutputStream(new FileOutputStream(gz))) { + Util.copyStream(in, out); } // if the compressed file is created successfully, remove the original file.delete(); diff --git a/core/src/main/java/hudson/util/IOUtils.java b/core/src/main/java/hudson/util/IOUtils.java index b8edc31242..221004fd11 100644 --- a/core/src/main/java/hudson/util/IOUtils.java +++ b/core/src/main/java/hudson/util/IOUtils.java @@ -136,12 +136,9 @@ public class IOUtils { * @since 1.422 */ public static String readFirstLine(InputStream is, String encoding) throws IOException { - BufferedReader reader = new BufferedReader( - encoding==null ? new InputStreamReader(is) : new InputStreamReader(is,encoding)); - try { + try (BufferedReader reader = new BufferedReader( + encoding == null ? new InputStreamReader(is) : new InputStreamReader(is, encoding))) { return reader.readLine(); - } finally { - reader.close(); } } diff --git a/core/src/main/java/hudson/util/SecretRewriter.java b/core/src/main/java/hudson/util/SecretRewriter.java index 0ee05dc869..45e5b6ae27 100644 --- a/core/src/main/java/hudson/util/SecretRewriter.java +++ b/core/src/main/java/hudson/util/SecretRewriter.java @@ -79,42 +79,36 @@ public class SecretRewriter { public boolean rewrite(File f, File backup) throws InvalidKeyException, IOException { AtomicFileWriter w = new AtomicFileWriter(f, "UTF-8"); try { - PrintWriter out = new PrintWriter(new BufferedWriter(w)); boolean modified = false; // did we actually change anything? - try { - FileInputStream fin = new FileInputStream(f); - try { + try (PrintWriter out = new PrintWriter(new BufferedWriter(w))) { + try (FileInputStream fin = new FileInputStream(f)) { BufferedReader r = new BufferedReader(new InputStreamReader(fin, "UTF-8")); String line; StringBuilder buf = new StringBuilder(); - while ((line=r.readLine())!=null) { - int copied=0; + while ((line = r.readLine()) != null) { + int copied = 0; buf.setLength(0); while (true) { - int sidx = line.indexOf('>',copied); - if (sidx<0) break; - int eidx = line.indexOf('<',sidx); - if (eidx<0) break; + int sidx = line.indexOf('>', copied); + if (sidx < 0) break; + int eidx = line.indexOf('<', sidx); + if (eidx < 0) break; - String elementText = line.substring(sidx+1,eidx); + String elementText = line.substring(sidx + 1, eidx); String replacement = tryRewrite(elementText); if (!replacement.equals(elementText)) modified = true; - buf.append(line.substring(copied,sidx+1)); + buf.append(line.substring(copied, sidx + 1)); buf.append(replacement); copied = eidx; } buf.append(line.substring(copied)); out.println(buf.toString()); } - } finally { - fin.close(); } - } finally { - out.close(); } if (modified) { diff --git a/core/src/main/java/hudson/util/Service.java b/core/src/main/java/hudson/util/Service.java index 56ec8928f0..6275b07e3f 100644 --- a/core/src/main/java/hudson/util/Service.java +++ b/core/src/main/java/hudson/util/Service.java @@ -50,28 +50,25 @@ public class Service { final Enumeration e = classLoader.getResources("META-INF/services/"+type.getName()); while (e.hasMoreElements()) { URL url = e.nextElement(); - BufferedReader configFile = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8")); - try { + try (BufferedReader configFile = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) { String line; while ((line = configFile.readLine()) != null) { line = line.trim(); - if (line.startsWith("#") || line.length()==0) continue; + if (line.startsWith("#") || line.length() == 0) continue; try { Class t = classLoader.loadClass(line); - if (!type.isAssignableFrom(t)) continue; // invalid type + if (!type.isAssignableFrom(t)) continue; // invalid type result.add(type.cast(t.newInstance())); } catch (ClassNotFoundException x) { - LOGGER.log(WARNING,"Failed to load "+line,x); + LOGGER.log(WARNING, "Failed to load " + line, x); } catch (InstantiationException x) { - LOGGER.log(WARNING,"Failed to load "+line,x); + LOGGER.log(WARNING, "Failed to load " + line, x); } catch (IllegalAccessException x) { - LOGGER.log(WARNING,"Failed to load "+line,x); + LOGGER.log(WARNING, "Failed to load " + line, x); } } - } finally { - configFile.close(); } } @@ -87,26 +84,23 @@ public class Service { Enumeration e = cl.getResources("META-INF/services/" + spi.getName()); while(e.hasMoreElements()) { final URL url = e.nextElement(); - final BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8")); - try { + try (BufferedReader r = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) { String line; - while((line=r.readLine())!=null) { - if(line.startsWith("#")) + while ((line = r.readLine()) != null) { + if (line.startsWith("#")) continue; // comment line line = line.trim(); - if(line.length()==0) + if (line.length() == 0) continue; // empty line. ignore. try { result.add(cl.loadClass(line).asSubclass(spi)); } catch (ClassNotFoundException x) { - LOGGER.log(Level.WARNING, "Failed to load "+line, x); + LOGGER.log(Level.WARNING, "Failed to load " + line, x); } } } catch (IOException x) { - LOGGER.log(Level.WARNING, "Failed to load "+url, x); - } finally { - r.close(); + LOGGER.log(Level.WARNING, "Failed to load " + url, x); } } } catch (IOException x) { diff --git a/core/src/main/java/hudson/util/TextFile.java b/core/src/main/java/hudson/util/TextFile.java index 4e16532044..b6fb8341e8 100644 --- a/core/src/main/java/hudson/util/TextFile.java +++ b/core/src/main/java/hudson/util/TextFile.java @@ -67,13 +67,10 @@ public class TextFile { public String read() throws IOException { StringWriter out = new StringWriter(); PrintWriter w = new PrintWriter(out); - BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8")); - try { + try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) { String line; - while((line=in.readLine())!=null) + while ((line = in.readLine()) != null) w.println(line); - } finally{ - in.close(); } return out.toString(); } @@ -177,23 +174,20 @@ public class TextFile { * So all in all, this algorithm should work decently, and it works quite efficiently on a large text. */ public @Nonnull String fastTail(int numChars, Charset cs) throws IOException { - RandomAccessFile raf = new RandomAccessFile(file,"r"); - try { + try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { long len = raf.length(); // err on the safe side and assume each char occupies 4 bytes // additional 1024 byte margin is to bring us back in sync in case we started reading from non-char boundary. - long pos = Math.max(0, len - (numChars*4+1024)); + long pos = Math.max(0, len - (numChars * 4 + 1024)); raf.seek(pos); - byte[] tail = new byte[(int) (len-pos)]; + byte[] tail = new byte[(int) (len - pos)]; raf.readFully(tail); String tails = cs.decode(java.nio.ByteBuffer.wrap(tail)).toString(); - return new String(tails.substring(Math.max(0,tails.length()-numChars))); // trim the baggage of substring by allocating a new String - } finally { - raf.close(); + return new String(tails.substring(Math.max(0, tails.length() - numChars))); // trim the baggage of substring by allocating a new String } } diff --git a/core/src/main/java/jenkins/PluginSubtypeMarker.java b/core/src/main/java/jenkins/PluginSubtypeMarker.java index d8e127f3ce..d10427a33d 100644 --- a/core/src/main/java/jenkins/PluginSubtypeMarker.java +++ b/core/src/main/java/jenkins/PluginSubtypeMarker.java @@ -111,11 +111,8 @@ public class PluginSubtypeMarker extends AbstractProcessor { private void write(TypeElement c) throws IOException { FileObject f = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", "META-INF/services/hudson.Plugin"); - Writer w = new OutputStreamWriter(f.openOutputStream(),"UTF-8"); - try { + try (Writer w = new OutputStreamWriter(f.openOutputStream(), "UTF-8")) { w.write(c.getQualifiedName().toString()); - } finally { - w.close(); } } diff --git a/core/src/main/java/jenkins/diagnosis/HsErrPidList.java b/core/src/main/java/jenkins/diagnosis/HsErrPidList.java index 64b1d93d78..f11090a4b4 100644 --- a/core/src/main/java/jenkins/diagnosis/HsErrPidList.java +++ b/core/src/main/java/jenkins/diagnosis/HsErrPidList.java @@ -49,14 +49,8 @@ public class HsErrPidList extends AdministrativeMonitor { return; } try { - FileChannel ch = null; - try { - ch = new FileInputStream(getSecretKeyFile()).getChannel(); + try (FileChannel ch = new FileInputStream(getSecretKeyFile()).getChannel()) { map = ch.map(MapMode.READ_ONLY,0,1); - } finally { - if (ch != null) { - ch.close(); - } } scan("./hs_err_pid%p.log"); diff --git a/core/src/main/java/jenkins/model/Jenkins.java b/core/src/main/java/jenkins/model/Jenkins.java index b25fbe2cc0..20c041e9ea 100644 --- a/core/src/main/java/jenkins/model/Jenkins.java +++ b/core/src/main/java/jenkins/model/Jenkins.java @@ -4157,9 +4157,9 @@ public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLeve if (rsp!=null) { rsp.setStatus(HttpServletResponse.SC_OK); rsp.setContentType("text/plain"); - PrintWriter w = rsp.getWriter(); - w.println("Shutting down"); - w.close(); + try (PrintWriter w = rsp.getWriter()) { + w.println("Shutting down"); + } } System.exit(0); diff --git a/core/src/main/java/jenkins/security/s2m/AdminWhitelistRule.java b/core/src/main/java/jenkins/security/s2m/AdminWhitelistRule.java index c9aabe5691..a05fd59e8e 100644 --- a/core/src/main/java/jenkins/security/s2m/AdminWhitelistRule.java +++ b/core/src/main/java/jenkins/security/s2m/AdminWhitelistRule.java @@ -109,14 +109,14 @@ public class AdminWhitelistRule implements StaplerProxy { private InputStream transformForWindows(InputStream src) throws IOException { BufferedReader r = new BufferedReader(new InputStreamReader(src)); ByteArrayOutputStream out = new ByteArrayOutputStream(); - PrintStream p = new PrintStream(out); - String line; - while ((line=r.readLine())!=null) { - if (!line.startsWith("#") && Functions.isWindows()) - line = line.replace("/","\\\\"); - p.println(line); + try (PrintStream p = new PrintStream(out)) { + String line; + while ((line = r.readLine()) != null) { + if (!line.startsWith("#") && Functions.isWindows()) + line = line.replace("/", "\\\\"); + p.println(line); + } } - p.close(); return new ByteArrayInputStream(out.toByteArray()); } diff --git a/core/src/main/java/jenkins/util/JSONSignatureValidator.java b/core/src/main/java/jenkins/util/JSONSignatureValidator.java index 73f9dd0a26..865a7b9917 100644 --- a/core/src/main/java/jenkins/util/JSONSignatureValidator.java +++ b/core/src/main/java/jenkins/util/JSONSignatureValidator.java @@ -143,10 +143,9 @@ public class JSONSignatureValidator { if (cert.endsWith("/") || cert.endsWith(".txt")) { continue; // skip directories also any text files that are meant to be documentation } - InputStream in = j.servletContext.getResourceAsStream(cert); - if (in == null) continue; // our test for paths ending in / should prevent this from happening Certificate certificate; - try { + try (InputStream in = j.servletContext.getResourceAsStream(cert)) { + if (in == null) continue; // our test for paths ending in / should prevent this from happening certificate = cf.generateCertificate(in); } catch (CertificateException e) { LOGGER.log(Level.WARNING, String.format("Webapp resources in /WEB-INF/update-center-rootCAs are " @@ -155,8 +154,6 @@ public class JSONSignatureValidator { + "resource for now.", cert), e); continue; - } finally { - in.close(); } try { TrustAnchor certificateAuthority = new TrustAnchor((X509Certificate) certificate, null); diff --git a/core/src/test/java/jenkins/util/xstream/XStreamDOMTest.java b/core/src/test/java/jenkins/util/xstream/XStreamDOMTest.java index 979a86cb2b..b32ed5a40f 100644 --- a/core/src/test/java/jenkins/util/xstream/XStreamDOMTest.java +++ b/core/src/test/java/jenkins/util/xstream/XStreamDOMTest.java @@ -83,12 +83,9 @@ public class XStreamDOMTest { @Test public void testUnmarshal() throws Exception { - InputStream is = XStreamDOMTest.class.getResourceAsStream("XStreamDOMTest.data1.xml"); Foo foo; - try { + try (InputStream is = XStreamDOMTest.class.getResourceAsStream("XStreamDOMTest.data1.xml")) { foo = (Foo) xs.fromXML(is); - } finally { - is.close(); } assertEquals("test1",foo.bar.getTagName()); assertEquals("value",foo.bar.getAttribute("key"));