From f0cd7ae8ff269dd738e3377a62f3fbebebf9aef6 Mon Sep 17 00:00:00 2001 From: Stephen Connolly Date: Mon, 20 Mar 2017 12:50:46 +0000 Subject: [PATCH] [JENKINS-42934] Avoid using new FileInputStream / new FileOutputStream --- .../java/hudson/cli/PrivateKeyProvider.java | 4 +- .../java/hudson/ClassicPluginStrategy.java | 14 ++-- core/src/main/java/hudson/FilePath.java | 69 ++++++++++--------- .../java/hudson/FileSystemProvisioner.java | 3 +- core/src/main/java/hudson/Main.java | 16 ++--- core/src/main/java/hudson/PluginWrapper.java | 3 +- core/src/main/java/hudson/Util.java | 6 +- core/src/main/java/hudson/WebAppMain.java | 9 ++- core/src/main/java/hudson/XmlFile.java | 9 +-- .../lifecycle/WindowsInstallerLink.java | 4 +- .../java/hudson/model/FileParameterValue.java | 9 +-- core/src/main/java/hudson/model/Queue.java | 3 +- core/src/main/java/hudson/model/Run.java | 6 +- .../main/java/hudson/model/UpdateCenter.java | 3 +- .../main/java/hudson/tools/JDKInstaller.java | 4 +- .../java/hudson/util/AtomicFileWriter.java | 3 +- .../main/java/hudson/util/CompressedFile.java | 19 +++-- core/src/main/java/hudson/util/IOUtils.java | 11 +-- .../main/java/hudson/util/SecretRewriter.java | 4 +- .../java/hudson/util/StreamTaskListener.java | 13 +++- core/src/main/java/hudson/util/TextFile.java | 6 +- .../util/io/ReopenableFileOutputStream.java | 5 +- .../util/io/RewindableFileOutputStream.java | 4 +- .../main/java/hudson/util/io/TarArchiver.java | 4 +- .../main/java/hudson/util/io/ZipArchiver.java | 7 +- .../java/jenkins/diagnosis/HsErrPidList.java | 5 +- .../security/DefaultConfidentialStore.java | 11 +-- .../java/jenkins/util/AntClassLoader.java | 3 +- .../jenkins/util/JSONSignatureValidator.java | 6 +- .../main/java/jenkins/util/VirtualFile.java | 3 +- .../java/jenkins/util/io/FileBoolean.java | 3 +- .../main/java/jenkins/util/xml/XMLUtils.java | 15 ++-- core/src/test/java/hudson/FilePathTest.java | 17 ++--- .../test/java/hudson/PluginManagerTest.java | 3 +- core/src/test/java/hudson/UtilTest.java | 3 +- .../java/hudson/model/LoadStatisticsTest.java | 7 +- core/src/test/java/hudson/os/SUTester.java | 4 +- .../java/hudson/util/io/TarArchiverTest.java | 16 +++-- .../java/hudson/util/io/ZipArchiverTest.java | 3 +- .../model/DirectoryBrowserSupportTest.java | 3 +- .../java/hudson/tools/JDKInstallerTest.java | 7 +- 41 files changed, 188 insertions(+), 159 deletions(-) diff --git a/cli/src/main/java/hudson/cli/PrivateKeyProvider.java b/cli/src/main/java/hudson/cli/PrivateKeyProvider.java index 5fe402afc6..a1f6b33890 100644 --- a/cli/src/main/java/hudson/cli/PrivateKeyProvider.java +++ b/cli/src/main/java/hudson/cli/PrivateKeyProvider.java @@ -30,6 +30,8 @@ import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.KeyPair; @@ -127,7 +129,7 @@ public class PrivateKeyProvider { } private static String readPemFile(File f) throws IOException{ - try (FileInputStream is = new FileInputStream(f); + try (InputStream is = Files.newInputStream(f.toPath()); DataInputStream dis = new DataInputStream(is)) { byte[] bytes = new byte[(int) f.length()]; dis.readFully(bytes); diff --git a/core/src/main/java/hudson/ClassicPluginStrategy.java b/core/src/main/java/hudson/ClassicPluginStrategy.java index 792e02a0b7..17722cef44 100644 --- a/core/src/main/java/hudson/ClassicPluginStrategy.java +++ b/core/src/main/java/hudson/ClassicPluginStrategy.java @@ -23,6 +23,8 @@ */ package hudson; +import java.io.InputStream; +import java.nio.file.Files; import jenkins.util.SystemProperties; import com.google.common.collect.Lists; import hudson.Plugin.DummyImpl; @@ -123,11 +125,8 @@ public class ClassicPluginStrategy implements PluginStrategy { try { // Locate the manifest String firstLine; - FileInputStream manifestHeaderInput = new FileInputStream(archive); - try { + try (InputStream manifestHeaderInput = Files.newInputStream(archive.toPath())) { firstLine = IOUtils.readFirstLine(manifestHeaderInput, "UTF-8"); - } finally { - manifestHeaderInput.close(); } if (firstLine.startsWith("Manifest-Version:")) { // this is the manifest already @@ -137,11 +136,8 @@ public class ClassicPluginStrategy implements PluginStrategy { } // Read the manifest - FileInputStream manifestInput = new FileInputStream(archive); - try { + try (InputStream manifestInput = Files.newInputStream(archive.toPath())) { return new Manifest(manifestInput); - } finally { - manifestInput.close(); } } catch (IOException e) { throw new IOException("Failed to load " + archive, e); @@ -173,7 +169,7 @@ public class ClassicPluginStrategy implements PluginStrategy { "Plugin installation failed. No manifest at " + manifestFile); } - try (FileInputStream fin = new FileInputStream(manifestFile)) { + try (InputStream fin = Files.newInputStream(manifestFile.toPath())) { manifest = new Manifest(fin); } } diff --git a/core/src/main/java/hudson/FilePath.java b/core/src/main/java/hudson/FilePath.java index bb68b4e067..a06681ed19 100644 --- a/core/src/main/java/hudson/FilePath.java +++ b/core/src/main/java/hudson/FilePath.java @@ -25,7 +25,6 @@ */ package hudson; -import jenkins.util.SystemProperties; import com.google.common.annotations.VisibleForTesting; import com.jcraft.jzlib.GZIPInputStream; import com.jcraft.jzlib.GZIPOutputStream; @@ -59,29 +58,9 @@ import hudson.util.IOUtils; import hudson.util.NamingThreadFactory; import hudson.util.io.Archiver; import hudson.util.io.ArchiverFactory; -import jenkins.FilePathFilter; -import jenkins.MasterToSlaveFileCallable; -import jenkins.SlaveToMasterFileCallable; -import jenkins.SoloFilePathFilter; -import jenkins.model.Jenkins; -import jenkins.util.ContextResettingExecutorService; -import jenkins.util.VirtualFile; -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.io.input.CountingInputStream; -import org.apache.tools.ant.DirectoryScanner; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.types.FileSet; -import org.apache.tools.zip.ZipEntry; -import org.apache.tools.zip.ZipFile; -import org.kohsuke.accmod.Restricted; -import org.kohsuke.accmod.restrictions.NoExternalUse; -import org.kohsuke.stapler.Stapler; - -import javax.annotation.CheckForNull; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileFilter; -import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; @@ -99,6 +78,7 @@ import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.net.URLConnection; +import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; @@ -116,16 +96,37 @@ import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; - -import static hudson.FilePath.TarCompression.*; -import static hudson.Util.*; +import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; +import jenkins.FilePathFilter; +import jenkins.MasterToSlaveFileCallable; +import jenkins.SlaveToMasterFileCallable; +import jenkins.SoloFilePathFilter; +import jenkins.model.Jenkins; import jenkins.security.MasterToSlaveCallable; +import jenkins.util.ContextResettingExecutorService; +import jenkins.util.SystemProperties; +import jenkins.util.VirtualFile; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.io.input.CountingInputStream; +import org.apache.tools.ant.DirectoryScanner; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.types.FileSet; +import org.apache.tools.zip.ZipEntry; +import org.apache.tools.zip.ZipFile; import org.jenkinsci.remoting.RoleChecker; import org.jenkinsci.remoting.RoleSensitive; +import org.kohsuke.accmod.Restricted; +import org.kohsuke.accmod.restrictions.NoExternalUse; +import org.kohsuke.stapler.Stapler; + +import static hudson.FilePath.TarCompression.GZIP; +import static hudson.Util.deleteFile; +import static hudson.Util.fixEmpty; +import static hudson.Util.isSymlink; /** * {@link File} like object with remoting support. @@ -1470,7 +1471,7 @@ public final class FilePath implements Serializable { private static final long serialVersionUID = -5094638816500738429L; public Void invoke(File f, VirtualChannel channel) throws IOException { if(!f.exists()) - new FileOutputStream(creating(f)).close(); + Files.newOutputStream(creating(f).toPath()).close(); if(!stating(f).setLastModified(timestamp)) throw new IOException("Failed to set the timestamp of "+f+" to "+timestamp); return null; @@ -1751,7 +1752,7 @@ public final class FilePath implements Serializable { */ public InputStream read() throws IOException, InterruptedException { if(channel==null) - return new FileInputStream(reading(new File(remote))); + return Files.newInputStream(reading(new File(remote)).toPath()); final Pipe p = Pipe.createRemoteToLocal(); actAsync(new SecureFileCallable() { @@ -1759,9 +1760,9 @@ public final class FilePath implements Serializable { @Override public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { - FileInputStream fis = null; + InputStream fis = null; try { - fis = new FileInputStream(reading(f)); + fis = Files.newInputStream(reading(f).toPath()); Util.copyStream(fis, p.getOut()); } catch (Exception x) { p.error(x); @@ -1876,7 +1877,7 @@ public final class FilePath implements Serializable { if(channel==null) { File f = new File(remote).getAbsoluteFile(); mkdirs(f.getParentFile()); - return new FileOutputStream(writing(f)); + return Files.newOutputStream(writing(f).toPath()); } return act(new SecureFileCallable() { @@ -1884,7 +1885,7 @@ public final class FilePath implements Serializable { public OutputStream invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { f = f.getAbsoluteFile(); mkdirs(f.getParentFile()); - FileOutputStream fos = new FileOutputStream(writing(f)); + OutputStream fos = Files.newOutputStream(writing(f).toPath()); return new RemoteOutputStream(fos); } }); @@ -1902,8 +1903,8 @@ public final class FilePath implements Serializable { private static final long serialVersionUID = 1L; public Void invoke(File f, VirtualChannel channel) throws IOException { mkdirs(f.getParentFile()); - FileOutputStream fos = new FileOutputStream(writing(f)); - try (Writer w = encoding != null ? new OutputStreamWriter(fos, encoding) : new OutputStreamWriter(fos)) { + try (OutputStream fos = Files.newOutputStream(writing(f).toPath()); + Writer w = encoding != null ? new OutputStreamWriter(fos, encoding) : new OutputStreamWriter(fos)) { w.write(content); } return null; @@ -2005,9 +2006,9 @@ public final class FilePath implements Serializable { act(new SecureFileCallable() { private static final long serialVersionUID = 4088559042349254141L; public Void invoke(File f, VirtualChannel channel) throws IOException { - FileInputStream fis = null; + InputStream fis = null; try { - fis = new FileInputStream(reading(f)); + fis = Files.newInputStream(reading(f).toPath()); Util.copyStream(fis,out); return null; } finally { diff --git a/core/src/main/java/hudson/FileSystemProvisioner.java b/core/src/main/java/hudson/FileSystemProvisioner.java index 8b9967e2bb..42d2b6ca53 100644 --- a/core/src/main/java/hudson/FileSystemProvisioner.java +++ b/core/src/main/java/hudson/FileSystemProvisioner.java @@ -31,6 +31,7 @@ import hudson.model.Describable; import hudson.model.Job; import hudson.model.TaskListener; import hudson.util.io.ArchiverFactory; +import java.nio.file.Files; import jenkins.model.Jenkins; import hudson.model.listeners.RunListener; import hudson.scm.SCM; @@ -215,7 +216,7 @@ 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"); - try (OutputStream os = new BufferedOutputStream(new FileOutputStream(wss))) { + try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(wss.toPath()))) { ws.archive(ArchiverFactory.TARGZ, os, glob); } return new WorkspaceSnapshotImpl(); diff --git a/core/src/main/java/hudson/Main.java b/core/src/main/java/hudson/Main.java index 66173630ac..efe2ca0c9f 100644 --- a/core/src/main/java/hudson/Main.java +++ b/core/src/main/java/hudson/Main.java @@ -23,6 +23,9 @@ */ package hudson; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; import jenkins.util.SystemProperties; import hudson.util.DualOutputStream; import hudson.util.EncodingStream; @@ -135,11 +138,9 @@ public class Main { // write the output to a temporary file first. File tmpFile = File.createTempFile("jenkins","log"); try { - FileOutputStream os = new FileOutputStream(tmpFile); - - Writer w = new OutputStreamWriter(os,"UTF-8"); int ret; - try { + try (OutputStream os = Files.newOutputStream(tmpFile.toPath()); + Writer w = new OutputStreamWriter(os,"UTF-8")) { w.write(""); w.write(""); w.flush(); @@ -156,8 +157,6 @@ public class Main { ret = proc.join(); w.write(""+ret+""+(System.currentTimeMillis()-start)+""); - } finally { - IOUtils.closeQuietly(w); } URL location = new URL(jobURL, "postBuildResult"); @@ -174,11 +173,8 @@ public class Main { con.setFixedLengthStreamingMode((int)tmpFile.length()); con.connect(); // send the data - FileInputStream in = new FileInputStream(tmpFile); - try { + try (InputStream in = Files.newInputStream(tmpFile.toPath())) { Util.copyStream(in,con.getOutputStream()); - } finally { - IOUtils.closeQuietly(in); } if(con.getResponseCode()!=200) { diff --git a/core/src/main/java/hudson/PluginWrapper.java b/core/src/main/java/hudson/PluginWrapper.java index 5932f0777e..1a55bbc1bd 100644 --- a/core/src/main/java/hudson/PluginWrapper.java +++ b/core/src/main/java/hudson/PluginWrapper.java @@ -29,6 +29,7 @@ import hudson.PluginManager.PluginInstanceStore; import hudson.model.AdministrativeMonitor; import hudson.model.Api; import hudson.model.ModelObject; +import java.nio.file.Files; import jenkins.YesNoMaybe; import jenkins.model.Jenkins; import hudson.model.UpdateCenter; @@ -495,7 +496,7 @@ public class PluginWrapper implements Comparable, ModelObject { */ public void disable() throws IOException { // creates an empty file - OutputStream os = new FileOutputStream(disableFile); + OutputStream os = Files.newOutputStream(disableFile.toPath()); os.close(); } diff --git a/core/src/main/java/hudson/Util.java b/core/src/main/java/hudson/Util.java index 4fb56c131a..ed794ef358 100644 --- a/core/src/main/java/hudson/Util.java +++ b/core/src/main/java/hudson/Util.java @@ -198,7 +198,7 @@ public class Util { StringBuilder str = new StringBuilder((int)logfile.length()); - try (BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(logfile), charset))) { + try (BufferedReader r = new BufferedReader(new InputStreamReader(Files.newInputStream(logfile.toPath()), charset))) { char[] buf = new char[1024]; int len; while ((len = r.read(buf, 0, buf.length)) > 0) @@ -800,7 +800,7 @@ public class Util { */ @Nonnull public static String getDigestOf(@Nonnull File file) throws IOException { - try (InputStream is = new FileInputStream(file)) { + try (InputStream is = Files.newInputStream(file.toPath())) { return getDigestOf(new BufferedInputStream(is)); } } @@ -1134,7 +1134,7 @@ public class Util { * Creates an empty file. */ public static void touch(@Nonnull File file) throws IOException { - new FileOutputStream(file).close(); + Files.newOutputStream(file.toPath()).close(); } /** diff --git a/core/src/main/java/hudson/WebAppMain.java b/core/src/main/java/hudson/WebAppMain.java index 2e087e0348..2081a685fd 100644 --- a/core/src/main/java/hudson/WebAppMain.java +++ b/core/src/main/java/hudson/WebAppMain.java @@ -24,6 +24,9 @@ package hudson; import hudson.security.ACLContext; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; import jenkins.util.SystemProperties; import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider; import com.thoughtworks.xstream.core.JVM; @@ -273,14 +276,10 @@ public class WebAppMain implements ServletContextListener { * @see BootFailure */ private void recordBootAttempt(File home) { - FileOutputStream o=null; - try { - o = new FileOutputStream(BootFailure.getBootFailureFile(home), true); + try (OutputStream o=Files.newOutputStream(BootFailure.getBootFailureFile(home).toPath(), StandardOpenOption.CREATE, StandardOpenOption.APPEND)) { o.write((new Date().toString() + System.getProperty("line.separator", "\n")).toString().getBytes()); } catch (IOException e) { LOGGER.log(WARNING, "Failed to record boot attempts",e); - } finally { - IOUtils.closeQuietly(o); } } diff --git a/core/src/main/java/hudson/XmlFile.java b/core/src/main/java/hudson/XmlFile.java index 9f438eeded..a118163dec 100644 --- a/core/src/main/java/hudson/XmlFile.java +++ b/core/src/main/java/hudson/XmlFile.java @@ -33,6 +33,7 @@ import hudson.diagnosis.OldDataMonitor; import hudson.model.Descriptor; import hudson.util.AtomicFileWriter; import hudson.util.XStream2; +import java.nio.file.Files; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.Locator; @@ -138,7 +139,7 @@ public final class XmlFile { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Reading "+file); } - try (InputStream in = new BufferedInputStream(new FileInputStream(file))) { + try (InputStream in = new BufferedInputStream(Files.newInputStream(file.toPath()))) { return xs.fromXML(in); } catch (XStreamException | Error e) { throw new IOException("Unable to read "+file,e); @@ -154,7 +155,7 @@ public final class XmlFile { */ public Object unmarshal( Object o ) throws IOException { - try (InputStream in = new BufferedInputStream(new FileInputStream(file))) { + try (InputStream in = new BufferedInputStream(Files.newInputStream(file.toPath()))) { // TODO: expose XStream the driver from XStream return xs.unmarshal(DEFAULT_DRIVER.createReader(in), o); } catch (XStreamException | Error e) { @@ -201,7 +202,7 @@ public final class XmlFile { * @return Reader for the file. should be close externally once read. */ public Reader readRaw() throws IOException { - FileInputStream fileInputStream = new FileInputStream(file); + InputStream fileInputStream = Files.newInputStream(file.toPath()); try { return new InputStreamReader(fileInputStream, sniffEncoding()); } catch(IOException ex) { @@ -247,7 +248,7 @@ public final class XmlFile { } } - try (InputStream in = new FileInputStream(file)) { + try (InputStream in = Files.newInputStream(file.toPath())) { InputSource input = new InputSource(file.toURI().toASCIIString()); input.setByteStream(in); JAXP.newSAXParser().parse(input,new DefaultHandler() { diff --git a/core/src/main/java/hudson/lifecycle/WindowsInstallerLink.java b/core/src/main/java/hudson/lifecycle/WindowsInstallerLink.java index a9142adbc6..09bca058d9 100644 --- a/core/src/main/java/hudson/lifecycle/WindowsInstallerLink.java +++ b/core/src/main/java/hudson/lifecycle/WindowsInstallerLink.java @@ -31,6 +31,8 @@ import hudson.model.TaskListener; import hudson.util.jna.Kernel32Utils; import hudson.util.jna.SHELLEXECUTEINFO; import hudson.util.jna.Shell32; +import java.io.InputStream; +import java.nio.file.Files; import jenkins.model.Jenkins; import hudson.AbortException; import hudson.Extension; @@ -306,7 +308,7 @@ public class WindowsInstallerLink extends ManagementLink { try { return Kernel32Utils.waitForExitProcess(sei.hProcess); } finally { - try (FileInputStream fin = new FileInputStream(new File(pwd,"redirect.log"))) { + try (InputStream fin = Files.newInputStream(new File(pwd,"redirect.log").toPath())) { IOUtils.copy(fin, out.getLogger()); } } diff --git a/core/src/main/java/hudson/model/FileParameterValue.java b/core/src/main/java/hudson/model/FileParameterValue.java index 16777ea6be..80461ed214 100644 --- a/core/src/main/java/hudson/model/FileParameterValue.java +++ b/core/src/main/java/hudson/model/FileParameterValue.java @@ -36,6 +36,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; +import java.nio.file.Files; import javax.servlet.ServletException; import org.apache.commons.fileupload.FileItem; @@ -205,7 +206,7 @@ public class FileParameterValue extends ParameterValue { AbstractBuild build = (AbstractBuild)request.findAncestor(AbstractBuild.class).getObject(); File fileParameter = getLocationUnderBuild(build); if (fileParameter.isFile()) { - InputStream data = new FileInputStream(fileParameter); + InputStream data = Files.newInputStream(fileParameter.toPath()); try { long lastModified = fileParameter.lastModified(); long contentLength = fileParameter.length(); @@ -245,7 +246,7 @@ public class FileParameterValue extends ParameterValue { } public InputStream getInputStream() throws IOException { - return new FileInputStream(file); + return Files.newInputStream(file.toPath()); } public String getContentType() { @@ -266,7 +267,7 @@ public class FileParameterValue extends ParameterValue { public byte[] get() { try { - try (FileInputStream inputStream = new FileInputStream(file)) { + try (InputStream inputStream = Files.newInputStream(file.toPath())) { return IOUtils.toByteArray(inputStream); } } catch (IOException e) { @@ -306,7 +307,7 @@ public class FileParameterValue extends ParameterValue { @Deprecated public OutputStream getOutputStream() throws IOException { - return new FileOutputStream(file); + return Files.newOutputStream(file.toPath()); } @Override diff --git a/core/src/main/java/hudson/model/Queue.java b/core/src/main/java/hudson/model/Queue.java index 73348264a4..5357b93758 100644 --- a/core/src/main/java/hudson/model/Queue.java +++ b/core/src/main/java/hudson/model/Queue.java @@ -63,6 +63,7 @@ import hudson.model.queue.CauseOfBlockage.BecauseNodeIsBusy; import hudson.model.queue.WorkUnitContext; import hudson.security.ACL; import hudson.security.AccessControlled; +import java.nio.file.Files; import jenkins.security.QueueItemAuthenticatorProvider; import jenkins.util.Timer; import hudson.triggers.SafeTimerTask; @@ -376,7 +377,7 @@ public class Queue extends ResourceController implements Saveable { // first try the old format File queueFile = getQueueFile(); if (queueFile.exists()) { - try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(queueFile)))) { + try (BufferedReader in = new BufferedReader(new InputStreamReader(Files.newInputStream(queueFile.toPath())))) { String line; while ((line = in.readLine()) != null) { AbstractProject j = Jenkins.getInstance().getItemByFullName(line, AbstractProject.class); diff --git a/core/src/main/java/hudson/model/Run.java b/core/src/main/java/hudson/model/Run.java index e43e18e791..3bc6d67930 100644 --- a/core/src/main/java/hudson/model/Run.java +++ b/core/src/main/java/hudson/model/Run.java @@ -41,6 +41,8 @@ import hudson.console.ConsoleLogFilter; import hudson.console.ConsoleNote; import hudson.console.ModelHyperlinkNote; import hudson.console.PlainTextConsoleOutputStream; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; import jenkins.util.SystemProperties; import hudson.Util; import hudson.XmlFile; @@ -1367,7 +1369,7 @@ public abstract class Run ,RunT extends Run,RunT extends Run iterator() { try { - final BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8")); + final BufferedReader in = new BufferedReader(new InputStreamReader( + Files.newInputStream(file.toPath()),"UTF-8")); return new AbstractIterator() { @Override diff --git a/core/src/main/java/hudson/util/io/ReopenableFileOutputStream.java b/core/src/main/java/hudson/util/io/ReopenableFileOutputStream.java index 1cac1df91a..9881f7c0d7 100644 --- a/core/src/main/java/hudson/util/io/ReopenableFileOutputStream.java +++ b/core/src/main/java/hudson/util/io/ReopenableFileOutputStream.java @@ -28,6 +28,8 @@ import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; /** * {@link OutputStream} that writes to a file. @@ -52,7 +54,8 @@ import java.io.OutputStream; private synchronized OutputStream current() throws IOException { if (current==null) try { - current = new FileOutputStream(out,appendOnNextOpen); + current = Files.newOutputStream(out.toPath(), StandardOpenOption.CREATE, + appendOnNextOpen ? StandardOpenOption.APPEND : StandardOpenOption.TRUNCATE_EXISTING); } catch (FileNotFoundException e) { throw new IOException("Failed to open "+out,e); } diff --git a/core/src/main/java/hudson/util/io/RewindableFileOutputStream.java b/core/src/main/java/hudson/util/io/RewindableFileOutputStream.java index b7bb2b5f02..735344c8b4 100644 --- a/core/src/main/java/hudson/util/io/RewindableFileOutputStream.java +++ b/core/src/main/java/hudson/util/io/RewindableFileOutputStream.java @@ -28,6 +28,8 @@ import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; import org.apache.commons.io.FileUtils; /** @@ -51,7 +53,7 @@ public class RewindableFileOutputStream extends OutputStream { if (!closed) { FileUtils.forceMkdir(out.getParentFile()); try { - current = new FileOutputStream(out,false); + current = Files.newOutputStream(out.toPath(), StandardOpenOption.TRUNCATE_EXISTING); } catch (FileNotFoundException e) { throw new IOException("Failed to open "+out,e); } diff --git a/core/src/main/java/hudson/util/io/TarArchiver.java b/core/src/main/java/hudson/util/io/TarArchiver.java index 013027a188..8ebdc82367 100644 --- a/core/src/main/java/hudson/util/io/TarArchiver.java +++ b/core/src/main/java/hudson/util/io/TarArchiver.java @@ -32,8 +32,10 @@ import hudson.util.IOUtils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; +import java.io.InputStream; import java.io.OutputStream; +import java.nio.file.Files; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarConstants; @@ -100,7 +102,7 @@ final class TarArchiver extends Archiver { if (!file.isDirectory()) { // ensure we don't write more bytes than the declared when we created the entry - try (FileInputStream fin = new FileInputStream(file); + try (InputStream fin = Files.newInputStream(file.toPath()); BoundedInputStream in = new BoundedInputStream(fin, size)) { int len; while ((len = in.read(buf)) >= 0) { diff --git a/core/src/main/java/hudson/util/io/ZipArchiver.java b/core/src/main/java/hudson/util/io/ZipArchiver.java index ef0ae49658..d58a5c292f 100644 --- a/core/src/main/java/hudson/util/io/ZipArchiver.java +++ b/core/src/main/java/hudson/util/io/ZipArchiver.java @@ -26,6 +26,8 @@ package hudson.util.io; import hudson.util.FileVisitor; import hudson.util.IOUtils; +import java.io.InputStream; +import java.nio.file.Files; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream; @@ -69,13 +71,10 @@ final class ZipArchiver extends Archiver { if (mode!=-1) fileZipEntry.setUnixMode(mode); fileZipEntry.setTime(f.lastModified()); zip.putNextEntry(fileZipEntry); - FileInputStream in = new FileInputStream(f); - try { + try (InputStream in = Files.newInputStream(f.toPath())) { int len; while((len=in.read(buf))>=0) zip.write(buf,0,len); - } finally { - in.close(); } zip.closeEntry(); } diff --git a/core/src/main/java/jenkins/diagnosis/HsErrPidList.java b/core/src/main/java/jenkins/diagnosis/HsErrPidList.java index f11090a4b4..c409ac9b32 100644 --- a/core/src/main/java/jenkins/diagnosis/HsErrPidList.java +++ b/core/src/main/java/jenkins/diagnosis/HsErrPidList.java @@ -6,6 +6,9 @@ import hudson.Functions; import hudson.Util; import hudson.model.AdministrativeMonitor; import hudson.util.jna.Kernel32Utils; +import java.nio.file.Files; +import java.nio.file.OpenOption; +import java.nio.file.StandardOpenOption; import jenkins.model.Jenkins; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; @@ -49,7 +52,7 @@ public class HsErrPidList extends AdministrativeMonitor { return; } try { - try (FileChannel ch = new FileInputStream(getSecretKeyFile()).getChannel()) { + try (FileChannel ch = FileChannel.open(getSecretKeyFile().toPath(), StandardOpenOption.READ)) { map = ch.map(MapMode.READ_ONLY,0,1); } diff --git a/core/src/main/java/jenkins/security/DefaultConfidentialStore.java b/core/src/main/java/jenkins/security/DefaultConfidentialStore.java index 7821f492fd..fee8b86655 100644 --- a/core/src/main/java/jenkins/security/DefaultConfidentialStore.java +++ b/core/src/main/java/jenkins/security/DefaultConfidentialStore.java @@ -4,6 +4,9 @@ import hudson.FilePath; import hudson.Util; import hudson.util.Secret; import hudson.util.TextFile; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; import jenkins.model.Jenkins; import javax.crypto.Cipher; @@ -72,11 +75,11 @@ public class DefaultConfidentialStore extends ConfidentialStore { @Override protected void store(ConfidentialKey key, byte[] payload) throws IOException { CipherOutputStream cos=null; - FileOutputStream fos=null; + OutputStream fos=null; try { Cipher sym = Secret.getCipher("AES"); sym.init(Cipher.ENCRYPT_MODE, masterKey); - cos = new CipherOutputStream(fos=new FileOutputStream(getFileFor(key)), sym); + cos = new CipherOutputStream(fos= Files.newOutputStream(getFileFor(key).toPath()), sym); cos.write(payload); cos.write(MAGIC); } catch (GeneralSecurityException e) { @@ -96,14 +99,14 @@ public class DefaultConfidentialStore extends ConfidentialStore { @Override protected byte[] load(ConfidentialKey key) throws IOException { CipherInputStream cis=null; - FileInputStream fis=null; + InputStream fis=null; try { File f = getFileFor(key); if (!f.exists()) return null; Cipher sym = Secret.getCipher("AES"); sym.init(Cipher.DECRYPT_MODE, masterKey); - cis = new CipherInputStream(fis=new FileInputStream(f), sym); + cis = new CipherInputStream(fis=Files.newInputStream(f.toPath()), sym); byte[] bytes = IOUtils.toByteArray(cis); return verifyMagic(bytes); } catch (GeneralSecurityException e) { diff --git a/core/src/main/java/jenkins/util/AntClassLoader.java b/core/src/main/java/jenkins/util/AntClassLoader.java index baf7eb968a..980aa25c00 100644 --- a/core/src/main/java/jenkins/util/AntClassLoader.java +++ b/core/src/main/java/jenkins/util/AntClassLoader.java @@ -17,6 +17,7 @@ */ package jenkins.util; +import java.nio.file.Files; import org.apache.tools.ant.BuildEvent; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; @@ -790,7 +791,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { if (jarFile == null && file.isDirectory()) { File resource = new File(file, resourceName); if (resource.exists()) { - return new FileInputStream(resource); + return Files.newInputStream(resource.toPath()); } } else { if (jarFile == null) { diff --git a/core/src/main/java/jenkins/util/JSONSignatureValidator.java b/core/src/main/java/jenkins/util/JSONSignatureValidator.java index 865a7b9917..2567a48071 100644 --- a/core/src/main/java/jenkins/util/JSONSignatureValidator.java +++ b/core/src/main/java/jenkins/util/JSONSignatureValidator.java @@ -2,6 +2,7 @@ package jenkins.util; import com.trilead.ssh2.crypto.Base64; import hudson.util.FormValidation; +import java.nio.file.Files; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.apache.commons.io.output.NullOutputStream; @@ -173,9 +174,8 @@ public class JSONSignatureValidator { if (cert.isDirectory() || cert.getName().endsWith(".txt")) { continue; // skip directories also any text files that are meant to be documentation } - FileInputStream in = new FileInputStream(cert); Certificate certificate; - try { + try (InputStream in = Files.newInputStream(cert.toPath())) { certificate = cf.generateCertificate(in); } catch (CertificateException e) { LOGGER.log(Level.WARNING, String.format("Files in %s are expected to be either " @@ -184,8 +184,6 @@ public class JSONSignatureValidator { cert.getParentFile().getAbsolutePath(), cert.getAbsolutePath()), e); continue; - } finally { - in.close(); } try { TrustAnchor certificateAuthority = new TrustAnchor((X509Certificate) certificate, null); diff --git a/core/src/main/java/jenkins/util/VirtualFile.java b/core/src/main/java/jenkins/util/VirtualFile.java index f6f592cd5f..4ec04afb40 100644 --- a/core/src/main/java/jenkins/util/VirtualFile.java +++ b/core/src/main/java/jenkins/util/VirtualFile.java @@ -38,6 +38,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.URI; +import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.LinkOption; import java.util.ArrayList; @@ -295,7 +296,7 @@ public abstract class VirtualFile implements Comparable, Serializab if (isIllegalSymlink()) { throw new FileNotFoundException(f.getPath()); } - return new FileInputStream(f); + return Files.newInputStream(f.toPath()); } private boolean isIllegalSymlink() { // TODO JENKINS-26838 try { diff --git a/core/src/main/java/jenkins/util/io/FileBoolean.java b/core/src/main/java/jenkins/util/io/FileBoolean.java index bce8228e4b..3f652875b6 100644 --- a/core/src/main/java/jenkins/util/io/FileBoolean.java +++ b/core/src/main/java/jenkins/util/io/FileBoolean.java @@ -1,5 +1,6 @@ package jenkins.util.io; +import java.nio.file.Files; import jenkins.model.Jenkins; import java.io.File; @@ -56,7 +57,7 @@ public class FileBoolean { public void on() { try { file.getParentFile().mkdirs(); - new FileOutputStream(file).close(); + Files.newOutputStream(file.toPath()).close(); get(); // update state } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to touch "+file); diff --git a/core/src/main/java/jenkins/util/xml/XMLUtils.java b/core/src/main/java/jenkins/util/xml/XMLUtils.java index f5929a38eb..6b756729c5 100644 --- a/core/src/main/java/jenkins/util/xml/XMLUtils.java +++ b/core/src/main/java/jenkins/util/xml/XMLUtils.java @@ -1,5 +1,7 @@ package jenkins.util.xml; +import java.io.InputStream; +import java.nio.file.Files; import jenkins.util.SystemProperties; import org.apache.commons.io.IOUtils; import org.kohsuke.accmod.Restricted; @@ -137,16 +139,9 @@ public final class XMLUtils { throw new IllegalArgumentException(String.format("File %s does not exist or is not a 'normal' file.", file.getAbsolutePath())); } - FileInputStream fileInputStream = new FileInputStream(file); - try { - InputStreamReader fileReader = new InputStreamReader(fileInputStream, encoding); - try { - return parse(fileReader); - } finally { - IOUtils.closeQuietly(fileReader); - } - } finally { - IOUtils.closeQuietly(fileInputStream); + try (InputStream fileInputStream = Files.newInputStream(file.toPath()); + InputStreamReader fileReader = new InputStreamReader(fileInputStream, encoding)) { + return parse(fileReader); } } diff --git a/core/src/test/java/hudson/FilePathTest.java b/core/src/test/java/hudson/FilePathTest.java index 7b515ec213..3608318286 100644 --- a/core/src/test/java/hudson/FilePathTest.java +++ b/core/src/test/java/hudson/FilePathTest.java @@ -43,6 +43,7 @@ import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; +import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; @@ -134,12 +135,12 @@ public class FilePathTest { } private void givenSomeContentInFile(File file, int size) throws IOException { - FileOutputStream os = new FileOutputStream(file); - byte[] buf = new byte[size]; - for (int i=0; i> whenFileIsCopied100TimesConcurrently(final File file) throws InterruptedException { @@ -369,7 +370,7 @@ public class FilePathTest { // Compress archive final FilePath tmpDirPath = new FilePath(tmpDir); - int tar = tmpDirPath.tar(new FileOutputStream(tarFile), tempFile.getName()); + int tar = tmpDirPath.tar(Files.newOutputStream(tarFile.toPath()), tempFile.getName()); assertEquals("One file should have been compressed", 1, tar); // Decompress @@ -725,7 +726,7 @@ public class FilePathTest { // Compress archive final FilePath tmpDirPath = new FilePath(srcFolder); - int tarred = tmpDirPath.tar(new FileOutputStream(archive), "**"); + int tarred = tmpDirPath.tar(Files.newOutputStream(archive.toPath()), "**"); assertEquals("One file should have been compressed", 3, tarred); // Decompress diff --git a/core/src/test/java/hudson/PluginManagerTest.java b/core/src/test/java/hudson/PluginManagerTest.java index 483eaa4678..843e15ba1e 100644 --- a/core/src/test/java/hudson/PluginManagerTest.java +++ b/core/src/test/java/hudson/PluginManagerTest.java @@ -26,6 +26,7 @@ package hudson; import java.io.File; import java.io.FileOutputStream; +import java.nio.file.Files; import org.apache.tools.ant.filters.StringInputStream; import org.junit.Test; import org.xml.sax.SAXException; @@ -151,7 +152,7 @@ public class PluginManagerTest { FileUtils.write(new File(newFolder, manifestPath), SAMPLE_MANIFEST_FILE); final File f = new File(tmp.getRoot(), "my.hpi"); - try(ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f))) { + try(ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(f.toPath()))) { ZipEntry e = new ZipEntry(manifestPath); out.putNextEntry(e); byte[] data = SAMPLE_MANIFEST_FILE.getBytes(); diff --git a/core/src/test/java/hudson/UtilTest.java b/core/src/test/java/hudson/UtilTest.java index b733eecefe..1a57b68314 100644 --- a/core/src/test/java/hudson/UtilTest.java +++ b/core/src/test/java/hudson/UtilTest.java @@ -24,6 +24,7 @@ */ package hudson; +import java.nio.file.Files; import java.util.List; import java.util.Map; import java.util.HashMap; @@ -490,7 +491,7 @@ public class UtilTest { // On unix, can't use "chattr +u" because ext fs ignores it. // On Windows, we can't delete files that are open for reading, so we use that. assert Functions.isWindows(); - final InputStream s = new FileInputStream(f); + final InputStream s = Files.newInputStream(f.toPath()); unlockFileCallables.put(f, new Callable() { public Void call() throws IOException { s.close(); return null; }; }); diff --git a/core/src/test/java/hudson/model/LoadStatisticsTest.java b/core/src/test/java/hudson/model/LoadStatisticsTest.java index 8c5d4091b7..bc1b668fc0 100644 --- a/core/src/test/java/hudson/model/LoadStatisticsTest.java +++ b/core/src/test/java/hudson/model/LoadStatisticsTest.java @@ -26,6 +26,9 @@ package hudson.model; import hudson.model.MultiStageTimeSeries.TimeScale; import hudson.model.queue.SubTask; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.StandardOpenOption; import org.apache.commons.io.IOUtils; import org.jfree.chart.JFreeChart; import org.junit.Test; @@ -87,11 +90,9 @@ public class LoadStatisticsTest { BufferedImage image = chart.createBufferedImage(400, 200); File tempFile = File.createTempFile("chart-", "png"); - FileOutputStream os = new FileOutputStream(tempFile); - try { + try (OutputStream os = Files.newOutputStream(tempFile.toPath(), StandardOpenOption.DELETE_ON_CLOSE)) { ImageIO.write(image, "PNG", os); } finally { - IOUtils.closeQuietly(os); tempFile.delete(); } } diff --git a/core/src/test/java/hudson/os/SUTester.java b/core/src/test/java/hudson/os/SUTester.java index 12d43f9787..286391dffb 100644 --- a/core/src/test/java/hudson/os/SUTester.java +++ b/core/src/test/java/hudson/os/SUTester.java @@ -1,6 +1,8 @@ package hudson.os; import hudson.util.StreamTaskListener; +import java.io.File; +import java.nio.file.Files; import jenkins.security.MasterToSlaveCallable; import java.io.FileOutputStream; @@ -13,7 +15,7 @@ public class SUTester { SU.execute(StreamTaskListener.fromStdout(),"kohsuke","bogus",new MasterToSlaveCallable() { public Object call() throws Throwable { System.out.println("Touching /tmp/x"); - new FileOutputStream("/tmp/x").close(); + Files.newOutputStream(new File("/tmp/x").toPath()).close(); return null; } }); diff --git a/core/src/test/java/hudson/util/io/TarArchiverTest.java b/core/src/test/java/hudson/util/io/TarArchiverTest.java index c85935de33..144be06c55 100644 --- a/core/src/test/java/hudson/util/io/TarArchiverTest.java +++ b/core/src/test/java/hudson/util/io/TarArchiverTest.java @@ -33,6 +33,8 @@ import hudson.util.StreamTaskListener; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; import java.util.Arrays; import static org.junit.Assert.*; import org.junit.Assume; @@ -71,8 +73,8 @@ public class TarArchiverTest { f.chmod(0644); int dirMode = dir.child("subdir").mode(); - dir.tar(new FileOutputStream(tar),"**/*"); - dir.zip(new FileOutputStream(zip)); + dir.tar(Files.newOutputStream(tar.toPath()),"**/*"); + dir.zip(Files.newOutputStream(zip.toPath())); FilePath e = dir.child("extract"); @@ -149,12 +151,12 @@ public class TarArchiverTest { File openFile = file; try { openFile.createNewFile(); - FileOutputStream fos = new FileOutputStream(openFile); - for (int i = 0; !finish && i < 5000000; i++) { // limit the max size, just in case. - fos.write(0); - // Thread.sleep(5); + try (OutputStream fos = Files.newOutputStream(openFile.toPath())) { + for (int i = 0; !finish && i < 5000000; i++) { // limit the max size, just in case. + fos.write(0); + // Thread.sleep(5); + } } - fos.close(); } catch (Exception e) { ex = e; } diff --git a/core/src/test/java/hudson/util/io/ZipArchiverTest.java b/core/src/test/java/hudson/util/io/ZipArchiverTest.java index 08ec7f2f14..cde8bd4ae7 100644 --- a/core/src/test/java/hudson/util/io/ZipArchiverTest.java +++ b/core/src/test/java/hudson/util/io/ZipArchiverTest.java @@ -5,6 +5,7 @@ import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; +import java.nio.file.Files; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; @@ -62,7 +63,7 @@ public class ZipArchiverTest { try { zipFile = File.createTempFile("test", ".zip"); - archiver = new ZipArchiver(new FileOutputStream(zipFile)); + archiver = new ZipArchiver(Files.newOutputStream(zipFile.toPath())); archiver.visit(tmpFile, "foo\\bar\\baz\\Test.txt"); } catch (Exception e) { diff --git a/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java b/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java index dc9ebea798..cfbee3ed2c 100644 --- a/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java +++ b/test/src/test/java/hudson/model/DirectoryBrowserSupportTest.java @@ -38,6 +38,7 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import java.nio.file.Files; import java.util.zip.ZipFile; import org.junit.Assume; @@ -204,7 +205,7 @@ public class DirectoryBrowserSupportTest { File file = File.createTempFile("DirectoryBrowserSupport", "zipDownload"); file.delete(); - Util.copyStreamAndClose(page.getInputStream(), new FileOutputStream(file)); + Util.copyStreamAndClose(page.getInputStream(), Files.newOutputStream(file.toPath())); return file; } diff --git a/test/src/test/java/hudson/tools/JDKInstallerTest.java b/test/src/test/java/hudson/tools/JDKInstallerTest.java index e9ced11efe..458f1547a0 100644 --- a/test/src/test/java/hudson/tools/JDKInstallerTest.java +++ b/test/src/test/java/hudson/tools/JDKInstallerTest.java @@ -8,6 +8,8 @@ import com.gargoylesoftware.htmlunit.html.HtmlFormUtil; import com.gargoylesoftware.htmlunit.html.HtmlPage; import hudson.tools.JDKInstaller.DescriptorImpl; +import java.io.InputStream; +import java.nio.file.Files; import org.junit.Assume; import org.junit.Before; import org.junit.Rule; @@ -54,8 +56,7 @@ public class JDKInstallerTest { LOGGER.warning(f+" doesn't exist. Skipping JDK installation tests"); } else { Properties prop = new Properties(); - FileInputStream in = new FileInputStream(f); - try { + try (InputStream in = Files.newInputStream(f.toPath())) { prop.load(in); String u = prop.getProperty("oracle.userName"); String p = prop.getProperty("oracle.password"); @@ -65,8 +66,6 @@ public class JDKInstallerTest { DescriptorImpl d = j.jenkins.getDescriptorByType(DescriptorImpl.class); d.doPostCredential(u,p); } - } finally { - in.close(); } } } -- GitLab