提交 23cb13aa 编写于 作者: J Jesse Glick 提交者: Oleg Nenashev

Clean up usages of IOUtils.closeQuietly and related calls (#2830)

* Clean up usages of IOUtils.closeQuietly and related calls predating Java 7.

* Review comments from @oleg-nenashev.

* Noticed another place where try-with-resources would protect against a potential leak.
上级 77804c14
......@@ -61,7 +61,6 @@ import hudson.util.io.ArchiverFactory;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
......@@ -728,7 +727,7 @@ public final class FilePath implements Serializable {
private static final long serialVersionUID = 1L;
});
} finally {
org.apache.commons.io.IOUtils.closeQuietly(_in);
_in.close();
}
}
......@@ -1760,15 +1759,11 @@ public final class FilePath implements Serializable {
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
InputStream fis = null;
try {
fis = Files.newInputStream(reading(f).toPath());
Util.copyStream(fis, p.getOut());
try (InputStream fis = Files.newInputStream(reading(f).toPath());
OutputStream out = p.getOut()) {
org.apache.commons.io.IOUtils.copy(fis, out);
} catch (Exception x) {
p.error(x);
} finally {
org.apache.commons.io.IOUtils.closeQuietly(fis);
org.apache.commons.io.IOUtils.closeQuietly(p.getOut());
}
return null;
}
......@@ -1822,10 +1817,9 @@ public final class FilePath implements Serializable {
private static final long serialVersionUID = 1L;
public Void invoke(File f, VirtualChannel channel) throws IOException {
final OutputStream out = new java.util.zip.GZIPOutputStream(p.getOut(), 8192);
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(reading(f), "r");
try (OutputStream os = p.getOut();
OutputStream out = new java.util.zip.GZIPOutputStream(os, 8192);
RandomAccessFile raf = new RandomAccessFile(reading(f), "r")) {
raf.seek(offset);
byte[] buf = new byte[8192];
int len;
......@@ -1833,15 +1827,6 @@ public final class FilePath implements Serializable {
out.write(buf, 0, len);
}
return null;
} finally {
IOUtils.closeQuietly(out);
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
// ignore
}
}
}
}
});
......@@ -2006,14 +1991,11 @@ public final class FilePath implements Serializable {
act(new SecureFileCallable<Void>() {
private static final long serialVersionUID = 4088559042349254141L;
public Void invoke(File f, VirtualChannel channel) throws IOException {
InputStream fis = null;
try {
fis = Files.newInputStream(reading(f).toPath());
Util.copyStream(fis,out);
try (InputStream fis = Files.newInputStream(reading(f).toPath())) {
org.apache.commons.io.IOUtils.copy(fis, out);
return null;
} finally {
org.apache.commons.io.IOUtils.closeQuietly(fis);
org.apache.commons.io.IOUtils.closeQuietly(out);
out.close();
}
}
});
......
......@@ -33,8 +33,6 @@ import com.thoughtworks.xstream.core.util.Base64Encoder;
import hudson.util.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
......@@ -174,11 +172,11 @@ public class Main {
con.connect();
// send the data
try (InputStream in = Files.newInputStream(tmpFile.toPath())) {
Util.copyStream(in,con.getOutputStream());
org.apache.commons.io.IOUtils.copy(in, con.getOutputStream());
}
if(con.getResponseCode()!=200) {
Util.copyStream(con.getErrorStream(),System.err);
org.apache.commons.io.IOUtils.copy(con.getErrorStream(), System.err);
}
return ret;
......
......@@ -339,14 +339,11 @@ public final class TcpSlaveAgentListener extends Thread {
@Override
public void handle(Socket socket) throws IOException, InterruptedException {
try {
OutputStream stream = socket.getOutputStream();
try {
try (OutputStream stream = socket.getOutputStream()) {
LOGGER.log(Level.FINE, "Received ping request from {0}", socket.getRemoteSocketAddress());
stream.write(ping);
stream.flush();
LOGGER.log(Level.FINE, "Sent ping response to {0}", socket.getRemoteSocketAddress());
} finally {
stream.close();
}
} finally {
socket.close();
......@@ -355,29 +352,24 @@ public final class TcpSlaveAgentListener extends Thread {
public boolean connect(Socket socket) throws IOException {
try {
DataOutputStream out = null;
InputStream in = null;
try {
LOGGER.log(Level.FINE, "Requesting ping from {0}", socket.getRemoteSocketAddress());
out = new DataOutputStream(socket.getOutputStream());
LOGGER.log(Level.FINE, "Requesting ping from {0}", socket.getRemoteSocketAddress());
try (DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {
out.writeUTF("Protocol:Ping");
in = socket.getInputStream();
byte[] response = new byte[ping.length];
int responseLength = in.read(response);
if (responseLength == ping.length && Arrays.equals(response, ping)) {
LOGGER.log(Level.FINE, "Received ping response from {0}", socket.getRemoteSocketAddress());
return true;
} else {
LOGGER.log(Level.FINE, "Expected ping response from {0} of {1} got {2}", new Object[]{
socket.getRemoteSocketAddress(),
new String(ping, "UTF-8"),
new String(response, 0, responseLength, "UTF-8")
});
return false;
try (InputStream in = socket.getInputStream()) {
byte[] response = new byte[ping.length];
int responseLength = in.read(response);
if (responseLength == ping.length && Arrays.equals(response, ping)) {
LOGGER.log(Level.FINE, "Received ping response from {0}", socket.getRemoteSocketAddress());
return true;
} else {
LOGGER.log(Level.FINE, "Expected ping response from {0} of {1} got {2}", new Object[]{
socket.getRemoteSocketAddress(),
new String(ping, "UTF-8"),
new String(response, 0, responseLength, "UTF-8")
});
return false;
}
}
} finally {
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(in);
}
} finally {
socket.close();
......
......@@ -25,7 +25,6 @@ package hudson;
import jenkins.util.SystemProperties;
import com.sun.jna.Native;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Proc.LocalProc;
......@@ -645,6 +644,10 @@ public class Util {
}
}
/**
* @deprecated Use {@link IOUtils#copy(InputStream, OutputStream)}
*/
@Deprecated
public static void copyStream(@Nonnull InputStream in,@Nonnull OutputStream out) throws IOException {
byte[] buf = new byte[8192];
int len;
......@@ -652,6 +655,10 @@ public class Util {
out.write(buf,0,len);
}
/**
* @deprecated Use {@link IOUtils#copy(Reader, Writer)}
*/
@Deprecated
public static void copyStream(@Nonnull Reader in, @Nonnull Writer out) throws IOException {
char[] buf = new char[8192];
int len;
......@@ -659,21 +666,23 @@ public class Util {
out.write(buf,0,len);
}
/**
* @deprecated Use {@link IOUtils#copy(InputStream, OutputStream)} in a {@code try}-with-resources block
*/
@Deprecated
public static void copyStreamAndClose(@Nonnull InputStream in, @Nonnull OutputStream out) throws IOException {
try {
try (InputStream _in = in; OutputStream _out = out) { // make sure both are closed, and use Throwable.addSuppressed
copyStream(in,out);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
/**
* @deprecated Use {@link IOUtils#copy(Reader, Writer)} in a {@code try}-with-resources block
*/
@Deprecated
public static void copyStreamAndClose(@Nonnull Reader in, @Nonnull Writer out) throws IOException {
try {
try (Reader _in = in; Writer _out = out) {
copyStream(in,out);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
......
......@@ -45,16 +45,15 @@ import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
/**
* Represents an XML data file that Jenkins uses as a data file.
......@@ -228,7 +227,7 @@ public final class XmlFile {
*/
public void writeRawTo(Writer w) throws IOException {
try (Reader r = readRaw()) {
Util.copyStream(r, w);
IOUtils.copy(r, w);
}
}
......
......@@ -7,7 +7,6 @@ import hudson.model.AbstractProject;
import hudson.model.Item;
import hudson.model.PermalinkProjectAction.Permalink;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.Option;
import java.io.IOException;
......@@ -117,8 +116,7 @@ public class ConsoleCommand extends CLICommand {
}
RingBuffer rb = new RingBuffer();
InputStream in = run.getLogInputStream();
try {
try (InputStream in = run.getLogInputStream()) {
byte[] buf = new byte[4096];
int len;
byte prev=0;
......@@ -137,8 +135,6 @@ public class ConsoleCommand extends CLICommand {
}
return rb.get();
} finally {
org.apache.commons.io.IOUtils.closeQuietly(in);
}
}
......
......@@ -938,12 +938,9 @@ public abstract class Descriptor<T extends Describable<T>> implements Saveable,
if(url!=null) {
// TODO: generalize macro expansion and perhaps even support JEXL
rsp.setContentType("text/html;charset=UTF-8");
InputStream in = url.openStream();
try {
try (InputStream in = url.openStream()) {
String literal = IOUtils.toString(in,"UTF-8");
rsp.getWriter().println(Util.replaceMacro(literal, Collections.singletonMap("rootURL",req.getContextPath())));
} finally {
IOUtils.closeQuietly(in);
}
return;
}
......
......@@ -371,11 +371,8 @@ public final class DirectoryBrowserSupport implements HttpResponse {
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);
try (InputStream in = f.open()) {
IOUtils.copy(in, zos);
}
zos.closeEntry();
}
......
......@@ -30,8 +30,6 @@ import hudson.tasks.BuildWrapper;
import hudson.util.VariableResolver;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
......@@ -206,8 +204,7 @@ public class FileParameterValue extends ParameterValue {
AbstractBuild build = (AbstractBuild)request.findAncestor(AbstractBuild.class).getObject();
File fileParameter = getLocationUnderBuild(build);
if (fileParameter.isFile()) {
InputStream data = Files.newInputStream(fileParameter.toPath());
try {
try (InputStream data = Files.newInputStream(fileParameter.toPath())) {
long lastModified = fileParameter.lastModified();
long contentLength = fileParameter.length();
if (request.hasParameter("view")) {
......@@ -215,8 +212,6 @@ public class FileParameterValue extends ParameterValue {
} else {
response.serveFile(request, data, lastModified, contentLength, originalFileName);
}
} finally {
IOUtils.closeQuietly(data);
}
}
}
......
......@@ -66,8 +66,6 @@ import hudson.util.XStream2;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
......@@ -1398,11 +1396,8 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
// try to fall back to the old getLogInputStream()
// mainly to support .gz compressed files
// In this case, console annotation handling will be turned off.
InputStream input = getLogInputStream();
try {
try (InputStream input = getLogInputStream()) {
IOUtils.copy(input, out.asWriter());
} finally {
IOUtils.closeQuietly(input);
}
}
}
......@@ -2123,14 +2118,11 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
*/
public void doConsoleText(StaplerRequest req, StaplerResponse rsp) throws IOException {
rsp.setContentType("text/plain;charset=UTF-8");
PlainTextConsoleOutputStream out = new PlainTextConsoleOutputStream(rsp.getCompressedOutputStream(req));
InputStream input = getLogInputStream();
try {
;
try (InputStream input = getLogInputStream();
OutputStream os = rsp.getCompressedOutputStream(req);
PlainTextConsoleOutputStream out = new PlainTextConsoleOutputStream(os)) {
IOUtils.copy(input, out);
out.flush();
} finally {
IOUtils.closeQuietly(input);
IOUtils.closeQuietly(out);
}
}
......
......@@ -36,7 +36,6 @@ import jenkins.util.SystemProperties;
import hudson.Util;
import hudson.XmlFile;
import static hudson.init.InitMilestone.PLUGINS_STARTED;
import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING;
import hudson.init.Initializer;
......@@ -52,7 +51,6 @@ import hudson.util.FormValidation;
import hudson.util.HttpResponses;
import hudson.util.NamingThreadFactory;
import hudson.util.IOException2;
import hudson.util.IOUtils;
import hudson.util.PersistedList;
import hudson.util.XStream2;
import jenkins.MissingDependencyException;
......@@ -78,8 +76,8 @@ import javax.annotation.Nonnull;
import javax.net.ssl.SSLHandshakeException;
import javax.servlet.ServletException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.net.HttpRetryException;
......@@ -114,6 +112,7 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import org.acegisecurity.context.SecurityContextHolder;
import org.apache.commons.io.IOUtils;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.export.Exported;
......@@ -1111,8 +1110,6 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
// to be handled by caller
}
CountingInputStream in = null;
OutputStream out = null;
URLConnection con = null;
try {
con = connect(job,src);
......@@ -1122,30 +1119,27 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
con.setReadTimeout(PLUGIN_DOWNLOAD_READ_TIMEOUT);
int total = con.getContentLength();
in = new CountingInputStream(con.getInputStream());
byte[] buf = new byte[8192];
int len;
File dst = job.getDestination();
File tmp = new File(dst.getPath()+".tmp");
out = Files.newOutputStream(tmp.toPath());
if (sha1 != null) {
out = new DigestOutputStream(out, sha1);
}
LOGGER.info("Downloading "+job.getName());
Thread t = Thread.currentThread();
String oldName = t.getName();
t.setName(oldName + ": " + src);
try {
while((len=in.read(buf))>=0) {
try (OutputStream _out = Files.newOutputStream(tmp.toPath());
OutputStream out = sha1 != null ? new DigestOutputStream(_out, sha1) : _out;
InputStream in = con.getInputStream();
CountingInputStream cin = new CountingInputStream(in)) {
while ((len = cin.read(buf)) >= 0) {
out.write(buf,0,len);
job.status = job.new Installing(total==-1 ? -1 : in.getCount()*100/total);
job.status = job.new Installing(total == -1 ? -1 : cin.getCount() * 100 / total);
}
} catch (IOException e) {
throw new IOException("Failed to load "+src+" to "+tmp,e);
} finally {
IOUtils.closeQuietly(out);
t.setName(oldName);
}
......@@ -1171,9 +1165,6 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
extraMessage = " (redirected to: " + con.getURL() + ")";
}
throw new IOException2("Failed to download from "+src+extraMessage,e);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
......@@ -1262,7 +1253,9 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
throw new HttpRetryException("Invalid response code (" + responseCode + ") from URL: " + url, responseCode);
}
} else {
Util.copyStreamAndClose(connection.getInputStream(),new NullOutputStream());
try (InputStream is = connection.getInputStream()) {
IOUtils.copy(is, new NullOutputStream());
}
}
} catch (SSLHandshakeException e) {
if (e.getMessage().contains("PKIX path building failed"))
......
......@@ -28,7 +28,6 @@ import hudson.PluginWrapper;
import hudson.Util;
import hudson.Extension;
import hudson.node_monitors.ArchitectureMonitor.DescriptorImpl;
import hudson.util.IOUtils;
import hudson.util.Secret;
import static hudson.util.TimeUnit2.DAYS;
......@@ -181,11 +180,10 @@ public class UsageStatistics extends PageDecorator {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// json -> UTF-8 encode -> gzip -> encrypt -> base64 -> string
OutputStreamWriter w = new OutputStreamWriter(new GZIPOutputStream(new CombinedCipherOutputStream(baos,getKey(),"AES")), "UTF-8");
try {
try (OutputStream cipheros = new CombinedCipherOutputStream(baos,getKey(),"AES");
OutputStream zipos = new GZIPOutputStream(cipheros);
OutputStreamWriter w = new OutputStreamWriter(zipos, "UTF-8")) {
o.write(w);
} finally {
IOUtils.closeQuietly(w);
}
return new String(Base64.encode(baos.toByteArray()));
......
......@@ -48,7 +48,6 @@ import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.tasks.Builder;
import hudson.util.IOUtils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
......@@ -683,13 +682,8 @@ public abstract class SCM implements Describable<SCM>, ExtensionPoint {
* @since 1.568
*/
protected final void createEmptyChangeLog(@Nonnull File changelogFile, @Nonnull TaskListener listener, @Nonnull String rootTag) throws IOException {
FileWriter w = null;
try {
w = new FileWriter(changelogFile);
try (FileWriter w = new FileWriter(changelogFile)) {
w.write("<"+rootTag +"/>");
w.close();
} finally {
IOUtils.closeQuietly(w);
}
}
......
......@@ -673,7 +673,11 @@ public class SlaveComputer extends Computer {
protected void kill() {
super.kill();
closeChannel();
IOUtils.closeQuietly(log);
try {
log.close();
} catch (IOException x) {
LOGGER.log(Level.WARNING, "Failed to close agent log", x);
}
try {
Util.deleteRecursive(getLogDir());
......
......@@ -32,7 +32,6 @@ import hudson.ProxyConfiguration;
import hudson.Util;
import hudson.model.DownloadService.Downloadable;
import hudson.model.JDK;
import hudson.model.Job;
import hudson.model.Node;
import hudson.model.TaskListener;
import hudson.util.ArgumentListBuilder;
......@@ -64,7 +63,6 @@ import javax.servlet.ServletException;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
......@@ -185,11 +183,9 @@ public class JDKInstaller extends ToolInstaller {
// so check if the file is gzipped, and if so, treat it accordingly
byte[] header = new byte[2];
{
DataInputStream in = new DataInputStream(fs.read(jdkBundle));
try {
try (InputStream is = fs.read(jdkBundle);
DataInputStream in = new DataInputStream(is)) {
in.readFully(header);
} finally {
IOUtils.closeQuietly(in);
}
}
......
......@@ -42,13 +42,13 @@ import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.util.FlushProofOutputStream;
import hudson.util.FormValidation;
import hudson.util.IOUtils;
import hudson.util.NamingThreadFactory;
import hudson.util.SequentialExecutionQueue;
import hudson.util.StreamTaskListener;
import hudson.util.TimeUnit2;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.text.DateFormat;
......@@ -450,12 +450,10 @@ public class SCMTrigger extends Trigger<Item> {
*/
public void doPollingLog(StaplerRequest req, StaplerResponse rsp) throws IOException {
rsp.setContentType("text/plain;charset=UTF-8");
// Prevent jelly from flushing stream so Content-Length header can be added afterwards
FlushProofOutputStream out = new FlushProofOutputStream(rsp.getCompressedOutputStream(req));
try {
try (OutputStream os = rsp.getCompressedOutputStream(req);
// Prevent jelly from flushing stream so Content-Length header can be added afterwards
FlushProofOutputStream out = new FlushProofOutputStream(os)) {
getPollingLogText().writeLogTo(0, out);
} finally {
IOUtils.closeQuietly(out);
}
}
......
......@@ -25,7 +25,6 @@ package hudson.util;
import com.jcraft.jzlib.GZIPInputStream;
import com.jcraft.jzlib.GZIPOutputStream;
import hudson.Util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
......@@ -112,14 +111,12 @@ public class CompressedFile {
StringBuilder str = new StringBuilder((int)sizeGuess);
Reader r = new InputStreamReader(read());
try {
try (InputStream is = read();
Reader r = new InputStreamReader(is)) {
char[] buf = new char[8192];
int len;
while((len=r.read(buf,0,buf.length))>0)
str.append(buf,0,len);
} finally {
IOUtils.closeQuietly(r);
}
return str.toString();
......@@ -137,8 +134,9 @@ public class CompressedFile {
public void run() {
try {
try (InputStream in = read();
OutputStream out = new GZIPOutputStream(Files.newOutputStream(gz.toPath()))) {
Util.copyStream(in, out);
OutputStream os = Files.newOutputStream(gz.toPath());
OutputStream out = new GZIPOutputStream(os)) {
org.apache.commons.io.IOUtils.copy(in, out);
}
// if the compressed file is created successfully, remove the original
file.delete();
......
......@@ -183,7 +183,7 @@ public class IOUtils {
}
/**
* @deprecated Use instead {@link org.apache.commons.io.IOUtils#closeQuietly(java.io.Reader)}
* @deprecated Use Java 7 {@code try}-with-resources instead.
*/
@Deprecated
public static void closeQuietly(Reader input) {
......@@ -191,7 +191,7 @@ public class IOUtils {
}
/**
* @deprecated Use instead {@link org.apache.commons.io.IOUtils#closeQuietly(java.io.Writer)}
* @deprecated Use Java 7 {@code try}-with-resources instead.
*/
@Deprecated
public static void closeQuietly(Writer output) {
......@@ -199,7 +199,7 @@ public class IOUtils {
}
/**
* @deprecated Use instead {@link org.apache.commons.io.IOUtils#closeQuietly(java.io.InputStream)}
* @deprecated Use Java 7 {@code try}-with-resources instead.
*/
@Deprecated
public static void closeQuietly(InputStream input) {
......@@ -207,7 +207,7 @@ public class IOUtils {
}
/**
* @deprecated Use instead {@link org.apache.commons.io.IOUtils#closeQuietly(java.io.OutputStream)}
* @deprecated Use Java 7 {@code try}-with-resources instead.
*/
@Deprecated
public static void closeQuietly(OutputStream output) {
......
......@@ -41,7 +41,7 @@ import java.util.HashMap;
*
* @author Kohsuke Kawaguchi
*/
public class MultipartFormDataParser {
public class MultipartFormDataParser implements AutoCloseable {
private final ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
private final Map<String,FileItem> byName = new HashMap<String,FileItem>();
......@@ -73,6 +73,12 @@ public class MultipartFormDataParser {
item.delete();
}
/** Alias for {@link #cleanUp}. */
@Override
public void close() {
cleanUp();
}
/**
* Checks a Content-Type string to assert if it is "multipart/form-data".
*
......
......@@ -29,7 +29,6 @@ import java.nio.file.Files;
import javax.annotation.Nonnull;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
......@@ -129,9 +128,7 @@ public class TextFile {
public @Nonnull String head(int numChars) throws IOException {
char[] buf = new char[numChars];
int read = 0;
Reader r = new FileReader(file);
try {
try (Reader r = new FileReader(file)) {
while (read<numChars) {
int d = r.read(buf,read,buf.length-read);
if (d<0)
......@@ -140,8 +137,6 @@ public class TextFile {
}
return new String(buf,0,read);
} finally {
org.apache.commons.io.IOUtils.closeQuietly(r);
}
}
......
......@@ -19,6 +19,7 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
......@@ -123,9 +124,8 @@ public class HsErrPidList extends AdministrativeMonitor {
private void scanFile(File log) {
LOGGER.fine("Scanning "+log);
BufferedReader r=null;
try {
r = new BufferedReader(new FileReader(log));
try (Reader rawReader = new FileReader(log);
BufferedReader r = new BufferedReader(rawReader)) {
if (!findHeader(r))
return;
......@@ -144,8 +144,6 @@ public class HsErrPidList extends AdministrativeMonitor {
} catch (IOException e) {
// not a big enough deal.
LOGGER.log(Level.FINE, "Failed to parse hs_err_pid file: " + log, e);
} finally {
IOUtils.closeQuietly(r);
}
}
......
......@@ -155,7 +155,6 @@ import hudson.util.FormValidation;
import hudson.util.Futures;
import hudson.util.HudsonIsLoading;
import hudson.util.HudsonIsRestarting;
import hudson.util.IOUtils;
import hudson.util.Iterators;
import hudson.util.JenkinsReloadFailed;
import hudson.util.Memoizer;
......@@ -3987,15 +3986,12 @@ public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLeve
*/
public void doDoFingerprintCheck( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// Parse the request
MultipartFormDataParser p = new MultipartFormDataParser(req);
if(isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) {
rsp.sendError(HttpServletResponse.SC_FORBIDDEN,"No crumb found");
}
try {
try (MultipartFormDataParser p = new MultipartFormDataParser(req)) {
if (isUseCrumbs() && !getCrumbIssuer().validateCrumb(req, p)) {
rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "No crumb found");
}
rsp.sendRedirect2(req.getContextPath()+"/fingerprint/"+
Util.getDigestOf(p.getFileItem("name").getInputStream())+'/');
} finally {
p.cleanUp();
}
}
......@@ -4860,15 +4856,11 @@ public class Jenkins extends AbstractCIBase implements DirectlyModifiableTopLeve
private static void computeVersion(ServletContext context) {
// set the version
Properties props = new Properties();
InputStream is = null;
try {
is = Jenkins.class.getResourceAsStream("jenkins-version.properties");
try (InputStream is = Jenkins.class.getResourceAsStream("jenkins-version.properties")) {
if(is!=null)
props.load(is);
} catch (IOException e) {
e.printStackTrace(); // if the version properties is missing, that's OK.
} finally {
IOUtils.closeQuietly(is);
}
String ver = props.getProperty("version");
if(ver==null) ver = UNCOMPUTED_VERSION;
......
......@@ -14,8 +14,6 @@ import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
......@@ -74,19 +72,16 @@ public class DefaultConfidentialStore extends ConfidentialStore {
*/
@Override
protected void store(ConfidentialKey key, byte[] payload) throws IOException {
CipherOutputStream cos=null;
OutputStream fos=null;
try {
Cipher sym = Secret.getCipher("AES");
sym.init(Cipher.ENCRYPT_MODE, masterKey);
cos = new CipherOutputStream(fos= Files.newOutputStream(getFileFor(key).toPath()), sym);
cos.write(payload);
cos.write(MAGIC);
try (OutputStream fos = Files.newOutputStream(getFileFor(key).toPath());
CipherOutputStream cos = new CipherOutputStream(fos, sym)) {
cos.write(payload);
cos.write(MAGIC);
}
} catch (GeneralSecurityException e) {
throw new IOException("Failed to persist the key: "+key.getId(),e);
} finally {
IOUtils.closeQuietly(cos);
IOUtils.closeQuietly(fos);
}
}
......@@ -98,17 +93,17 @@ public class DefaultConfidentialStore extends ConfidentialStore {
*/
@Override
protected byte[] load(ConfidentialKey key) throws IOException {
CipherInputStream cis=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=Files.newInputStream(f.toPath()), sym);
byte[] bytes = IOUtils.toByteArray(cis);
return verifyMagic(bytes);
try (InputStream fis=Files.newInputStream(f.toPath());
CipherInputStream cis = new CipherInputStream(fis, sym)) {
byte[] bytes = IOUtils.toByteArray(cis);
return verifyMagic(bytes);
}
} catch (GeneralSecurityException e) {
throw new IOException("Failed to load the key: "+key.getId(),e);
} catch (IOException x) {
......@@ -117,9 +112,6 @@ public class DefaultConfidentialStore extends ConfidentialStore {
} else {
throw x;
}
} finally {
IOUtils.closeQuietly(cis);
IOUtils.closeQuietly(fis);
}
}
......
package jenkins.slaves;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.ClassicPluginStrategy;
import hudson.Extension;
import hudson.Functions;
import hudson.TcpSlaveAgentListener.ConnectionFromCurrentPeer;
import hudson.Util;
import hudson.model.Computer;
import hudson.model.Slave;
import hudson.remoting.Channel;
......@@ -23,11 +21,9 @@ import javax.annotation.Nonnull;
import jenkins.model.Jenkins;
import jenkins.security.ChannelConfigurator;
import jenkins.util.SystemProperties;
import org.apache.commons.io.IOUtils;
import org.jenkinsci.remoting.engine.JnlpConnectionState;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
......@@ -173,7 +169,11 @@ public class DefaultJnlpSlaveReceiver extends JnlpAgentReceiver {
} catch (IOException | InterruptedException e) {
PrintWriter logw = new PrintWriter(state.getLog(), true);
Functions.printStackTrace(e, logw);
IOUtils.closeQuietly(event.getChannel());
try {
event.getChannel().close();
} catch (IOException x) {
LOGGER.log(Level.WARNING, null, x);
}
}
}
......
......@@ -29,13 +29,11 @@ import static org.junit.Assert.assertTrue;
import hudson.FilePath;
import hudson.Functions;
import hudson.Launcher;
import hudson.Util;
import hudson.tasks.ArtifactArchiver;
import hudson.tasks.BatchFile;
import hudson.tasks.Shell;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
......@@ -53,6 +51,8 @@ import org.jvnet.hudson.test.TestBuilder;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.UnexpectedPage;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import java.io.OutputStream;
import org.apache.commons.io.IOUtils;
/**
* @author Kohsuke Kawaguchi
......@@ -205,7 +205,10 @@ public class DirectoryBrowserSupportTest {
File file = File.createTempFile("DirectoryBrowserSupport", "zipDownload");
file.delete();
Util.copyStreamAndClose(page.getInputStream(), Files.newOutputStream(file.toPath()));
try (InputStream is = page.getInputStream();
OutputStream os = Files.newOutputStream(file.toPath())) {
IOUtils.copy(is, os);
}
return file;
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册