diff --git a/WHATSNEW b/WHATSNEW index 5894c07c7..0f052c90b 100644 --- a/WHATSNEW +++ b/WHATSNEW @@ -27,6 +27,11 @@ Fixed bugs: cannot determine the local hostname. Bugzilla Report 56593 + * URLResource#getLastModified tried to access the connection to the + URL without making sure it was established, potentially leading to + a NullPointerException when using FTP. + Bugzilla Report 56873 + Other changes: -------------- diff --git a/src/main/org/apache/tools/ant/types/resources/URLResource.java b/src/main/org/apache/tools/ant/types/resources/URLResource.java index a1439080a..70d6c9baa 100644 --- a/src/main/org/apache/tools/ant/types/resources/URLResource.java +++ b/src/main/org/apache/tools/ant/types/resources/URLResource.java @@ -265,8 +265,11 @@ public class URLResource extends Resource implements URLProvider { if (!isExists(false)) { return UNKNOWN_DATETIME; } - // isExists has already opened the connection - return conn.getLastModified(); + return withConnection(new ConnectionUser() { + public long useConnection(URLConnection c) { + return conn.getLastModified(); + } + }, UNKNOWN_DATETIME); } /** @@ -291,14 +294,11 @@ public class URLResource extends Resource implements URLProvider { if (!isExists(false)) { return 0L; } - try { - connect(); - long contentlength = conn.getContentLength(); - close(); - return contentlength; - } catch (IOException e) { - return UNKNOWN_SIZE; - } + return withConnection(new ConnectionUser() { + public long useConnection(URLConnection c) { + return conn.getContentLength(); + } + }, UNKNOWN_SIZE); } /** @@ -431,4 +431,24 @@ public class URLResource extends Resource implements URLProvider { } } + private interface ConnectionUser { + long useConnection(URLConnection c); + } + + private long withConnection(ConnectionUser u, long defaultValue) { + try { + if (conn != null) { + return u.useConnection(conn); + } else { + try { + connect(); + return u.useConnection(conn); + } finally { + close(); + } + } + } catch (IOException ex) { + return defaultValue; + } + } }