Skip to content

Commit

Permalink
[JENKINS-42934] Avoid using new FileInputStream / new FileOutputStream
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenc committed Mar 20, 2017
1 parent 4948d6c commit f0cd7ae
Show file tree
Hide file tree
Showing 41 changed files with 188 additions and 159 deletions.
4 changes: 3 additions & 1 deletion cli/src/main/java/hudson/cli/PrivateKeyProvider.java
Expand Up @@ -30,6 +30,8 @@
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;
Expand Down Expand Up @@ -127,7 +129,7 @@ public static KeyPair loadKey(File f, String passwd) throws IOException, General
}

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);
Expand Down
14 changes: 5 additions & 9 deletions core/src/main/java/hudson/ClassicPluginStrategy.java
Expand Up @@ -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;
Expand Down Expand Up @@ -123,11 +125,8 @@ private static Manifest loadLinkedManifest(File archive) throws IOException {
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
Expand All @@ -137,11 +136,8 @@ private static Manifest loadLinkedManifest(File archive) throws IOException {
}

// 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);
Expand Down Expand Up @@ -173,7 +169,7 @@ private static Manifest loadLinkedManifest(File archive) throws IOException {
"Plugin installation failed. No manifest at "
+ manifestFile);
}
try (FileInputStream fin = new FileInputStream(manifestFile)) {
try (InputStream fin = Files.newInputStream(manifestFile.toPath())) {
manifest = new Manifest(fin);
}
}
Expand Down
69 changes: 35 additions & 34 deletions core/src/main/java/hudson/FilePath.java
Expand Up @@ -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;
Expand Down Expand Up @@ -59,29 +58,9 @@
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;
Expand All @@ -99,6 +78,7 @@
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;
Expand All @@ -116,16 +96,37 @@
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.
Expand Down Expand Up @@ -1470,7 +1471,7 @@ public void touch(final long timestamp) throws IOException, InterruptedException
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;
Expand Down Expand Up @@ -1751,17 +1752,17 @@ private static String[] glob(File dir, String includes, String excludes, boolean
*/
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<Void>() {
private static final long serialVersionUID = 1L;

@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);
Expand Down Expand Up @@ -1876,15 +1877,15 @@ public OutputStream write() throws IOException, InterruptedException {
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<OutputStream>() {
private static final long serialVersionUID = 1L;
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);
}
});
Expand All @@ -1902,8 +1903,8 @@ public void write(final String content, final String encoding) throws IOExceptio
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;
Expand Down Expand Up @@ -2005,9 +2006,9 @@ public void copyTo(OutputStream os) throws IOException, InterruptedException {
act(new SecureFileCallable<Void>() {
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 {
Expand Down
3 changes: 2 additions & 1 deletion core/src/main/java/hudson/FileSystemProvisioner.java
Expand Up @@ -31,6 +31,7 @@
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;
Expand Down Expand Up @@ -215,7 +216,7 @@ public WorkspaceSnapshot snapshot(AbstractBuild<?, ?> build, FilePath ws, TaskLi
*/
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();
Expand Down
16 changes: 6 additions & 10 deletions core/src/main/java/hudson/Main.java
Expand Up @@ -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;
Expand Down Expand Up @@ -135,11 +138,9 @@ public static int remotePost(String[] args) throws Exception {
// 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("<?xml version='1.0' encoding='UTF-8'?>");
w.write("<run><log encoding='hexBinary' content-encoding='"+Charset.defaultCharset().name()+"'>");
w.flush();
Expand All @@ -156,8 +157,6 @@ public static int remotePost(String[] args) throws Exception {
ret = proc.join();

w.write("</log><result>"+ret+"</result><duration>"+(System.currentTimeMillis()-start)+"</duration></run>");
} finally {
IOUtils.closeQuietly(w);
}

URL location = new URL(jobURL, "postBuildResult");
Expand All @@ -174,11 +173,8 @@ public static int remotePost(String[] args) throws Exception {
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) {
Expand Down
3 changes: 2 additions & 1 deletion core/src/main/java/hudson/PluginWrapper.java
Expand Up @@ -29,6 +29,7 @@
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;
Expand Down Expand Up @@ -495,7 +496,7 @@ public void enable() throws IOException {
*/
public void disable() throws IOException {
// creates an empty file
OutputStream os = new FileOutputStream(disableFile);
OutputStream os = Files.newOutputStream(disableFile.toPath());
os.close();
}

Expand Down
6 changes: 3 additions & 3 deletions core/src/main/java/hudson/Util.java
Expand Up @@ -198,7 +198,7 @@ public static String loadFile(@Nonnull File logfile, @Nonnull Charset charset) t

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)
Expand Down Expand Up @@ -800,7 +800,7 @@ public static String getDigestOf(@Nonnull String text) {
*/
@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));
}
}
Expand Down Expand Up @@ -1134,7 +1134,7 @@ public static String xmlEscape(@Nonnull String text) {
* Creates an empty file.
*/
public static void touch(@Nonnull File file) throws IOException {
new FileOutputStream(file).close();
Files.newOutputStream(file.toPath()).close();
}

/**
Expand Down
9 changes: 4 additions & 5 deletions core/src/main/java/hudson/WebAppMain.java
Expand Up @@ -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;
Expand Down Expand Up @@ -273,14 +276,10 @@ public void joinInit() throws InterruptedException {
* @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);
}
}

Expand Down
9 changes: 5 additions & 4 deletions core/src/main/java/hudson/XmlFile.java
Expand Up @@ -33,6 +33,7 @@
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;
Expand Down Expand Up @@ -138,7 +139,7 @@ public Object read() throws IOException {
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);
Expand All @@ -154,7 +155,7 @@ public Object read() throws IOException {
*/
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) {
Expand Down Expand Up @@ -201,7 +202,7 @@ public String toString() {
* @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) {
Expand Down Expand Up @@ -247,7 +248,7 @@ public Eureka(String encoding) {
}
}

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() {
Expand Down

0 comments on commit f0cd7ae

Please sign in to comment.