(tomcat) branch 9.0.x updated: Replace various existing patterns with the URLConnection wrapper

[email protected]
Newsgroups gmane.comp.jakarta.tomcat.devel
Message-ID <178308919092.3747528.4598210720622821732@gitbox3-he-fi.apache.org>
This is an automated email from the ASF dual-hosted git repository.

rmaucher pushed a commit to branch 9.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git


The following commit(s) were added to refs/heads/9.0.x by this push:
     new 7368c8f0b5 Replace various existing patterns with the URLConnection wrapper
7368c8f0b5 is described below

commit 7368c8f0b5e4bf252ddcedb407d4e9a6160c21fa
Author: remm <[email protected]>
AuthorDate: Fri Jul 3 16:24:13 2026 +0200

    Replace various existing patterns with the URLConnection wrapper
---
 .../catalina/ssi/SSIServletExternalResolver.java   | 40 ++++------------
 .../org/apache/catalina/startup/ContextConfig.java | 31 +++---------
 .../apache/catalina/users/MemoryUserDatabase.java  | 56 +++++++++-------------
 java/org/apache/jasper/JspCompilationContext.java  | 27 ++++-------
 java/org/apache/jasper/compiler/Compiler.java      | 14 +++---
 java/org/apache/jasper/compiler/TldCache.java      | 11 ++---
 java/org/apache/tomcat/Jar.java                    |  1 +
 .../tomcat/util/file/ConfigurationSource.java      | 10 +---
 8 files changed, 61 insertions(+), 129 deletions(-)

diff --git a/java/org/apache/catalina/ssi/SSIServletExternalResolver.java b/java/org/apache/catalina/ssi/SSIServletExternalResolver.java
index 0347ed11a4..8ef107b166 100644
--- a/java/org/apache/catalina/ssi/SSIServletExternalResolver.java
+++ b/java/org/apache/catalina/ssi/SSIServletExternalResolver.java
@@ -36,8 +36,8 @@ import javax.servlet.http.HttpServletResponse;
 
 import org.apache.catalina.connector.Connector;
 import org.apache.catalina.connector.Request;
-import org.apache.tomcat.util.ExceptionUtils;
 import org.apache.tomcat.util.buf.B2CConverter;
+import org.apache.tomcat.util.buf.CloseableURLConnection;
 import org.apache.tomcat.util.buf.UDecoder;
 import org.apache.tomcat.util.http.Method;
 import org.apache.tomcat.util.http.RequestUtil;
@@ -608,23 +608,12 @@ public class SSIServletExternalResolver implements SSIExternalResolver {
      */
     @Override
     public long getFileLastModified(String path, boolean virtual) throws IOException {
-        long lastModified = 0;
-        URLConnection urlConnection = null;
-        try {
-            urlConnection = getURLConnection(path, virtual);
-            lastModified = urlConnection.getLastModified();
-        } catch (IOException ignore) {
+        try (CloseableURLConnection urlConnection = new CloseableURLConnection(getURLConnection(path, virtual))) {
+            return urlConnection.getLastModified();
+        } catch (IOException e) {
             // Ignore this. It will always fail for non-file based includes
-        } finally {
-            if (urlConnection != null) {
-                try {
-                    urlConnection.getInputStream().close();
-                } catch (Exception e) {
-                    ExceptionUtils.handleThrowable(e);
-                }
-            }
+            return 0L;
         }
-        return lastModified;
     }
 
 
@@ -640,23 +629,12 @@ public class SSIServletExternalResolver implements SSIExternalResolver {
      */
     @Override
     public long getFileSize(String path, boolean virtual) throws IOException {
-        long fileSize = -1;
-        URLConnection urlConnection = null;
-        try {
-            urlConnection = getURLConnection(path, virtual);
-            fileSize = urlConnection.getContentLengthLong();
-        } catch (IOException ignore) {
+        try (CloseableURLConnection urlConnection = new CloseableURLConnection(getURLConnection(path, virtual))) {
+            return urlConnection.getContentLengthLong();
+        } catch (IOException e) {
             // Ignore this. It will always fail for non-file based includes
-        } finally {
-            if (urlConnection != null) {
-                try {
-                    urlConnection.getInputStream().close();
-                } catch (Exception e) {
-                    ExceptionUtils.handleThrowable(e);
-                }
-            }
+            return -1L;
         }
-        return fileSize;
     }
 
 
diff --git a/java/org/apache/catalina/startup/ContextConfig.java b/java/org/apache/catalina/startup/ContextConfig.java
index cc59f1d43e..97942f9fad 100644
--- a/java/org/apache/catalina/startup/ContextConfig.java
+++ b/java/org/apache/catalina/startup/ContextConfig.java
@@ -84,6 +84,7 @@ import org.apache.tomcat.util.bcel.classfile.ClassParser;
 import org.apache.tomcat.util.bcel.classfile.ElementValue;
 import org.apache.tomcat.util.bcel.classfile.ElementValuePair;
 import org.apache.tomcat.util.bcel.classfile.JavaClass;
+import org.apache.tomcat.util.buf.CloseableURLConnection;
 import org.apache.tomcat.util.buf.UriUtil;
 import org.apache.tomcat.util.descriptor.InputSourceUtil;
 import org.apache.tomcat.util.descriptor.XmlErrorHandler;
@@ -1704,42 +1705,24 @@ public class ContextConfig implements LifecycleListener {
         long hostTimeStamp = 0;
 
         if (globalWebXml != null) {
-            URLConnection uc = null;
             try {
                 URI uri = new URI(globalWebXml.getSystemId());
-                URL url = uri.toURL();
-                uc = url.openConnection();
-                globalTimeStamp = uc.getLastModified();
+                try (CloseableURLConnection uc = new CloseableURLConnection(uri.toURL())) {
+                    globalTimeStamp = uc.getLastModified();
+                }
             } catch (IOException | URISyntaxException | IllegalArgumentException e) {
                 globalTimeStamp = -1;
-            } finally {
-                if (uc != null) {
-                    try {
-                        uc.getInputStream().close();
-                    } catch (Exception e) {
-                        ExceptionUtils.handleThrowable(e);
-                    }
-                }
             }
         }
 
         if (hostWebXml != null) {
-            URLConnection uc = null;
             try {
                 URI uri = new URI(hostWebXml.getSystemId());
-                URL url = uri.toURL();
-                uc = url.openConnection();
-                hostTimeStamp = uc.getLastModified();
+                try (CloseableURLConnection uc = new CloseableURLConnection(uri.toURL())) {
+                    hostTimeStamp = uc.getLastModified();
+                }
             } catch (IOException | URISyntaxException | IllegalArgumentException e) {
                 hostTimeStamp = -1;
-            } finally {
-                if (uc != null) {
-                    try {
-                        uc.getInputStream().close();
-                    } catch (Exception e) {
-                        ExceptionUtils.handleThrowable(e);
-                    }
-                }
             }
         }
 
diff --git a/java/org/apache/catalina/users/MemoryUserDatabase.java b/java/org/apache/catalina/users/MemoryUserDatabase.java
index 4ae43c9c83..740f17458a 100644
--- a/java/org/apache/catalina/users/MemoryUserDatabase.java
+++ b/java/org/apache/catalina/users/MemoryUserDatabase.java
@@ -23,8 +23,6 @@ import java.io.IOException;
 import java.io.OutputStreamWriter;
 import java.io.PrintWriter;
 import java.net.URI;
-import java.net.URL;
-import java.net.URLConnection;
 import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
 import java.util.Iterator;
@@ -40,6 +38,7 @@ import org.apache.catalina.User;
 import org.apache.catalina.UserDatabase;
 import org.apache.juli.logging.Log;
 import org.apache.juli.logging.LogFactory;
+import org.apache.tomcat.util.buf.CloseableURLConnection;
 import org.apache.tomcat.util.digester.AbstractObjectCreationFactory;
 import org.apache.tomcat.util.digester.Digester;
 import org.apache.tomcat.util.file.ConfigFileLoader;
@@ -640,43 +639,34 @@ public class MemoryUserDatabase implements UserDatabase {
         }
 
         URI uri = ConfigFileLoader.getSource().getURI(getPathname());
-        URLConnection uConn = null;
         try {
-            URL url = uri.toURL();
-            uConn = url.openConnection();
-
-            if (this.lastModified != uConn.getLastModified()) {
-                writeLock.lock();
-                try {
-                    long detectedLastModified = uConn.getLastModified();
-                    // Last modified as a resolution of 1s. Ensure that a write
-                    // to the file is not in progress by ensuring that the last
-                    // modified time is at least 2 seconds ago.
-                    if (this.lastModified != detectedLastModified &&
-                            detectedLastModified + 2000 < System.currentTimeMillis()) {
-                        log.info(sm.getString("memoryUserDatabase.reload", id, uri));
-                        open();
+            try (CloseableURLConnection uConn = new CloseableURLConnection(uri.toURL())) {
+                if (this.lastModified != uConn.getLastModified()) {
+                    writeLock.lock();
+                    try {
+                        long detectedLastModified = uConn.getLastModified();
+                        // Last modified as a resolution of 1s. Ensure that a write
+                        // to the file is not in progress by ensuring that the last
+                        // modified time is at least 2 seconds ago.
+                        if (this.lastModified != detectedLastModified &&
+                                detectedLastModified + 2000 < System.currentTimeMillis()) {
+                            log.info(sm.getString("memoryUserDatabase.reload", id, uri));
+                            open();
+                        }
+                    } finally {
+                        writeLock.unlock();
                     }
-                } finally {
-                    writeLock.unlock();
                 }
+            } catch (FileNotFoundException fnfe) {
+                // The file doesn't exist.
+                // This has been logged above. No need to log again.
+                // Set the last modified time to avoid repeated log messages
+                this.lastModified = 0;
+            } catch (IOException ioe) {
+                log.warn(sm.getString("memoryUserDatabase.fileClose", pathname), ioe);
             }
         } catch (Exception e) {
             log.error(sm.getString("memoryUserDatabase.reloadError", id, uri), e);
-        } finally {
-            if (uConn != null) {
-                try {
-                    // Can't close a uConn directly. Have to do it like this.
-                    uConn.getInputStream().close();
-                } catch (FileNotFoundException fnfe) {
-                    // The file doesn't exist.
-                    // This has been logged above. No need to log again.
-                    // Set the last modified time to avoid repeated log messages
-                    this.lastModified = 0;
-                } catch (IOException ioe) {
-                    log.warn(sm.getString("memoryUserDatabase.fileClose", pathname), ioe);
-                }
-            }
         }
     }
 
diff --git a/java/org/apache/jasper/JspCompilationContext.java b/java/org/apache/jasper/JspCompilationContext.java
index c4bf6bc5a2..b93bfa412a 100644
--- a/java/org/apache/jasper/JspCompilationContext.java
+++ b/java/org/apache/jasper/JspCompilationContext.java
@@ -40,6 +40,7 @@ import org.apache.jasper.servlet.JspServletWrapper;
 import org.apache.juli.logging.Log;
 import org.apache.juli.logging.LogFactory;
 import org.apache.tomcat.Jar;
+import org.apache.tomcat.util.buf.CloseableURLConnection;
 import org.apache.tomcat.util.descriptor.tld.TldResourcePath;
 
 /**
@@ -448,7 +449,6 @@ public class JspCompilationContext {
      */
     public Long getLastModified(String resource, Jar tagJar) {
         long result = -1;
-        URLConnection uc = null;
         try {
             if (tagJar != null) {
                 if (resource.startsWith("/")) {
@@ -461,32 +461,23 @@ public class JspCompilationContext {
                     incrementRemoved();
                     return Long.valueOf(result);
                 }
-                uc = jspUrl.openConnection();
-                if (uc instanceof JarURLConnection) {
-                    JarEntry jarEntry = ((JarURLConnection) uc).getJarEntry();
-                    if (jarEntry != null) {
-                        result = jarEntry.getTime();
+                try (CloseableURLConnection uc = new CloseableURLConnection(jspUrl)) {
+                    if (uc.getConnection() instanceof JarURLConnection) {
+                        JarEntry jarEntry = ((JarURLConnection) uc.getConnection()).getJarEntry();
+                        if (jarEntry != null) {
+                            result = jarEntry.getTime();
+                        } else {
+                            result = uc.getLastModified();
+                        }
                     } else {
                         result = uc.getLastModified();
                     }
-                } else {
-                    result = uc.getLastModified();
                 }
             }
         } catch (IOException ioe) {
             if (log.isDebugEnabled()) {
                 log.debug(Localizer.getMessage("jsp.error.lastModified", getJspFile()), ioe);
             }
-        } finally {
-            if (uc != null) {
-                try {
-                    uc.getInputStream().close();
-                } catch (Exception e) {
-                    if (log.isDebugEnabled()) {
-                        log.debug(Localizer.getMessage("jsp.error.lastModified", getJspFile()), e);
-                    }
-                }
-            }
         }
         return Long.valueOf(result);
     }
diff --git a/java/org/apache/jasper/compiler/Compiler.java b/java/org/apache/jasper/compiler/Compiler.java
index 3c1ab2923a..e15c526d72 100644
--- a/java/org/apache/jasper/compiler/Compiler.java
+++ b/java/org/apache/jasper/compiler/Compiler.java
@@ -25,7 +25,6 @@ import java.io.UnsupportedEncodingException;
 import java.net.JarURLConnection;
 import java.net.URI;
 import java.net.URL;
-import java.net.URLConnection;
 import java.util.Map;
 import java.util.Map.Entry;
 
@@ -37,6 +36,7 @@ import org.apache.jasper.servlet.JspServletWrapper;
 import org.apache.juli.logging.Log;
 import org.apache.juli.logging.LogFactory;
 import org.apache.tomcat.Jar;
+import org.apache.tomcat.util.buf.CloseableURLConnection;
 import org.apache.tomcat.util.descriptor.tld.TldResourcePath;
 import org.apache.tomcat.util.scan.JarFactory;
 
@@ -557,13 +557,13 @@ public abstract class Compiler {
                     if (includeUrl == null) {
                         return true;
                     }
-                    URLConnection iuc = includeUrl.openConnection();
-                    if (iuc instanceof JarURLConnection) {
-                        includeLastModified = ((JarURLConnection) iuc).getJarEntry().getTime();
-                    } else {
-                        includeLastModified = iuc.getLastModified();
+                    try (CloseableURLConnection iuc = new CloseableURLConnection(includeUrl)) {
+                        if (iuc.getConnection() instanceof JarURLConnection) {
+                            includeLastModified = ((JarURLConnection) iuc.getConnection()).getJarEntry().getTime();
+                        } else {
+                            includeLastModified = iuc.getLastModified();
+                        }
                     }
-                    iuc.getInputStream().close();
                 }
 
                 if (includeLastModified != include.getValue().longValue()) {
diff --git a/java/org/apache/jasper/compiler/TldCache.java b/java/org/apache/jasper/compiler/TldCache.java
index e0a8080c34..790d3ef4a5 100644
--- a/java/org/apache/jasper/compiler/TldCache.java
+++ b/java/org/apache/jasper/compiler/TldCache.java
@@ -18,7 +18,6 @@ package org.apache.jasper.compiler;
 
 import java.io.IOException;
 import java.net.URL;
-import java.net.URLConnection;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Map.Entry;
@@ -28,6 +27,7 @@ import javax.servlet.ServletContext;
 import org.apache.jasper.Constants;
 import org.apache.jasper.JasperException;
 import org.apache.tomcat.Jar;
+import org.apache.tomcat.util.buf.CloseableURLConnection;
 import org.apache.tomcat.util.descriptor.tld.TaglibXml;
 import org.apache.tomcat.util.descriptor.tld.TldParser;
 import org.apache.tomcat.util.descriptor.tld.TldResourcePath;
@@ -168,13 +168,8 @@ public class TldCache {
                 // webappPath will be null for JARs containing TLDs that are on
                 // the class path but not part of the web application
                 URL url = servletContext.getResource(tldResourcePath.getWebappPath());
-                URLConnection conn = url.openConnection();
-                result[0] = conn.getLastModified();
-                if ("file".equals(url.getProtocol())) {
-                    // Reading the last modified time opens an input stream so we
-                    // need to make sure it is closed again otherwise the TLD file
-                    // will be locked until GC runs.
-                    conn.getInputStream().close();
+                try (CloseableURLConnection conn = new CloseableURLConnection(url)) {
+                    result[0] = conn.getLastModified();
                 }
             }
             try (Jar jar = tldResourcePath.openJar()) {
diff --git a/java/org/apache/tomcat/Jar.java b/java/org/apache/tomcat/Jar.java
index 4fbca5db16..0afa18d1c2 100644
--- a/java/org/apache/tomcat/Jar.java
+++ b/java/org/apache/tomcat/Jar.java
@@ -62,6 +62,7 @@ public interface Jar extends AutoCloseable {
         URL jarUrl = getJarFileURL();
         URLConnection urlConn = null;
         try {
+            // Note: this cannot use CloseableURLConnection due to Tomcat JAR packaging
             urlConn = jarUrl.openConnection();
             return urlConn.getLastModified();
         } finally {
diff --git a/java/org/apache/tomcat/util/file/ConfigurationSource.java b/java/org/apache/tomcat/util/file/ConfigurationSource.java
index 04f778cc4e..fbd4518d61 100644
--- a/java/org/apache/tomcat/util/file/ConfigurationSource.java
+++ b/java/org/apache/tomcat/util/file/ConfigurationSource.java
@@ -24,8 +24,8 @@ import java.io.InputStream;
 import java.net.MalformedURLException;
 import java.net.URI;
 import java.net.URL;
-import java.net.URLConnection;
 
+import org.apache.tomcat.util.buf.CloseableURLConnection;
 import org.apache.tomcat.util.buf.UriUtil;
 
 /**
@@ -128,14 +128,8 @@ public interface ConfigurationSource {
      * @throws IOException if an I/O error occurs while fetching the last modified time
      */
         public long getLastModified() throws MalformedURLException, IOException {
-            URLConnection connection = null;
-            try {
-                connection = uri.toURL().openConnection();
+            try (CloseableURLConnection connection = new CloseableURLConnection(uri.toURL())) {
                 return connection.getLastModified();
-            } finally {
-                if (connection != null) {
-                    connection.getInputStream().close();
-                }
             }
         }
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.