You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by gg...@apache.org on 2020/09/20 22:50:19 UTC
[commons-net] 02/02: Fix potential resource leaks with
try-with-resource blocks.
This is an automated email from the ASF dual-hosted git repository.
ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-net.git
commit e2715a012ab91a844d28b0963e2f8b322c225ab9
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Sun Sep 20 18:47:12 2020 -0400
Fix potential resource leaks with try-with-resource blocks.
---
.../net/examples/cidr/SubnetUtilsExample.java | 17 +++---
.../commons/net/examples/ftp/FTPClientExample.java | 20 ++-----
.../commons/net/examples/mail/POP3ExportMbox.java | 59 ++++++++++----------
.../apache/commons/net/examples/unix/chargen.java | 24 ++++----
.../apache/commons/net/finger/FingerClient.java | 13 +----
.../java/org/apache/commons/net/ftp/FTPClient.java | 36 +++++-------
.../java/org/apache/commons/net/ftp/FTPFile.java | 64 +++++++++++-----------
.../apache/commons/net/ftp/FTPListParseEngine.java | 15 +++--
.../org/apache/commons/net/nntp/NNTPClient.java | 44 ++++++---------
.../org/apache/commons/net/smtp/SMTPClient.java | 12 ++--
10 files changed, 133 insertions(+), 171 deletions(-)
diff --git a/src/main/java/org/apache/commons/net/examples/cidr/SubnetUtilsExample.java b/src/main/java/org/apache/commons/net/examples/cidr/SubnetUtilsExample.java
index 57cb1b8..6786993 100644
--- a/src/main/java/org/apache/commons/net/examples/cidr/SubnetUtilsExample.java
+++ b/src/main/java/org/apache/commons/net/examples/cidr/SubnetUtilsExample.java
@@ -55,17 +55,16 @@ public class SubnetUtilsExample {
System.out.printf("Total usable addresses: \t%d%n", Long.valueOf(info.getAddressCountLong()));
System.out.printf("Address List: %s%n%n", Arrays.toString(info.getAllAddresses()));
- final String prompt ="Enter an IP address (e.g. 192.168.0.10):";
+ final String prompt = "Enter an IP address (e.g. 192.168.0.10):";
System.out.println(prompt);
- final Scanner scanner = new Scanner(System.in);
- while (scanner.hasNextLine()) {
- final String address = scanner.nextLine();
- System.out.println("The IP address [" + address + "] is "
- + (info.isInRange(address) ? "" : "not ")
- + "within the subnet [" + subnet + "]");
- System.out.println(prompt);
+ try (final Scanner scanner = new Scanner(System.in)) {
+ while (scanner.hasNextLine()) {
+ final String address = scanner.nextLine();
+ System.out.println("The IP address [" + address + "] is " + (info.isInRange(address) ? "" : "not ")
+ + "within the subnet [" + subnet + "]");
+ System.out.println(prompt);
+ }
}
- scanner.close();
}
}
diff --git a/src/main/java/org/apache/commons/net/examples/ftp/FTPClientExample.java b/src/main/java/org/apache/commons/net/examples/ftp/FTPClientExample.java
index 9691ad9..887037d 100644
--- a/src/main/java/org/apache/commons/net/examples/ftp/FTPClientExample.java
+++ b/src/main/java/org/apache/commons/net/examples/ftp/FTPClientExample.java
@@ -397,13 +397,9 @@ __main:
if (storeFile)
{
- InputStream input;
-
- input = new FileInputStream(local);
-
- ftp.storeFile(remote, input);
-
- input.close();
+ try (InputStream input = new FileInputStream(local)) {
+ ftp.storeFile(remote, input);
+ }
if (keepAliveTimeout > 0) {
showCslStats(ftp);
@@ -505,13 +501,9 @@ __main:
}
else
{
- OutputStream output;
-
- output = new FileOutputStream(local);
-
- ftp.retrieveFile(remote, output);
-
- output.close();
+ try (OutputStream output = new FileOutputStream(local)) {
+ ftp.retrieveFile(remote, output);
+ }
if (keepAliveTimeout > 0) {
showCslStats(ftp);
diff --git a/src/main/java/org/apache/commons/net/examples/mail/POP3ExportMbox.java b/src/main/java/org/apache/commons/net/examples/mail/POP3ExportMbox.java
index cb28027..2f1410b 100644
--- a/src/main/java/org/apache/commons/net/examples/mail/POP3ExportMbox.java
+++ b/src/main/java/org/apache/commons/net/examples/mail/POP3ExportMbox.java
@@ -141,19 +141,20 @@ public final class POP3ExportMbox
System.out.println("Writing dir: " + mbox);
// Currently POP3Client uses iso-8859-1
for (int i = 1; i <= count; i++) {
- final OutputStreamWriter fw = new OutputStreamWriter(
- new FileOutputStream(new File(mbox,i+".eml")),StandardCharsets.ISO_8859_1);
- writeFile(pop3, fw, i);
- fw.close();
+ try (final OutputStreamWriter fw = new OutputStreamWriter(
+ new FileOutputStream(new File(mbox, i + ".eml")), StandardCharsets.ISO_8859_1)) {
+ writeFile(pop3, fw, i);
+ }
}
} else {
System.out.println("Writing file: " + mbox);
// Currently POP3Client uses iso-8859-1
- final OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(mbox),StandardCharsets.ISO_8859_1);
- for (int i = 1; i <= count; i++) {
- writeMbox(pop3, fw, i);
+ try (final OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(mbox),
+ StandardCharsets.ISO_8859_1)) {
+ for (int i = 1; i <= count; i++) {
+ writeMbox(pop3, fw, i);
+ }
}
- fw.close();
}
}
@@ -168,38 +169,36 @@ public final class POP3ExportMbox
}
private static void writeFile(final POP3Client pop3, final OutputStreamWriter fw, final int i) throws IOException {
- final BufferedReader r = (BufferedReader) pop3.retrieveMessage(i);
- String line;
- while ((line = r.readLine()) != null)
- {
- fw.write(line);
- fw.write("\n");
+ try (final BufferedReader r = (BufferedReader) pop3.retrieveMessage(i)) {
+ String line;
+ while ((line = r.readLine()) != null) {
+ fw.write(line);
+ fw.write("\n");
+ }
}
- r.close();
}
private static void writeMbox(final POP3Client pop3, final OutputStreamWriter fw, final int i) throws IOException {
final SimpleDateFormat DATE_FORMAT // for mbox From_ lines
- = new SimpleDateFormat("EEE MMM dd HH:mm:ss YYYY");
+ = new SimpleDateFormat("EEE MMM dd HH:mm:ss YYYY");
final String replyTo = "MAILER-DAEMON"; // default
final Date received = new Date();
- final BufferedReader r = (BufferedReader) pop3.retrieveMessage(i);
- fw.append("From ");
- fw.append(replyTo);
- fw.append(' ');
- fw.append(DATE_FORMAT.format(received));
- fw.append("\n");
- String line;
- while ((line = r.readLine()) != null)
- {
- if (startsWith(line, PATFROM)) {
- fw.write(">");
+ try (final BufferedReader r = (BufferedReader) pop3.retrieveMessage(i)) {
+ fw.append("From ");
+ fw.append(replyTo);
+ fw.append(' ');
+ fw.append(DATE_FORMAT.format(received));
+ fw.append("\n");
+ String line;
+ while ((line = r.readLine()) != null) {
+ if (startsWith(line, PATFROM)) {
+ fw.write(">");
+ }
+ fw.write(line);
+ fw.write("\n");
}
- fw.write(line);
fw.write("\n");
}
- fw.write("\n");
- r.close();
}
private static boolean startsWith(final String input, final Pattern pat) {
diff --git a/src/main/java/org/apache/commons/net/examples/unix/chargen.java b/src/main/java/org/apache/commons/net/examples/unix/chargen.java
index 426ac99..781b7fc 100644
--- a/src/main/java/org/apache/commons/net/examples/unix/chargen.java
+++ b/src/main/java/org/apache/commons/net/examples/unix/chargen.java
@@ -47,26 +47,22 @@ public final class chargen
int lines = 100;
String line;
final CharGenTCPClient client = new CharGenTCPClient();
- BufferedReader chargenInput;
// We want to timeout if a response takes longer than 60 seconds
client.setDefaultTimeout(60000);
client.connect(host);
- chargenInput =
- new BufferedReader(new InputStreamReader(client.getInputStream()));
-
- // We assume the chargen service outputs lines, but it really doesn't
- // have to, so this code might actually not work if no newlines are
- // present.
- while (lines-- > 0)
- {
- if ((line = chargenInput.readLine()) == null) {
- break;
+ try (BufferedReader chargenInput = new BufferedReader(new InputStreamReader(client.getInputStream()))) {
+
+ // We assume the chargen service outputs lines, but it really doesn't
+ // have to, so this code might actually not work if no newlines are
+ // present.
+ while (lines-- > 0) {
+ if ((line = chargenInput.readLine()) == null) {
+ break;
+ }
+ System.out.println(line);
}
- System.out.println(line);
}
-
- chargenInput.close();
client.disconnect();
}
diff --git a/src/main/java/org/apache/commons/net/finger/FingerClient.java b/src/main/java/org/apache/commons/net/finger/FingerClient.java
index 11c7654..4993d86 100644
--- a/src/main/java/org/apache/commons/net/finger/FingerClient.java
+++ b/src/main/java/org/apache/commons/net/finger/FingerClient.java
@@ -85,23 +85,16 @@ public class FingerClient extends SocketClient
{
int read;
final StringBuilder result = new StringBuilder(__buffer.length);
- BufferedReader input;
- input =
- new BufferedReader(new InputStreamReader(getInputStream(longOutput,
- username), getCharset()));
-
- try {
- while (true)
- {
+ try (BufferedReader input = new BufferedReader(
+ new InputStreamReader(getInputStream(longOutput, username), getCharset()));) {
+ while (true) {
read = input.read(__buffer, 0, __buffer.length);
if (read <= 0) {
break;
}
result.append(__buffer, 0, read);
}
- } finally {
- input.close();
}
return result.toString();
diff --git a/src/main/java/org/apache/commons/net/ftp/FTPClient.java b/src/main/java/org/apache/commons/net/ftp/FTPClient.java
index c0ab811..56e0447 100644
--- a/src/main/java/org/apache/commons/net/ftp/FTPClient.java
+++ b/src/main/java/org/apache/commons/net/ftp/FTPClient.java
@@ -825,9 +825,7 @@ implements Configurable
{
// if no activePortRange was set (correctly) -> getActivePort() = 0
// -> new ServerSocket(0) -> bind to any free local port
- final ServerSocket server = _serverSocketFactory_.createServerSocket(getActivePort(), 1, getHostAddress());
-
- try {
+ try (final ServerSocket server = _serverSocketFactory_.createServerSocket(getActivePort(), 1, getHostAddress())) {
// Try EPRT only if remote server is over IPv6, if not use PORT,
// because EPRT has no advantage over PORT on IPv4.
// It could even have the disadvantage,
@@ -872,8 +870,6 @@ implements Configurable
if (__sendDataSocketBufferSize > 0) {
socket.setSendBufferSize(__sendDataSocketBufferSize);
}
- } finally {
- server.close();
}
}
else
@@ -2940,27 +2936,25 @@ implements Configurable
*/
public String[] listNames(final String pathname) throws IOException
{
- final Socket socket = _openDataConnection_(FTPCmd.NLST, getListArguments(pathname));
+ final ArrayList<String> results = new ArrayList<>();
+ try (final Socket socket = _openDataConnection_(FTPCmd.NLST, getListArguments(pathname))) {
- if (socket == null) {
- return null;
- }
+ if (socket == null) {
+ return null;
+ }
- final BufferedReader reader =
- new BufferedReader(new InputStreamReader(socket.getInputStream(), getControlEncoding()));
+ try (final BufferedReader reader = new BufferedReader(
+ new InputStreamReader(socket.getInputStream(), getControlEncoding()))) {
- final ArrayList<String> results = new ArrayList<>();
- String line;
- while ((line = reader.readLine()) != null) {
- results.add(line);
+ String line;
+ while ((line = reader.readLine()) != null) {
+ results.add(line);
+ }
+ }
}
- reader.close();
- socket.close();
-
- if (completePendingCommand())
- {
- final String[] names = new String[ results.size() ];
+ if (completePendingCommand()) {
+ final String[] names = new String[results.size()];
return results.toArray(names);
}
diff --git a/src/main/java/org/apache/commons/net/ftp/FTPFile.java b/src/main/java/org/apache/commons/net/ftp/FTPFile.java
index 7b3e02d..90b8f2f 100644
--- a/src/main/java/org/apache/commons/net/ftp/FTPFile.java
+++ b/src/main/java/org/apache/commons/net/ftp/FTPFile.java
@@ -460,44 +460,44 @@ public class FTPFile implements Serializable
return "[Invalid: could not parse file entry]";
}
final StringBuilder sb = new StringBuilder();
- final Formatter fmt = new Formatter(sb);
- sb.append(formatType());
- sb.append(permissionToString(USER_ACCESS));
- sb.append(permissionToString(GROUP_ACCESS));
- sb.append(permissionToString(WORLD_ACCESS));
- fmt.format(" %4d", Integer.valueOf(getHardLinkCount()));
- fmt.format(" %-8s %-8s", getUser(), getGroup());
- fmt.format(" %8d", Long.valueOf(getSize()));
- Calendar timestamp = getTimestamp();
- if (timestamp != null) {
- if (timezone != null) {
- final TimeZone newZone = TimeZone.getTimeZone(timezone);
- if (!newZone.equals(timestamp.getTimeZone())){
- final Date original = timestamp.getTime();
- final Calendar newStamp = Calendar.getInstance(newZone);
- newStamp.setTime(original);
- timestamp = newStamp;
+ try (final Formatter fmt = new Formatter(sb)) {
+ sb.append(formatType());
+ sb.append(permissionToString(USER_ACCESS));
+ sb.append(permissionToString(GROUP_ACCESS));
+ sb.append(permissionToString(WORLD_ACCESS));
+ fmt.format(" %4d", Integer.valueOf(getHardLinkCount()));
+ fmt.format(" %-8s %-8s", getUser(), getGroup());
+ fmt.format(" %8d", Long.valueOf(getSize()));
+ Calendar timestamp = getTimestamp();
+ if (timestamp != null) {
+ if (timezone != null) {
+ final TimeZone newZone = TimeZone.getTimeZone(timezone);
+ if (!newZone.equals(timestamp.getTimeZone())) {
+ final Date original = timestamp.getTime();
+ final Calendar newStamp = Calendar.getInstance(newZone);
+ newStamp.setTime(original);
+ timestamp = newStamp;
+ }
}
- }
- fmt.format(" %1$tY-%1$tm-%1$td", timestamp);
- // Only display time units if they are present
- if (timestamp.isSet(Calendar.HOUR_OF_DAY)) {
- fmt.format(" %1$tH", timestamp);
- if (timestamp.isSet(Calendar.MINUTE)) {
- fmt.format(":%1$tM", timestamp);
- if (timestamp.isSet(Calendar.SECOND)) {
- fmt.format(":%1$tS", timestamp);
- if (timestamp.isSet(Calendar.MILLISECOND)) {
- fmt.format(".%1$tL", timestamp);
+ fmt.format(" %1$tY-%1$tm-%1$td", timestamp);
+ // Only display time units if they are present
+ if (timestamp.isSet(Calendar.HOUR_OF_DAY)) {
+ fmt.format(" %1$tH", timestamp);
+ if (timestamp.isSet(Calendar.MINUTE)) {
+ fmt.format(":%1$tM", timestamp);
+ if (timestamp.isSet(Calendar.SECOND)) {
+ fmt.format(":%1$tS", timestamp);
+ if (timestamp.isSet(Calendar.MILLISECOND)) {
+ fmt.format(".%1$tL", timestamp);
+ }
}
}
+ fmt.format(" %1$tZ", timestamp);
}
- fmt.format(" %1$tZ", timestamp);
}
+ sb.append(' ');
+ sb.append(getName());
}
- sb.append(' ');
- sb.append(getName());
- fmt.close();
return sb.toString();
}
diff --git a/src/main/java/org/apache/commons/net/ftp/FTPListParseEngine.java b/src/main/java/org/apache/commons/net/ftp/FTPListParseEngine.java
index 6542ea2..a8e625e 100644
--- a/src/main/java/org/apache/commons/net/ftp/FTPListParseEngine.java
+++ b/src/main/java/org/apache/commons/net/ftp/FTPListParseEngine.java
@@ -136,17 +136,16 @@ public class FTPListParseEngine {
*/
private void readStream(final InputStream stream, final String encoding) throws IOException
{
- final BufferedReader reader = new BufferedReader(
- new InputStreamReader(stream, Charsets.toCharset(encoding)));
+ try (final BufferedReader reader = new BufferedReader(
+ new InputStreamReader(stream, Charsets.toCharset(encoding)))) {
- String line = this.parser.readNextEntry(reader);
+ String line = this.parser.readNextEntry(reader);
- while (line != null)
- {
- this.entries.add(line);
- line = this.parser.readNextEntry(reader);
+ while (line != null) {
+ this.entries.add(line);
+ line = this.parser.readNextEntry(reader);
+ }
}
- reader.close();
}
/**
diff --git a/src/main/java/org/apache/commons/net/nntp/NNTPClient.java b/src/main/java/org/apache/commons/net/nntp/NNTPClient.java
index 82504ef..036972e 100644
--- a/src/main/java/org/apache/commons/net/nntp/NNTPClient.java
+++ b/src/main/java/org/apache/commons/net/nntp/NNTPClient.java
@@ -244,13 +244,12 @@ public class NNTPClient extends NNTP
private NewsgroupInfo[] __readNewsgroupListing() throws IOException
{
- final BufferedReader reader = new DotTerminatedMessageReader(_reader_);
// Start of with a big vector because we may be reading a very large
// amount of groups.
final Vector<NewsgroupInfo> list = new Vector<>(2048);
String line;
- try {
+ try (final BufferedReader reader = new DotTerminatedMessageReader(_reader_)) {
while ((line = reader.readLine()) != null) {
final NewsgroupInfo tmp = __parseNewsgroupListEntry(line);
if (tmp != null) {
@@ -259,8 +258,6 @@ public class NNTPClient extends NNTP
throw new MalformedServerReplyException(line);
}
}
- } finally {
- reader.close();
}
int size;
if ((size = list.size()) < 1) {
@@ -769,12 +766,11 @@ public class NNTPClient extends NNTP
return null;
}
- final StringWriter help = new StringWriter();
- final BufferedReader reader = new DotTerminatedMessageReader(_reader_);
- Util.copyReader(reader, help);
- reader.close();
- help.close();
- return help.toString();
+ try (final StringWriter help = new StringWriter();
+ final BufferedReader reader = new DotTerminatedMessageReader(_reader_)) {
+ Util.copyReader(reader, help);
+ return help.toString();
+ }
}
/**
@@ -785,18 +781,18 @@ public class NNTPClient extends NNTP
*/
public String[] listOverviewFmt() throws IOException
{
- if (!NNTPReply.isPositiveCompletion(sendCommand("LIST", "OVERVIEW.FMT"))){
+ if (!NNTPReply.isPositiveCompletion(sendCommand("LIST", "OVERVIEW.FMT"))) {
return null;
}
- final BufferedReader reader = new DotTerminatedMessageReader(_reader_);
- String line;
- final ArrayList<String> list = new ArrayList<>();
- while((line=reader.readLine()) != null) {
- list.add(line);
+ try (final BufferedReader reader = new DotTerminatedMessageReader(_reader_)) {
+ String line;
+ final ArrayList<String> list = new ArrayList<>();
+ while ((line = reader.readLine()) != null) {
+ list.add(line);
+ }
+ return list.toArray(new String[list.size()]);
}
- reader.close();
- return list.toArray(new String[list.size()]);
}
/***
@@ -1258,22 +1254,18 @@ public class NNTPClient extends NNTP
public String[] listNewNews(final NewGroupsOrNewsQuery query)
throws IOException
{
- if (!NNTPReply.isPositiveCompletion(
- newnews(query.getNewsgroups(), query.getDate(), query.getTime(),
- query.isGMT(), query.getDistributions()))) {
+ if (!NNTPReply.isPositiveCompletion(newnews(query.getNewsgroups(), query.getDate(), query.getTime(),
+ query.isGMT(), query.getDistributions()))) {
return null;
}
final Vector<String> list = new Vector<>();
- final BufferedReader reader = new DotTerminatedMessageReader(_reader_);
+ try (final BufferedReader reader = new DotTerminatedMessageReader(_reader_)) {
- String line;
- try {
+ String line;
while ((line = reader.readLine()) != null) {
list.addElement(line);
}
- } finally {
- reader.close();
}
final int size = list.size();
diff --git a/src/main/java/org/apache/commons/net/smtp/SMTPClient.java b/src/main/java/org/apache/commons/net/smtp/SMTPClient.java
index bdf447f..4abf4a3 100644
--- a/src/main/java/org/apache/commons/net/smtp/SMTPClient.java
+++ b/src/main/java/org/apache/commons/net/smtp/SMTPClient.java
@@ -388,17 +388,15 @@ public class SMTPClient extends SMTP
***/
public boolean sendShortMessageData(final String message) throws IOException
{
- Writer writer;
+ try (Writer writer = sendMessageData()) {
- writer = sendMessageData();
+ if (writer == null) {
+ return false;
+ }
- if (writer == null) {
- return false;
+ writer.write(message);
}
- writer.write(message);
- writer.close();
-
return completePendingCommand();
}