You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@tomcat.apache.org by ma...@apache.org on 2023/01/24 11:17:19 UTC

[tomcat] branch 9.0.x updated (b922d9c780 -> 3dab9abcee)

This is an automated email from the ASF dual-hosted git repository.

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


    from b922d9c780 Add initial Eclipse format configurations
     new 636e19f2a3 Code cleanup (format). No functional change.
     new 3c8ee6e86b Code cleanup (format). No functional change.
     new fe204bd18d Code cleanup (format). No functional change.
     new 74c9ebf14f Code cleanup (format). No functional change.
     new 91ca309136 Code cleanup (format). No functional change.
     new 2d6f8fc2c0 Code cleanup (format). No functional change.
     new 3dab9abcee Review all uses of LinkedHashMap#removeEldestEntry

The 7 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../catalina/authenticator/AuthenticatorBase.java  | 456 +++++------
 .../catalina/authenticator/BasicAuthenticator.java |  87 +--
 .../apache/catalina/authenticator/Constants.java   |  26 +-
 .../authenticator/DigestAuthenticator.java         | 138 ++--
 .../catalina/authenticator/FormAuthenticator.java  | 144 ++--
 .../authenticator/NonLoginAuthenticator.java       |  68 +-
 .../catalina/authenticator/SSLAuthenticator.java   |  44 +-
 .../catalina/authenticator/SavedRequest.java       |  19 +-
 .../catalina/authenticator/SingleSignOn.java       | 257 +++----
 .../catalina/authenticator/SingleSignOnEntry.java  |  82 +-
 .../authenticator/SingleSignOnSessionKey.java      |  17 +-
 .../authenticator/SpnegoAuthenticator.java         | 105 +--
 .../catalina/filters/AddDefaultCharsetFilter.java  |  34 +-
 java/org/apache/catalina/filters/Constants.java    |  37 +-
 java/org/apache/catalina/filters/CorsFilter.java   | 550 ++++++-------
 .../catalina/filters/CsrfPreventionFilter.java     | 129 ++--
 .../catalina/filters/CsrfPreventionFilterBase.java |  34 +-
 .../org/apache/catalina/filters/ExpiresFilter.java | 438 +++++------
 .../catalina/filters/FailedRequestFilter.java      |  25 +-
 java/org/apache/catalina/filters/FilterBase.java   |  30 +-
 .../catalina/filters/HttpHeaderSecurityFilter.java |  15 +-
 .../apache/catalina/filters/RemoteAddrFilter.java  |  17 +-
 .../apache/catalina/filters/RemoteCIDRFilter.java  |  27 +-
 .../apache/catalina/filters/RemoteHostFilter.java  |  16 +-
 .../apache/catalina/filters/RemoteIpFilter.java    | 263 ++++---
 .../catalina/filters/RequestDumperFilter.java      |  69 +-
 .../org/apache/catalina/filters/RequestFilter.java |  91 +--
 .../catalina/filters/RestCsrfPreventionFilter.java |  71 +-
 .../catalina/filters/SessionInitializerFilter.java |  23 +-
 .../filters/SetCharacterEncodingFilter.java        |  88 ++-
 .../apache/catalina/filters/WebdavFixFilter.java   |  58 +-
 .../catalina/realm/AuthenticatedUserRealm.java     |  10 +-
 java/org/apache/catalina/realm/CombinedRealm.java  | 155 ++--
 .../org/apache/catalina/realm/DataSourceRealm.java | 102 ++-
 .../realm/DigestCredentialHandlerBase.java         | 147 ++--
 .../apache/catalina/realm/GenericPrincipal.java    |  99 ++-
 .../apache/catalina/realm/JAASCallbackHandler.java | 110 ++-
 .../catalina/realm/JAASMemoryLoginModule.java      | 116 ++-
 java/org/apache/catalina/realm/JAASRealm.java      | 338 ++++----
 java/org/apache/catalina/realm/JDBCRealm.java      | 163 ++--
 java/org/apache/catalina/realm/JNDIRealm.java      | 854 +++++++++------------
 java/org/apache/catalina/realm/LockOutRealm.java   | 165 ++--
 java/org/apache/catalina/realm/MemoryRealm.java    |  52 +-
 java/org/apache/catalina/realm/MemoryRuleSet.java  |  31 +-
 .../realm/MessageDigestCredentialHandler.java      |  34 +-
 .../catalina/realm/NestedCredentialHandler.java    |   7 +-
 java/org/apache/catalina/realm/NullRealm.java      |   5 +-
 java/org/apache/catalina/realm/RealmBase.java      | 504 ++++++------
 .../apache/catalina/realm/UserDatabaseRealm.java   |  52 +-
 .../catalina/realm/X509SubjectDnRetriever.java     |   3 +-
 .../catalina/realm/X509UsernameRetriever.java      |   4 +-
 java/org/apache/catalina/tribes/util/Arrays.java   |  54 +-
 .../catalina/tribes/util/ExceptionUtils.java       |   4 +-
 .../catalina/tribes/util/ExecutorFactory.java      |  43 +-
 java/org/apache/catalina/tribes/util/Logs.java     |   1 +
 .../apache/catalina/tribes/util/StringManager.java | 111 ++-
 .../catalina/tribes/util/TcclThreadFactory.java    |  11 +-
 .../apache/catalina/tribes/util/UUIDGenerator.java |  35 +-
 java/org/apache/juli/AsyncFileHandler.java         |  54 +-
 java/org/apache/juli/ClassLoaderLogManager.java    | 114 ++-
 java/org/apache/juli/DateFormatCache.java          |  59 +-
 java/org/apache/juli/FileHandler.java              | 111 ++-
 java/org/apache/juli/JdkLoggerFormatter.java       |  80 +-
 java/org/apache/juli/OneLineFormatter.java         |  54 +-
 java/org/apache/juli/VerbatimFormatter.java        |   8 +-
 java/org/apache/juli/WebappProperties.java         |  38 +-
 java/org/apache/tomcat/util/res/StringManager.java | 122 ++-
 67 files changed, 3115 insertions(+), 4193 deletions(-)


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


[tomcat] 03/07: Code cleanup (format). No functional change.

Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit fe204bd18dc2babcad0f6ea0683f1a09e8a0c2bb
Author: Mark Thomas <ma...@apache.org>
AuthorDate: Tue Jan 24 11:14:34 2023 +0000

    Code cleanup (format). No functional change.
---
 .../catalina/realm/AuthenticatedUserRealm.java     |  10 +-
 java/org/apache/catalina/realm/CombinedRealm.java  | 155 ++--
 .../org/apache/catalina/realm/DataSourceRealm.java | 102 ++-
 .../realm/DigestCredentialHandlerBase.java         | 147 ++--
 .../apache/catalina/realm/GenericPrincipal.java    |  99 ++-
 .../apache/catalina/realm/JAASCallbackHandler.java | 110 ++-
 .../catalina/realm/JAASMemoryLoginModule.java      | 116 ++-
 java/org/apache/catalina/realm/JAASRealm.java      | 338 ++++----
 java/org/apache/catalina/realm/JDBCRealm.java      | 163 ++--
 java/org/apache/catalina/realm/JNDIRealm.java      | 854 +++++++++------------
 java/org/apache/catalina/realm/LockOutRealm.java   | 158 ++--
 java/org/apache/catalina/realm/MemoryRealm.java    |  52 +-
 java/org/apache/catalina/realm/MemoryRuleSet.java  |  31 +-
 .../realm/MessageDigestCredentialHandler.java      |  34 +-
 .../catalina/realm/NestedCredentialHandler.java    |   7 +-
 java/org/apache/catalina/realm/NullRealm.java      |   5 +-
 java/org/apache/catalina/realm/RealmBase.java      | 504 ++++++------
 .../apache/catalina/realm/UserDatabaseRealm.java   |  52 +-
 .../catalina/realm/X509SubjectDnRetriever.java     |   3 +-
 .../catalina/realm/X509UsernameRetriever.java      |   4 +-
 20 files changed, 1279 insertions(+), 1665 deletions(-)

diff --git a/java/org/apache/catalina/realm/AuthenticatedUserRealm.java b/java/org/apache/catalina/realm/AuthenticatedUserRealm.java
index 96abe6ce05..d10f041976 100644
--- a/java/org/apache/catalina/realm/AuthenticatedUserRealm.java
+++ b/java/org/apache/catalina/realm/AuthenticatedUserRealm.java
@@ -21,13 +21,11 @@ import java.security.Principal;
 /**
  * This Realm is intended for use with Authenticator implementations
  * ({@link org.apache.catalina.authenticator.SSLAuthenticator},
- * {@link org.apache.catalina.authenticator.SpnegoAuthenticator}) that
- * authenticate the user as well as obtain the user credentials. An
- * authenticated Principal is always created from the user name presented to
- * without further validation.
+ * {@link org.apache.catalina.authenticator.SpnegoAuthenticator}) that authenticate the user as well as obtain the user
+ * credentials. An authenticated Principal is always created from the user name presented to without further validation.
  * <p>
- * <strong>Note:</strong> It is unsafe to use this Realm with Authenticator
- * implementations that do not validate the provided credentials.
+ * <strong>Note:</strong> It is unsafe to use this Realm with Authenticator implementations that do not validate the
+ * provided credentials.
  */
 public class AuthenticatedUserRealm extends RealmBase {
 
diff --git a/java/org/apache/catalina/realm/CombinedRealm.java b/java/org/apache/catalina/realm/CombinedRealm.java
index 8c880e6396..807e5c7f34 100644
--- a/java/org/apache/catalina/realm/CombinedRealm.java
+++ b/java/org/apache/catalina/realm/CombinedRealm.java
@@ -38,10 +38,9 @@ import org.ietf.jgss.GSSException;
 import org.ietf.jgss.GSSName;
 
 /**
- * Realm implementation that contains one or more realms. Authentication is
- * attempted for each realm in the order they were configured. If any realm
- * authenticates the user then the authentication succeeds. When combining
- * realms usernames should be unique across all combined realms.
+ * Realm implementation that contains one or more realms. Authentication is attempted for each realm in the order they
+ * were configured. If any realm authenticates the user then the authentication succeeds. When combining realms
+ * usernames should be unique across all combined realms.
  */
 public class CombinedRealm extends RealmBase {
 
@@ -53,17 +52,15 @@ public class CombinedRealm extends RealmBase {
     protected final List<Realm> realms = new ArrayList<>();
 
     /**
-     * Add a realm to the list of realms that will be used to authenticate
-     * users.
+     * Add a realm to the list of realms that will be used to authenticate users.
+     *
      * @param theRealm realm which should be wrapped by the combined realm
      */
     public void addRealm(Realm theRealm) {
         realms.add(theRealm);
 
         if (log.isDebugEnabled()) {
-            sm.getString("combinedRealm.addRealm",
-                    theRealm.getClass().getName(),
-                    Integer.toString(realms.size()));
+            sm.getString("combinedRealm.addRealm", theRealm.getClass().getName(), Integer.toString(realms.size()));
         }
     }
 
@@ -75,8 +72,7 @@ public class CombinedRealm extends RealmBase {
         ObjectName[] result = new ObjectName[realms.size()];
         for (Realm realm : realms) {
             if (realm instanceof RealmBase) {
-                result[realms.indexOf(realm)] =
-                    ((RealmBase) realm).getObjectName();
+                result[realms.indexOf(realm)] = ((RealmBase) realm).getObjectName();
             }
         }
         return result;
@@ -90,42 +86,34 @@ public class CombinedRealm extends RealmBase {
     }
 
     /**
-     * Return the Principal associated with the specified username, which
-     * matches the digest calculated using the given parameters using the
-     * method described in RFC 2069; otherwise return <code>null</code>.
+     * Return the Principal associated with the specified username, which matches the digest calculated using the given
+     * parameters using the method described in RFC 2069; otherwise return <code>null</code>.
      *
-     * @param username Username of the Principal to look up
+     * @param username     Username of the Principal to look up
      * @param clientDigest Digest which has been submitted by the client
-     * @param nonce Unique (or supposedly unique) token which has been used
-     * for this request
-     * @param realmName Realm name
-     * @param md5a2 Second MD5 digest used to calculate the digest :
-     * MD5(Method + ":" + uri)
+     * @param nonce        Unique (or supposedly unique) token which has been used for this request
+     * @param realmName    Realm name
+     * @param md5a2        Second MD5 digest used to calculate the digest : MD5(Method + ":" + uri)
      */
     @Override
-    public Principal authenticate(String username, String clientDigest,
-            String nonce, String nc, String cnonce, String qop,
-            String realmName, String md5a2) {
+    public Principal authenticate(String username, String clientDigest, String nonce, String nc, String cnonce,
+            String qop, String realmName, String md5a2) {
         Principal authenticatedUser = null;
 
         for (Realm realm : realms) {
             if (log.isDebugEnabled()) {
-                log.debug(sm.getString("combinedRealm.authStart", username,
-                        realm.getClass().getName()));
+                log.debug(sm.getString("combinedRealm.authStart", username, realm.getClass().getName()));
             }
 
-            authenticatedUser = realm.authenticate(username, clientDigest, nonce,
-                    nc, cnonce, qop, realmName, md5a2);
+            authenticatedUser = realm.authenticate(username, clientDigest, nonce, nc, cnonce, qop, realmName, md5a2);
 
             if (authenticatedUser == null) {
                 if (log.isDebugEnabled()) {
-                    log.debug(sm.getString("combinedRealm.authFail", username,
-                            realm.getClass().getName()));
+                    log.debug(sm.getString("combinedRealm.authFail", username, realm.getClass().getName()));
                 }
             } else {
                 if (log.isDebugEnabled()) {
-                    log.debug(sm.getString("combinedRealm.authSuccess",
-                            username, realm.getClass().getName()));
+                    log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getClass().getName()));
                 }
                 break;
             }
@@ -135,8 +123,7 @@ public class CombinedRealm extends RealmBase {
 
 
     /**
-     * Return the Principal associated with the specified user name otherwise
-     * return <code>null</code>.
+     * Return the Principal associated with the specified user name otherwise return <code>null</code>.
      *
      * @param username User name of the Principal to look up
      */
@@ -146,21 +133,18 @@ public class CombinedRealm extends RealmBase {
 
         for (Realm realm : realms) {
             if (log.isDebugEnabled()) {
-                log.debug(sm.getString("combinedRealm.authStart", username,
-                        realm.getClass().getName()));
+                log.debug(sm.getString("combinedRealm.authStart", username, realm.getClass().getName()));
             }
 
             authenticatedUser = realm.authenticate(username);
 
             if (authenticatedUser == null) {
                 if (log.isDebugEnabled()) {
-                    log.debug(sm.getString("combinedRealm.authFail", username,
-                            realm.getClass().getName()));
+                    log.debug(sm.getString("combinedRealm.authFail", username, realm.getClass().getName()));
                 }
             } else {
                 if (log.isDebugEnabled()) {
-                    log.debug(sm.getString("combinedRealm.authSuccess",
-                            username, realm.getClass().getName()));
+                    log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getClass().getName()));
                 }
                 break;
             }
@@ -170,12 +154,11 @@ public class CombinedRealm extends RealmBase {
 
 
     /**
-     * Return the Principal associated with the specified username and
-     * credentials, if there is one; otherwise return <code>null</code>.
+     * Return the Principal associated with the specified username and credentials, if there is one; otherwise return
+     * <code>null</code>.
      *
-     * @param username Username of the Principal to look up
-     * @param credentials Password or other credentials to use in
-     *  authenticating this username
+     * @param username    Username of the Principal to look up
+     * @param credentials Password or other credentials to use in authenticating this username
      */
     @Override
     public Principal authenticate(String username, String credentials) {
@@ -183,21 +166,18 @@ public class CombinedRealm extends RealmBase {
 
         for (Realm realm : realms) {
             if (log.isDebugEnabled()) {
-                log.debug(sm.getString("combinedRealm.authStart", username,
-                        realm.getClass().getName()));
+                log.debug(sm.getString("combinedRealm.authStart", username, realm.getClass().getName()));
             }
 
             authenticatedUser = realm.authenticate(username, credentials);
 
             if (authenticatedUser == null) {
                 if (log.isDebugEnabled()) {
-                    log.debug(sm.getString("combinedRealm.authFail", username,
-                            realm.getClass().getName()));
+                    log.debug(sm.getString("combinedRealm.authFail", username, realm.getClass().getName()));
                 }
             } else {
                 if (log.isDebugEnabled()) {
-                    log.debug(sm.getString("combinedRealm.authSuccess",
-                            username, realm.getClass().getName()));
+                    log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getClass().getName()));
                 }
                 break;
             }
@@ -213,11 +193,10 @@ public class CombinedRealm extends RealmBase {
      */
     @Override
     public void setContainer(Container container) {
-        for(Realm realm : realms) {
+        for (Realm realm : realms) {
             // Set the realmPath for JMX naming
             if (realm instanceof RealmBase) {
-                ((RealmBase) realm).setRealmPath(
-                        getRealmPath() + "/realm" + realms.indexOf(realm));
+                ((RealmBase) realm).setRealmPath(getRealmPath() + "/realm" + realms.indexOf(realm));
             }
 
             // Set the container for sub-realms. Mainly so logging works.
@@ -228,12 +207,11 @@ public class CombinedRealm extends RealmBase {
 
 
     /**
-     * Prepare for the beginning of active use of the public methods of this
-     * component and implement the requirements of
+     * Prepare for the beginning of active use of the public methods of this component and implement the requirements of
      * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
      *
-     * @exception LifecycleException if this component detects a fatal error
-     *  that prevents this component from being used
+     * @exception LifecycleException if this component detects a fatal error that prevents this component from being
+     *                                   used
      */
     @Override
     protected void startInternal() throws LifecycleException {
@@ -248,8 +226,7 @@ public class CombinedRealm extends RealmBase {
                 } catch (LifecycleException e) {
                     // If realm doesn't start can't authenticate against it
                     iter.remove();
-                    log.error(sm.getString("combinedRealm.realmStartFail",
-                            realm.getClass().getName()), e);
+                    log.error(sm.getString("combinedRealm.realmStartFail", realm.getClass().getName()), e);
                 }
             }
         }
@@ -264,14 +241,12 @@ public class CombinedRealm extends RealmBase {
 
 
     /**
-     * Gracefully terminate the active use of the public methods of this
-     * component and implement the requirements of
+     * Gracefully terminate the active use of the public methods of this component and implement the requirements of
      * {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
      *
-     * @exception LifecycleException if this component detects a fatal error
-     *  that needs to be reported
+     * @exception LifecycleException if this component detects a fatal error that needs to be reported
      */
-     @Override
+    @Override
     protected void stopInternal() throws LifecycleException {
         // Stop this realm, then the sub-realms (reverse order to start)
         super.stopInternal();
@@ -309,37 +284,34 @@ public class CombinedRealm extends RealmBase {
     }
 
     /**
-     * Return the Principal associated with the specified chain of X509
-     * client certificates.  If there is none, return <code>null</code>.
+     * Return the Principal associated with the specified chain of X509 client certificates. If there is none, return
+     * <code>null</code>.
      *
-     * @param certs Array of client certificates, with the first one in
-     *  the array being the certificate of the client itself.
+     * @param certs Array of client certificates, with the first one in the array being the certificate of the client
+     *                  itself.
      */
     @Override
     public Principal authenticate(X509Certificate[] certs) {
         Principal authenticatedUser = null;
         String username = null;
-        if (certs != null && certs.length >0) {
+        if (certs != null && certs.length > 0) {
             username = certs[0].getSubjectX500Principal().toString();
         }
 
         for (Realm realm : realms) {
             if (log.isDebugEnabled()) {
-                log.debug(sm.getString("combinedRealm.authStart", username,
-                        realm.getClass().getName()));
+                log.debug(sm.getString("combinedRealm.authStart", username, realm.getClass().getName()));
             }
 
             authenticatedUser = realm.authenticate(certs);
 
             if (authenticatedUser == null) {
                 if (log.isDebugEnabled()) {
-                    log.debug(sm.getString("combinedRealm.authFail", username,
-                            realm.getClass().getName()));
+                    log.debug(sm.getString("combinedRealm.authFail", username, realm.getClass().getName()));
                 }
             } else {
                 if (log.isDebugEnabled()) {
-                    log.debug(sm.getString("combinedRealm.authSuccess",
-                            username, realm.getClass().getName()));
+                    log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getClass().getName()));
                 }
                 break;
             }
@@ -364,21 +336,18 @@ public class CombinedRealm extends RealmBase {
 
             for (Realm realm : realms) {
                 if (log.isDebugEnabled()) {
-                    log.debug(sm.getString("combinedRealm.authStart",
-                            gssName, realm.getClass().getName()));
+                    log.debug(sm.getString("combinedRealm.authStart", gssName, realm.getClass().getName()));
                 }
 
                 authenticatedUser = realm.authenticate(gssContext, storeCred);
 
                 if (authenticatedUser == null) {
                     if (log.isDebugEnabled()) {
-                        log.debug(sm.getString("combinedRealm.authFail",
-                                gssName, realm.getClass().getName()));
+                        log.debug(sm.getString("combinedRealm.authFail", gssName, realm.getClass().getName()));
                     }
                 } else {
                     if (log.isDebugEnabled()) {
-                        log.debug(sm.getString("combinedRealm.authSuccess",
-                                gssName, realm.getClass().getName()));
+                        log.debug(sm.getString("combinedRealm.authSuccess", gssName, realm.getClass().getName()));
                     }
                     break;
                 }
@@ -399,21 +368,18 @@ public class CombinedRealm extends RealmBase {
 
         for (Realm realm : realms) {
             if (log.isDebugEnabled()) {
-                log.debug(sm.getString("combinedRealm.authStart",
-                        gssName, realm.getClass().getName()));
+                log.debug(sm.getString("combinedRealm.authStart", gssName, realm.getClass().getName()));
             }
 
             authenticatedUser = realm.authenticate(gssName, gssCredential);
 
             if (authenticatedUser == null) {
                 if (log.isDebugEnabled()) {
-                    log.debug(sm.getString("combinedRealm.authFail",
-                            gssName, realm.getClass().getName()));
+                    log.debug(sm.getString("combinedRealm.authFail", gssName, realm.getClass().getName()));
                 }
             } else {
                 if (log.isDebugEnabled()) {
-                    log.debug(sm.getString("combinedRealm.authSuccess",
-                            gssName, realm.getClass().getName()));
+                    log.debug(sm.getString("combinedRealm.authSuccess", gssName, realm.getClass().getName()));
                 }
                 break;
             }
@@ -438,9 +404,8 @@ public class CombinedRealm extends RealmBase {
     protected String getPassword(String username) {
         // This method should never be called
         // Stack trace will show where this was called from
-        UnsupportedOperationException uoe =
-            new UnsupportedOperationException(
-                    sm.getString("combinedRealm.getPassword"));
+        UnsupportedOperationException uoe = new UnsupportedOperationException(
+                sm.getString("combinedRealm.getPassword"));
         log.error(sm.getString("combinedRealm.unexpectedMethod"), uoe);
         throw uoe;
     }
@@ -449,9 +414,8 @@ public class CombinedRealm extends RealmBase {
     protected Principal getPrincipal(String username) {
         // This method should never be called
         // Stack trace will show where this was called from
-        UnsupportedOperationException uoe =
-            new UnsupportedOperationException(
-                    sm.getString("combinedRealm.getPrincipal"));
+        UnsupportedOperationException uoe = new UnsupportedOperationException(
+                sm.getString("combinedRealm.getPrincipal"));
         log.error(sm.getString("combinedRealm.unexpectedMethod"), uoe);
         throw uoe;
     }
@@ -479,8 +443,7 @@ public class CombinedRealm extends RealmBase {
     private class CombinedRealmCredentialHandler implements CredentialHandler {
 
         @Override
-        public boolean matches(String inputCredentials,
-                String storedCredentials) {
+        public boolean matches(String inputCredentials, String storedCredentials) {
             for (Realm realm : realms) {
                 if (realm.getCredentialHandler().matches(inputCredentials, storedCredentials)) {
                     return true;
@@ -501,7 +464,7 @@ public class CombinedRealm extends RealmBase {
                 }
             }
             return null;
-       }
+        }
 
     }
 }
diff --git a/java/org/apache/catalina/realm/DataSourceRealm.java b/java/org/apache/catalina/realm/DataSourceRealm.java
index 8ac2e37f01..644ab5dc3f 100644
--- a/java/org/apache/catalina/realm/DataSourceRealm.java
+++ b/java/org/apache/catalina/realm/DataSourceRealm.java
@@ -31,9 +31,8 @@ import org.apache.catalina.LifecycleException;
 import org.apache.naming.ContextBindings;
 
 /**
- * Implementation of <b>Realm</b> that works with any JDBC JNDI DataSource.
- * See the Realm How-To for more details on how to set up the database and
- * for configuration options.
+ * Implementation of <b>Realm</b> that works with any JDBC JNDI DataSource. See the Realm How-To for more details on how
+ * to set up the database and for configuration options.
  *
  * @author Glenn L. Nielsen
  * @author Craig R. McClanahan
@@ -121,8 +120,8 @@ public class DataSourceRealm extends RealmBase {
      *
      * @param dataSourceName the name of the JNDI JDBC DataSource
      */
-    public void setDataSourceName( String dataSourceName) {
-      this.dataSourceName = dataSourceName;
+    public void setDataSourceName(String dataSourceName) {
+        this.dataSourceName = dataSourceName;
     }
 
     /**
@@ -133,13 +132,12 @@ public class DataSourceRealm extends RealmBase {
     }
 
     /**
-     * Set to true to cause the datasource to be looked up in the webapp JNDI
-     * Context.
+     * Set to true to cause the datasource to be looked up in the webapp JNDI Context.
      *
      * @param localDataSource the new flag value
      */
     public void setLocalDataSource(boolean localDataSource) {
-      this.localDataSource = localDataSource;
+        this.localDataSource = localDataSource;
     }
 
     /**
@@ -154,7 +152,7 @@ public class DataSourceRealm extends RealmBase {
      *
      * @param roleNameCol The column name
      */
-    public void setRoleNameCol( String roleNameCol ) {
+    public void setRoleNameCol(String roleNameCol) {
         this.roleNameCol = roleNameCol;
     }
 
@@ -170,8 +168,8 @@ public class DataSourceRealm extends RealmBase {
      *
      * @param userCredCol The column name
      */
-    public void setUserCredCol( String userCredCol ) {
-       this.userCredCol = userCredCol;
+    public void setUserCredCol(String userCredCol) {
+        this.userCredCol = userCredCol;
     }
 
     /**
@@ -186,8 +184,8 @@ public class DataSourceRealm extends RealmBase {
      *
      * @param userNameCol The column name
      */
-    public void setUserNameCol( String userNameCol ) {
-       this.userNameCol = userNameCol;
+    public void setUserNameCol(String userNameCol) {
+        this.userNameCol = userNameCol;
     }
 
     /**
@@ -202,7 +200,7 @@ public class DataSourceRealm extends RealmBase {
      *
      * @param userRoleTable The table name
      */
-    public void setUserRoleTable( String userRoleTable ) {
+    public void setUserRoleTable(String userRoleTable) {
         this.userRoleTable = userRoleTable;
     }
 
@@ -218,25 +216,22 @@ public class DataSourceRealm extends RealmBase {
      *
      * @param userTable The table name
      */
-    public void setUserTable( String userTable ) {
-      this.userTable = userTable;
+    public void setUserTable(String userTable) {
+        this.userTable = userTable;
     }
 
 
     // --------------------------------------------------------- Public Methods
 
     /**
-     * Return the Principal associated with the specified username and
-     * credentials, if there is one; otherwise return <code>null</code>.
+     * Return the Principal associated with the specified username and credentials, if there is one; otherwise return
+     * <code>null</code>. If there are any errors with the JDBC connection, executing the query or anything we return
+     * null (don't authenticate). This event is also logged, and the connection will be closed so that a subsequent
+     * request will automatically re-open it.
      *
-     * If there are any errors with the JDBC connection, executing
-     * the query or anything we return null (don't authenticate). This
-     * event is also logged, and the connection will be closed so that
-     * a subsequent request will automatically re-open it.
+     * @param username    Username of the Principal to look up
+     * @param credentials Password or other credentials to use in authenticating this username
      *
-     * @param username Username of the Principal to look up
-     * @param credentials Password or other credentials to use in
-     *  authenticating this username
      * @return the associated principal, or <code>null</code> if there is none.
      */
     @Override
@@ -257,13 +252,10 @@ public class DataSourceRealm extends RealmBase {
             return null;
         }
 
-        try
-        {
+        try {
             // Acquire a Principal object for this user
             return authenticate(dbConnection, username, credentials);
-        }
-        finally
-        {
+        } finally {
             close(dbConnection);
         }
     }
@@ -281,24 +273,21 @@ public class DataSourceRealm extends RealmBase {
 
 
     /**
-     * Return the Principal associated with the specified username and
-     * credentials, if there is one; otherwise return <code>null</code>.
+     * Return the Principal associated with the specified username and credentials, if there is one; otherwise return
+     * <code>null</code>.
      *
      * @param dbConnection The database connection to be used
-     * @param username Username of the Principal to look up
-     * @param credentials Password or other credentials to use in
-     *  authenticating this username
+     * @param username     Username of the Principal to look up
+     * @param credentials  Password or other credentials to use in authenticating this username
+     *
      * @return the associated principal, or <code>null</code> if there is none.
      */
-    protected Principal authenticate(Connection dbConnection,
-                                     String username,
-                                     String credentials) {
+    protected Principal authenticate(Connection dbConnection, String username, String credentials) {
         // No user or no credentials
         // Can't possibly authenticate, don't bother the database then
         if (username == null || credentials == null) {
             if (containerLog.isTraceEnabled()) {
-                containerLog.trace(sm.getString("dataSourceRealm.authenticateFailure",
-                                                username));
+                containerLog.trace(sm.getString("dataSourceRealm.authenticateFailure", username));
             }
             return null;
         }
@@ -306,14 +295,13 @@ public class DataSourceRealm extends RealmBase {
         // Look up the user's credentials
         String dbCredentials = getPassword(dbConnection, username);
 
-        if(dbCredentials == null) {
+        if (dbCredentials == null) {
             // User was not found in the database.
             // Waste a bit of time as not to reveal that the user does not exist.
             getCredentialHandler().mutate(credentials);
 
             if (containerLog.isTraceEnabled()) {
-                containerLog.trace(sm.getString("dataSourceRealm.authenticateFailure",
-                                                username));
+                containerLog.trace(sm.getString("dataSourceRealm.authenticateFailure", username));
             }
             return null;
         }
@@ -323,13 +311,11 @@ public class DataSourceRealm extends RealmBase {
 
         if (validated) {
             if (containerLog.isTraceEnabled()) {
-                containerLog.trace(sm.getString("dataSourceRealm.authenticateSuccess",
-                                                username));
+                containerLog.trace(sm.getString("dataSourceRealm.authenticateSuccess", username));
             }
         } else {
             if (containerLog.isTraceEnabled()) {
-                containerLog.trace(sm.getString("dataSourceRealm.authenticateFailure",
-                                                username));
+                containerLog.trace(sm.getString("dataSourceRealm.authenticateFailure", username));
             }
             return null;
         }
@@ -386,7 +372,7 @@ public class DataSourceRealm extends RealmBase {
             } else {
                 context = getServer().getGlobalNamingContext();
             }
-            DataSource dataSource = (DataSource)context.lookup(dataSourceName);
+            DataSource dataSource = (DataSource) context.lookup(dataSourceName);
             Connection connection = dataSource.getConnection();
             connectionSuccess = true;
             return connection;
@@ -424,7 +410,7 @@ public class DataSourceRealm extends RealmBase {
      * Return the password associated with the given principal's user name.
      *
      * @param dbConnection The database connection to be used
-     * @param username Username for which password should be retrieved
+     * @param username     Username for which password should be retrieved
      *
      * @return the password for the specified user
      */
@@ -452,7 +438,9 @@ public class DataSourceRealm extends RealmBase {
 
     /**
      * Return the Principal associated with the given user name.
+     *
      * @param username the user name
+     *
      * @return the principal object
      */
     @Override
@@ -462,8 +450,7 @@ public class DataSourceRealm extends RealmBase {
             return new GenericPrincipal(username, null, null);
         }
         try {
-            return new GenericPrincipal(username,
-                    getPassword(dbConnection, username),
+            return new GenericPrincipal(username, getPassword(dbConnection, username),
                     getRoles(dbConnection, username));
         } finally {
             close(dbConnection);
@@ -473,7 +460,9 @@ public class DataSourceRealm extends RealmBase {
 
     /**
      * Return the roles associated with the given user name.
+     *
      * @param username User name for which roles should be retrieved
+     *
      * @return an array list of the role names
      */
     protected ArrayList<String> getRoles(String username) {
@@ -498,7 +487,7 @@ public class DataSourceRealm extends RealmBase {
      * Return the roles associated with the given user name.
      *
      * @param dbConnection The database connection to be used
-     * @param username User name for which roles should be retrieved
+     * @param username     User name for which roles should be retrieved
      *
      * @return an array list of the role names
      */
@@ -526,7 +515,7 @@ public class DataSourceRealm extends RealmBase {
                 }
                 return list;
             }
-        } catch(SQLException e) {
+        } catch (SQLException e) {
             containerLog.error(sm.getString("dataSourceRealm.getRoles.exception", username), e);
         }
 
@@ -542,12 +531,11 @@ public class DataSourceRealm extends RealmBase {
     // ------------------------------------------------------ Lifecycle Methods
 
     /**
-     * Prepare for the beginning of active use of the public methods of this
-     * component and implement the requirements of
+     * Prepare for the beginning of active use of the public methods of this component and implement the requirements of
      * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
      *
-     * @exception LifecycleException if this component detects a fatal error
-     *  that prevents this component from being used
+     * @exception LifecycleException if this component detects a fatal error that prevents this component from being
+     *                                   used
      */
     @Override
     protected void startInternal() throws LifecycleException {
diff --git a/java/org/apache/catalina/realm/DigestCredentialHandlerBase.java b/java/org/apache/catalina/realm/DigestCredentialHandlerBase.java
index 0291df01fb..2743184df0 100644
--- a/java/org/apache/catalina/realm/DigestCredentialHandlerBase.java
+++ b/java/org/apache/catalina/realm/DigestCredentialHandlerBase.java
@@ -31,8 +31,7 @@ import org.apache.tomcat.util.res.StringManager;
  */
 public abstract class DigestCredentialHandlerBase implements CredentialHandler {
 
-    protected static final StringManager sm =
-            StringManager.getManager(DigestCredentialHandlerBase.class);
+    protected static final StringManager sm = StringManager.getManager(DigestCredentialHandlerBase.class);
 
     public static final int DEFAULT_SALT_LENGTH = 32;
 
@@ -44,8 +43,8 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
 
 
     /**
-     * @return the number of iterations of the associated algorithm that will be
-     * used when creating a new stored credential for a given input credential.
+     * @return the number of iterations of the associated algorithm that will be used when creating a new stored
+     *             credential for a given input credential.
      */
     public int getIterations() {
         return iterations;
@@ -53,8 +52,9 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
 
 
     /**
-     * Set the number of iterations of the associated algorithm that will be
-     * used when creating a new stored credential for a given input credential.
+     * Set the number of iterations of the associated algorithm that will be used when creating a new stored credential
+     * for a given input credential.
+     *
      * @param iterations the iterations count
      */
     public void setIterations(int iterations) {
@@ -63,8 +63,7 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
 
 
     /**
-     * @return the salt length that will be used when creating a new stored
-     * credential for a given input credential.
+     * @return the salt length that will be used when creating a new stored credential for a given input credential.
      */
     public int getSaltLength() {
         return saltLength;
@@ -72,8 +71,8 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
 
 
     /**
-     * Set the salt length that will be used when creating a new stored
-     * credential for a given input credential.
+     * Set the salt length that will be used when creating a new stored credential for a given input credential.
+     *
      * @param saltLength the salt length
      */
     public void setSaltLength(int saltLength) {
@@ -82,8 +81,9 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
 
 
     /**
-     * When checking input credentials against stored credentials will a warning
-     * message be logged if invalid stored credentials are discovered?
+     * When checking input credentials against stored credentials will a warning message be logged if invalid stored
+     * credentials are discovered?
+     *
      * @return <code>true</code> if logging will occur
      */
     public boolean getLogInvalidStoredCredentials() {
@@ -92,11 +92,10 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
 
 
     /**
-     * Set whether a warning message will be logged if invalid stored
-     * credentials are discovered while checking input credentials against
-     * stored credentials?
-     * @param logInvalidStoredCredentials <code>true</code> to log, the
-     *   default value is <code>false</code>
+     * Set whether a warning message will be logged if invalid stored credentials are discovered while checking input
+     * credentials against stored credentials?
+     *
+     * @param logInvalidStoredCredentials <code>true</code> to log, the default value is <code>false</code>
      */
     public void setLogInvalidStoredCredentials(boolean logInvalidStoredCredentials) {
         this.logInvalidStoredCredentials = logInvalidStoredCredentials;
@@ -138,8 +137,7 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
             // Output the simple/old format for backwards compatibility
             return serverCredential;
         } else {
-            StringBuilder result =
-                    new StringBuilder((saltLength << 1) + 10 + serverCredential.length() + 2);
+            StringBuilder result = new StringBuilder((saltLength << 1) + 10 + serverCredential.length() + 2);
             result.append(HexUtils.toHexString(salt));
             result.append('$');
             result.append(iterations);
@@ -152,16 +150,15 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
 
 
     /**
-     * Checks whether the provided credential matches the stored credential when
-     * the stored credential is in the form salt$iteration-count$credential
+     * Checks whether the provided credential matches the stored credential when the stored credential is in the form
+     * salt$iteration-count$credential
      *
      * @param inputCredentials  The input credential
      * @param storedCredentials The stored credential
      *
      * @return <code>true</code> if they match, otherwise <code>false</code>
      */
-    protected boolean matchesSaltIterationsEncoded(String inputCredentials,
-            String storedCredentials) {
+    protected boolean matchesSaltIterationsEncoded(String inputCredentials, String storedCredentials) {
 
         if (storedCredentials == null) {
             // Stored credentials are invalid
@@ -180,7 +177,7 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
             return false;
         }
 
-        String hexSalt = storedCredentials.substring(0,  sep1);
+        String hexSalt = storedCredentials.substring(0, sep1);
 
         int iterations = Integer.parseInt(storedCredentials.substring(sep1 + 1, sep2));
 
@@ -209,8 +206,7 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
         if (logInvalidStoredCredentials) {
             // Logging credentials could be a security concern but they are
             // invalid and that is probably a bigger problem
-            getLog().warn(sm.getString("credentialHandler.invalidStoredCredential",
-                    storedCredentials));
+            getLog().warn(sm.getString("credentialHandler.invalidStoredCredential", storedCredentials));
         }
     }
 
@@ -224,41 +220,33 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
 
 
     /**
-     * Generates the equivalent stored credentials for the given input
-     * credentials, salt and iterations. If the algorithm requires a key length,
-     * the default will be used.
+     * Generates the equivalent stored credentials for the given input credentials, salt and iterations. If the
+     * algorithm requires a key length, the default will be used.
      *
-     * @param inputCredentials  User provided credentials
-     * @param salt              Salt, if any
-     * @param iterations        Number of iterations of the algorithm associated
-     *                          with this CredentialHandler applied to the
-     *                          inputCredentials to generate the equivalent
-     *                          stored credentials
+     * @param inputCredentials User provided credentials
+     * @param salt             Salt, if any
+     * @param iterations       Number of iterations of the algorithm associated with this CredentialHandler applied to
+     *                             the inputCredentials to generate the equivalent stored credentials
      *
-     * @return  The equivalent stored credentials for the given input
-     *          credentials or <code>null</code> if the generation fails
+     * @return The equivalent stored credentials for the given input credentials or <code>null</code> if the generation
+     *             fails
      */
     protected abstract String mutate(String inputCredentials, byte[] salt, int iterations);
 
 
     /**
-     * Generates the equivalent stored credentials for the given input
-     * credentials, salt, iterations and key length. The default implementation
-     * calls ignores the key length and calls
-     * {@link #mutate(String, byte[], int)}. Sub-classes that use the key length
-     * should override this method.
+     * Generates the equivalent stored credentials for the given input credentials, salt, iterations and key length. The
+     * default implementation calls ignores the key length and calls {@link #mutate(String, byte[], int)}. Sub-classes
+     * that use the key length should override this method.
      *
-     * @param inputCredentials  User provided credentials
-     * @param salt              Salt, if any
-     * @param iterations        Number of iterations of the algorithm associated
-     *                          with this CredentialHandler applied to the
-     *                          inputCredentials to generate the equivalent
-     *                          stored credentials
-     * @param keyLength         Length of the produced digest in bits for
-     *                          implementations where it's applicable
+     * @param inputCredentials User provided credentials
+     * @param salt             Salt, if any
+     * @param iterations       Number of iterations of the algorithm associated with this CredentialHandler applied to
+     *                             the inputCredentials to generate the equivalent stored credentials
+     * @param keyLength        Length of the produced digest in bits for implementations where it's applicable
      *
-     * @return  The equivalent stored credentials for the given input
-     *          credentials or <code>null</code> if the generation fails
+     * @return The equivalent stored credentials for the given input credentials or <code>null</code> if the generation
+     *             fails
      */
     protected String mutate(String inputCredentials, byte[] salt, int iterations, int keyLength) {
         return mutate(inputCredentials, salt, iterations);
@@ -266,25 +254,23 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
 
 
     /**
-     * Set the algorithm used to convert input credentials to stored
-     * credentials.
+     * Set the algorithm used to convert input credentials to stored credentials.
+     *
      * @param algorithm the algorithm
-     * @throws NoSuchAlgorithmException if the specified algorithm
-     *  is not supported
+     *
+     * @throws NoSuchAlgorithmException if the specified algorithm is not supported
      */
     public abstract void setAlgorithm(String algorithm) throws NoSuchAlgorithmException;
 
 
     /**
-     * @return the algorithm used to convert input credentials to stored
-     * credentials.
+     * @return the algorithm used to convert input credentials to stored credentials.
      */
     public abstract String getAlgorithm();
 
 
     /**
-     * @return the default number of iterations used by the
-     * {@link CredentialHandler}.
+     * @return the default number of iterations used by the {@link CredentialHandler}.
      */
     protected abstract int getDefaultIterations();
 
@@ -295,21 +281,18 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
     protected abstract Log getLog();
 
     /**
-     * Implements String equality which always compares all characters in the
-     * string, without stopping early if any characters do not match.
+     * Implements String equality which always compares all characters in the string, without stopping early if any
+     * characters do not match.
      * <p>
-     * <i>Note:</i>
-     * This implementation was adapted from {@link MessageDigest#isEqual}
-     * which we assume is as optimizer-defeating as possible.
+     * <i>Note:</i> This implementation was adapted from {@link MessageDigest#isEqual} which we assume is as
+     * optimizer-defeating as possible.
      *
-     * @param s1 The first string to compare.
-     * @param s2 The second string to compare.
-     * @param ignoreCase <code>true</code> if the strings should be compared
-     *        without regard to case. Note that "true" here is only guaranteed
-     *        to work with plain ASCII characters.
+     * @param s1         The first string to compare.
+     * @param s2         The second string to compare.
+     * @param ignoreCase <code>true</code> if the strings should be compared without regard to case. Note that "true"
+     *                       here is only guaranteed to work with plain ASCII characters.
      *
-     * @return <code>true</code> if the strings are equal to each other,
-     *         <code>false</code> otherwise.
+     * @return <code>true</code> if the strings are equal to each other, <code>false</code> otherwise.
      */
     public static boolean equals(final String s1, final String s2, final boolean ignoreCase) {
         if (s1 == s2) {
@@ -335,7 +318,7 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
             final int index2 = ((i - len2) >>> 31) * i;
             char c1 = s1.charAt(i);
             char c2 = s2.charAt(index2);
-            if(ignoreCase) {
+            if (ignoreCase) {
                 c1 = Character.toLowerCase(c1);
                 c2 = Character.toLowerCase(c2);
             }
@@ -345,22 +328,18 @@ public abstract class DigestCredentialHandlerBase implements CredentialHandler {
     }
 
     /**
-     * Implements byte-array equality which always compares all bytes in the
-     * array, without stopping early if any bytes do not match.
+     * Implements byte-array equality which always compares all bytes in the array, without stopping early if any bytes
+     * do not match.
      * <p>
-     * <i>Note:</i>
-     * Implementation note: this method delegates to {@link MessageDigest#isEqual}
-     * under the assumption that it provides a constant-time comparison of the
-     * bytes in the arrays. Java 7+ has such an implementation, but neither the
-     * Javadoc nor any specification requires it. Therefore, Tomcat should
-     * continue to use <i>this</i> method internally in case the JDK
-     * implementation changes so this method can be re-implemented properly.
+     * <i>Note:</i> Implementation note: this method delegates to {@link MessageDigest#isEqual} under the assumption
+     * that it provides a constant-time comparison of the bytes in the arrays. Java 7+ has such an implementation, but
+     * neither the Javadoc nor any specification requires it. Therefore, Tomcat should continue to use <i>this</i>
+     * method internally in case the JDK implementation changes so this method can be re-implemented properly.
      *
      * @param b1 The first array to compare.
      * @param b2 The second array to compare.
      *
-     * @return <code>true</code> if the arrays are equal to each other,
-     *         <code>false</code> otherwise.
+     * @return <code>true</code> if the arrays are equal to each other, <code>false</code> otherwise.
      */
     public static boolean equals(final byte[] b1, final byte[] b2) {
         return MessageDigest.isEqual(b1, b2);
diff --git a/java/org/apache/catalina/realm/GenericPrincipal.java b/java/org/apache/catalina/realm/GenericPrincipal.java
index bf765273cb..da00102750 100644
--- a/java/org/apache/catalina/realm/GenericPrincipal.java
+++ b/java/org/apache/catalina/realm/GenericPrincipal.java
@@ -30,8 +30,8 @@ import org.apache.catalina.TomcatPrincipal;
 import org.ietf.jgss.GSSCredential;
 
 /**
- * Generic implementation of <strong>java.security.Principal</strong> that
- * is available for use by <code>Realm</code> implementations.
+ * Generic implementation of <strong>java.security.Principal</strong> that is available for use by <code>Realm</code>
+ * implementations.
  *
  * @author Craig R. McClanahan
  */
@@ -43,71 +43,62 @@ public class GenericPrincipal implements TomcatPrincipal, Serializable {
     // ----------------------------------------------------------- Constructors
 
     /**
-     * Construct a new Principal, associated with the specified Realm, for the
-     * specified username and password, with the specified role names
-     * (as Strings).
+     * Construct a new Principal, associated with the specified Realm, for the specified username and password, with the
+     * specified role names (as Strings).
      *
-     * @param name The username of the user represented by this Principal
+     * @param name     The username of the user represented by this Principal
      * @param password Credentials used to authenticate this user
-     * @param roles List of roles (must be Strings) possessed by this user
+     * @param roles    List of roles (must be Strings) possessed by this user
      */
     public GenericPrincipal(String name, String password, List<String> roles) {
         this(name, password, roles, null);
     }
 
     /**
-     * Construct a new Principal, associated with the specified Realm, for the
-     * specified username and password, with the specified role names
-     * (as Strings).
+     * Construct a new Principal, associated with the specified Realm, for the specified username and password, with the
+     * specified role names (as Strings).
      *
-     * @param name The username of the user represented by this Principal
-     * @param password Credentials used to authenticate this user
-     * @param roles List of roles (must be Strings) possessed by this user
-     * @param userPrincipal - the principal to be returned from the request
-     *        getUserPrincipal call if not null; if null, this will be returned
+     * @param name          The username of the user represented by this Principal
+     * @param password      Credentials used to authenticate this user
+     * @param roles         List of roles (must be Strings) possessed by this user
+     * @param userPrincipal - the principal to be returned from the request getUserPrincipal call if not null; if null,
+     *                          this will be returned
      */
-    public GenericPrincipal(String name, String password, List<String> roles,
-            Principal userPrincipal) {
+    public GenericPrincipal(String name, String password, List<String> roles, Principal userPrincipal) {
         this(name, password, roles, userPrincipal, null);
     }
 
     /**
-     * Construct a new Principal, associated with the specified Realm, for the
-     * specified username and password, with the specified role names
-     * (as Strings).
+     * Construct a new Principal, associated with the specified Realm, for the specified username and password, with the
+     * specified role names (as Strings).
      *
-     * @param name The username of the user represented by this Principal
-     * @param password Credentials used to authenticate this user
-     * @param roles List of roles (must be Strings) possessed by this user
-     * @param userPrincipal - the principal to be returned from the request
-     *        getUserPrincipal call if not null; if null, this will be returned
-     * @param loginContext  - If provided, this will be used to log out the user
-     *        at the appropriate time
+     * @param name          The username of the user represented by this Principal
+     * @param password      Credentials used to authenticate this user
+     * @param roles         List of roles (must be Strings) possessed by this user
+     * @param userPrincipal - the principal to be returned from the request getUserPrincipal call if not null; if null,
+     *                          this will be returned
+     * @param loginContext  - If provided, this will be used to log out the user at the appropriate time
      */
-    public GenericPrincipal(String name, String password, List<String> roles,
-            Principal userPrincipal, LoginContext loginContext) {
+    public GenericPrincipal(String name, String password, List<String> roles, Principal userPrincipal,
+            LoginContext loginContext) {
         this(name, password, roles, userPrincipal, loginContext, null, null);
     }
 
     /**
-     * Construct a new Principal, associated with the specified Realm, for the
-     * specified username and password, with the specified role names
-     * (as Strings).
+     * Construct a new Principal, associated with the specified Realm, for the specified username and password, with the
+     * specified role names (as Strings).
      *
-     * @param name The username of the user represented by this Principal
-     * @param password Credentials used to authenticate this user
-     * @param roles List of roles (must be Strings) possessed by this user
-     * @param userPrincipal - the principal to be returned from the request
-     *        getUserPrincipal call if not null; if null, this will be returned
-     * @param loginContext  - If provided, this will be used to log out the user
-     *        at the appropriate time
+     * @param name          The username of the user represented by this Principal
+     * @param password      Credentials used to authenticate this user
+     * @param roles         List of roles (must be Strings) possessed by this user
+     * @param userPrincipal - the principal to be returned from the request getUserPrincipal call if not null; if null,
+     *                          this will be returned
+     * @param loginContext  - If provided, this will be used to log out the user at the appropriate time
      * @param gssCredential - If provided, the user's delegated credentials
-     * @param attributes - If provided, additional attributes associated with
-     *        this Principal
+     * @param attributes    - If provided, additional attributes associated with this Principal
      */
-    public GenericPrincipal(String name, String password, List<String> roles,
-            Principal userPrincipal, LoginContext loginContext,
-            GSSCredential gssCredential, Map<String, Object> attributes) {
+    public GenericPrincipal(String name, String password, List<String> roles, Principal userPrincipal,
+            LoginContext loginContext, GSSCredential gssCredential, Map<String, Object> attributes) {
         super();
         this.name = name;
         this.password = password;
@@ -140,8 +131,7 @@ public class GenericPrincipal implements TomcatPrincipal, Serializable {
 
 
     /**
-     * The authentication credentials for the user represented by
-     * this Principal.
+     * The authentication credentials for the user represented by this Principal.
      */
     protected final String password;
 
@@ -176,8 +166,7 @@ public class GenericPrincipal implements TomcatPrincipal, Serializable {
 
 
     /**
-     * The JAAS LoginContext, if any, used to authenticate this Principal.
-     * Kept so we can call logout().
+     * The JAAS LoginContext, if any, used to authenticate this Principal. Kept so we can call logout().
      */
     protected final transient LoginContext loginContext;
 
@@ -191,6 +180,7 @@ public class GenericPrincipal implements TomcatPrincipal, Serializable {
     public GSSCredential getGssCredential() {
         return this.gssCredential;
     }
+
     protected void setGssCredential(GSSCredential gssCredential) {
         this.gssCredential = gssCredential;
     }
@@ -208,8 +198,7 @@ public class GenericPrincipal implements TomcatPrincipal, Serializable {
      *
      * @param role Role to be tested
      *
-     * @return <code>true</code> if this Principal has been assigned the given
-     *         role, otherwise <code>false</code>
+     * @return <code>true</code> if this Principal has been assigned the given role, otherwise <code>false</code>
      */
     public boolean hasRole(String role) {
         if ("*".equals(role)) { // Special 2.4 role meaning everyone
@@ -223,8 +212,7 @@ public class GenericPrincipal implements TomcatPrincipal, Serializable {
 
 
     /**
-     * Return a String representation of this object, which exposes only
-     * information that should be public.
+     * Return a String representation of this object, which exposes only information that should be public.
      */
     @Override
     public String toString() {
@@ -283,8 +271,8 @@ public class GenericPrincipal implements TomcatPrincipal, Serializable {
         private final Principal principal;
         private final Map<String, Object> attributes;
 
-        public SerializablePrincipal(String name, String password, String[] roles,
-                Principal principal, Map<String, Object> attributes) {
+        public SerializablePrincipal(String name, String password, String[] roles, Principal principal,
+                Map<String, Object> attributes) {
             this.name = name;
             this.password = password;
             this.roles = roles;
@@ -297,8 +285,7 @@ public class GenericPrincipal implements TomcatPrincipal, Serializable {
         }
 
         private Object readResolve() {
-            return new GenericPrincipal(name, password, Arrays.asList(roles), principal, null, null,
-                    attributes);
+            return new GenericPrincipal(name, password, Arrays.asList(roles), principal, null, null, attributes);
         }
     }
 }
diff --git a/java/org/apache/catalina/realm/JAASCallbackHandler.java b/java/org/apache/catalina/realm/JAASCallbackHandler.java
index dfb3bc6668..bf0205e9b1 100644
--- a/java/org/apache/catalina/realm/JAASCallbackHandler.java
+++ b/java/org/apache/catalina/realm/JAASCallbackHandler.java
@@ -29,17 +29,19 @@ import javax.security.auth.callback.UnsupportedCallbackException;
 import org.apache.tomcat.util.res.StringManager;
 
 /**
- * <p>Implementation of the JAAS <code>CallbackHandler</code> interface,
- * used to negotiate delivery of the username and credentials that were
- * specified to our constructor.  No interaction with the user is required
- * (or possible).</p>
- *
- * <p>This <code>CallbackHandler</code> will pre-digest the supplied
- * password, if required by the <code>&lt;Realm&gt;</code> element in
- * <code>server.xml</code>.</p>
- * <p>At present, <code>JAASCallbackHandler</code> knows how to handle callbacks of
- * type <code>javax.security.auth.callback.NameCallback</code> and
- * <code>javax.security.auth.callback.PasswordCallback</code>.</p>
+ * <p>
+ * Implementation of the JAAS <code>CallbackHandler</code> interface, used to negotiate delivery of the username and
+ * credentials that were specified to our constructor. No interaction with the user is required (or possible).
+ * </p>
+ * <p>
+ * This <code>CallbackHandler</code> will pre-digest the supplied password, if required by the
+ * <code>&lt;Realm&gt;</code> element in <code>server.xml</code>.
+ * </p>
+ * <p>
+ * At present, <code>JAASCallbackHandler</code> knows how to handle callbacks of type
+ * <code>javax.security.auth.callback.NameCallback</code> and
+ * <code>javax.security.auth.callback.PasswordCallback</code>.
+ * </p>
  *
  * @author Craig R. McClanahan
  * @author Andrew R. Jaquith
@@ -50,41 +52,35 @@ public class JAASCallbackHandler implements CallbackHandler {
 
 
     /**
-     * Construct a callback handler configured with the specified values.
-     * Note that if the <code>JAASRealm</code> instance specifies digested passwords,
-     * the <code>password</code> parameter will be pre-digested here.
+     * Construct a callback handler configured with the specified values. Note that if the <code>JAASRealm</code>
+     * instance specifies digested passwords, the <code>password</code> parameter will be pre-digested here.
      *
-     * @param realm Our associated JAASRealm instance
+     * @param realm    Our associated JAASRealm instance
      * @param username Username to be authenticated with
      * @param password Password to be authenticated with
      */
-    public JAASCallbackHandler(JAASRealm realm, String username,
-                               String password) {
+    public JAASCallbackHandler(JAASRealm realm, String username, String password) {
 
-        this(realm, username, password, null, null, null, null, null, null,
-                null);
+        this(realm, username, password, null, null, null, null, null, null, null);
     }
 
 
     /**
      * Construct a callback handler for DIGEST authentication.
      *
-     * @param realm         Our associated JAASRealm instance
-     * @param username      Username to be authenticated with
-     * @param password      Password to be authenticated with
-     * @param nonce         Server generated nonce
-     * @param nc            Nonce count
-     * @param cnonce        Client generated nonce
-     * @param qop           Quality of protection applied to the message
-     * @param realmName     Realm name
-     * @param md5a2         Second MD5 digest used to calculate the digest
-     *                      MD5(Method + ":" + uri)
-     * @param authMethod    The authentication method in use
+     * @param realm      Our associated JAASRealm instance
+     * @param username   Username to be authenticated with
+     * @param password   Password to be authenticated with
+     * @param nonce      Server generated nonce
+     * @param nc         Nonce count
+     * @param cnonce     Client generated nonce
+     * @param qop        Quality of protection applied to the message
+     * @param realmName  Realm name
+     * @param md5a2      Second MD5 digest used to calculate the digest MD5(Method + ":" + uri)
+     * @param authMethod The authentication method in use
      */
-    public JAASCallbackHandler(JAASRealm realm, String username,
-                               String password, String nonce, String nc,
-                               String cnonce, String qop, String realmName,
-                               String md5a2, String authMethod) {
+    public JAASCallbackHandler(JAASRealm realm, String username, String password, String nonce, String nc,
+            String cnonce, String qop, String realmName, String md5a2, String authMethod) {
         this.realm = realm;
         this.username = username;
 
@@ -164,21 +160,17 @@ public class JAASCallbackHandler implements CallbackHandler {
 
 
     /**
-     * Retrieve the information requested in the provided <code>Callbacks</code>.
-     * This implementation only recognizes {@link NameCallback},
-     * {@link PasswordCallback} and {@link TextInputCallback}.
-     * {@link TextInputCallback} is used to pass the various additional
-     * parameters required for DIGEST authentication.
+     * Retrieve the information requested in the provided <code>Callbacks</code>. This implementation only recognizes
+     * {@link NameCallback}, {@link PasswordCallback} and {@link TextInputCallback}. {@link TextInputCallback} is used
+     * to pass the various additional parameters required for DIGEST authentication.
      *
      * @param callbacks The set of <code>Callback</code>s to be processed
      *
-     * @exception IOException if an input/output error occurs
-     * @exception UnsupportedCallbackException if the login method requests
-     *  an unsupported callback type
+     * @exception IOException                  if an input/output error occurs
+     * @exception UnsupportedCallbackException if the login method requests an unsupported callback type
      */
     @Override
-    public void handle(Callback callbacks[])
-        throws IOException, UnsupportedCallbackException {
+    public void handle(Callback callbacks[]) throws IOException, UnsupportedCallbackException {
 
         for (Callback callback : callbacks) {
 
@@ -187,41 +179,31 @@ public class JAASCallbackHandler implements CallbackHandler {
                     realm.getContainer().getLogger().trace(sm.getString("jaasCallback.username", username));
                 }
                 ((NameCallback) callback).setName(username);
-            }
-            else if (callback instanceof PasswordCallback) {
+            } else if (callback instanceof PasswordCallback) {
                 final char[] passwordcontents;
                 if (password != null) {
                     passwordcontents = password.toCharArray();
                 } else {
                     passwordcontents = new char[0];
                 }
-                ((PasswordCallback) callback).setPassword
-                        (passwordcontents);
-            }
-            else if (callback instanceof TextInputCallback) {
+                ((PasswordCallback) callback).setPassword(passwordcontents);
+            } else if (callback instanceof TextInputCallback) {
                 TextInputCallback cb = ((TextInputCallback) callback);
                 if (cb.getPrompt().equals("nonce")) {
                     cb.setText(nonce);
-                }
-                else if (cb.getPrompt().equals("nc")) {
+                } else if (cb.getPrompt().equals("nc")) {
                     cb.setText(nc);
-                }
-                else if (cb.getPrompt().equals("cnonce")) {
+                } else if (cb.getPrompt().equals("cnonce")) {
                     cb.setText(cnonce);
-                }
-                else if (cb.getPrompt().equals("qop")) {
+                } else if (cb.getPrompt().equals("qop")) {
                     cb.setText(qop);
-                }
-                else if (cb.getPrompt().equals("realmName")) {
+                } else if (cb.getPrompt().equals("realmName")) {
                     cb.setText(realmName);
-                }
-                else if (cb.getPrompt().equals("md5a2")) {
+                } else if (cb.getPrompt().equals("md5a2")) {
                     cb.setText(md5a2);
-                }
-                else if (cb.getPrompt().equals("authMethod")) {
+                } else if (cb.getPrompt().equals("authMethod")) {
                     cb.setText(authMethod);
-                }
-                else if (cb.getPrompt().equals("catalinaBase")) {
+                } else if (cb.getPrompt().equals("catalinaBase")) {
                     cb.setText(realm.getContainer().getCatalinaBase().getAbsolutePath());
                 } else {
                     throw new UnsupportedCallbackException(callback);
diff --git a/java/org/apache/catalina/realm/JAASMemoryLoginModule.java b/java/org/apache/catalina/realm/JAASMemoryLoginModule.java
index 99ba3c259a..314a54b92c 100644
--- a/java/org/apache/catalina/realm/JAASMemoryLoginModule.java
+++ b/java/org/apache/catalina/realm/JAASMemoryLoginModule.java
@@ -41,35 +41,30 @@ import org.apache.tomcat.util.IntrospectionUtils;
 import org.apache.tomcat.util.digester.Digester;
 
 /**
- * <p>Implementation of the JAAS <strong>LoginModule</strong> interface,
- * primarily for use in testing <code>JAASRealm</code>.  It utilizes an
- * XML-format data file of username/password/role information identical to
- * that supported by <code>org.apache.catalina.realm.MemoryRealm</code>.</p>
- *
- * <p>This class recognizes the following string-valued options, which are
- * specified in the configuration file and passed to {@link
- * #initialize(Subject, CallbackHandler, Map, Map)} in the <code>options</code>
- * argument:</p>
+ * <p>
+ * Implementation of the JAAS <strong>LoginModule</strong> interface, primarily for use in testing
+ * <code>JAASRealm</code>. It utilizes an XML-format data file of username/password/role information identical to that
+ * supported by <code>org.apache.catalina.realm.MemoryRealm</code>.
+ * </p>
+ * <p>
+ * This class recognizes the following string-valued options, which are specified in the configuration file and passed
+ * to {@link #initialize(Subject, CallbackHandler, Map, Map)} in the <code>options</code> argument:
+ * </p>
  * <ul>
- * <li><strong>pathname</strong> - Relative (to the pathname specified by the
- *     "catalina.base" system property) or absolute pathname to the
- *     XML file containing our user information, in the format supported by
- *     {@link MemoryRealm}.  The default value matches the MemoryRealm
- *     default.</li>
- * <li><strong>credentialHandlerClassName</strong> - The fully qualified class
- *     name of the CredentialHandler to use. If not specified, {@link
- *     MessageDigestCredentialHandler} will be used.</li>
- * <li>Any additional options will be used to identify and call setters on the
- *     {@link CredentialHandler}. For example, <code>algorithm=SHA256</code>
- *     would result in a call to {@link
- *     MessageDigestCredentialHandler#setAlgorithm(String)} with a parameter of
- *     <code>"SHA256"</code></li>
+ * <li><strong>pathname</strong> - Relative (to the pathname specified by the "catalina.base" system property) or
+ * absolute pathname to the XML file containing our user information, in the format supported by {@link MemoryRealm}.
+ * The default value matches the MemoryRealm default.</li>
+ * <li><strong>credentialHandlerClassName</strong> - The fully qualified class name of the CredentialHandler to use. If
+ * not specified, {@link MessageDigestCredentialHandler} will be used.</li>
+ * <li>Any additional options will be used to identify and call setters on the {@link CredentialHandler}. For example,
+ * <code>algorithm=SHA256</code> would result in a call to {@link MessageDigestCredentialHandler#setAlgorithm(String)}
+ * with a parameter of <code>"SHA256"</code></li>
  * </ul>
- *
- * <p><strong>IMPLEMENTATION NOTE</strong> - This class implements
- * <code>Realm</code> only to satisfy the calling requirements of the
- * <code>GenericPrincipal</code> constructor.  It does not actually perform
- * the functionality required of a <code>Realm</code> implementation.</p>
+ * <p>
+ * <strong>IMPLEMENTATION NOTE</strong> - This class implements <code>Realm</code> only to satisfy the calling
+ * requirements of the <code>GenericPrincipal</code> constructor. It does not actually perform the functionality
+ * required of a <code>Realm</code> implementation.
+ * </p>
  *
  * @author Craig R. McClanahan
  */
@@ -96,7 +91,7 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
     /**
      * The configuration information for this <code>LoginModule</code>.
      */
-    protected Map<String,?> options = null;
+    protected Map<String, ?> options = null;
 
 
     /**
@@ -106,17 +101,15 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
 
 
     /**
-     * The <code>Principal</code> identified by our validation, or
-     * <code>null</code> if validation failed.
+     * The <code>Principal</code> identified by our validation, or <code>null</code> if validation failed.
      */
     protected Principal principal = null;
 
 
     /**
-     * The state information that is shared with other configured
-     * <code>LoginModule</code> instances.
+     * The state information that is shared with other configured <code>LoginModule</code> instances.
      */
-    protected Map<String,?> sharedState = null;
+    protected Map<String, ?> sharedState = null;
 
 
     /**
@@ -134,13 +127,11 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
     }
 
     /**
-     * Phase 2 of authenticating a <code>Subject</code> when Phase 1
-     * fails.  This method is called if the <code>LoginContext</code>
-     * failed somewhere in the overall authentication chain.
+     * Phase 2 of authenticating a <code>Subject</code> when Phase 1 fails. This method is called if the
+     * <code>LoginContext</code> failed somewhere in the overall authentication chain.
      *
-     * @return <code>true</code> if this method succeeded, or
-     *  <code>false</code> if this <code>LoginModule</code> should be
-     *  ignored
+     * @return <code>true</code> if this method succeeded, or <code>false</code> if this <code>LoginModule</code> should
+     *             be ignored
      *
      * @exception LoginException if the abort fails
      */
@@ -167,13 +158,11 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
 
 
     /**
-     * Phase 2 of authenticating a <code>Subject</code> when Phase 1
-     * was successful.  This method is called if the <code>LoginContext</code>
-     * succeeded in the overall authentication chain.
+     * Phase 2 of authenticating a <code>Subject</code> when Phase 1 was successful. This method is called if the
+     * <code>LoginContext</code> succeeded in the overall authentication chain.
      *
-     * @return <code>true</code> if the authentication succeeded, or
-     *  <code>false</code> if this <code>LoginModule</code> should be
-     *  ignored
+     * @return <code>true</code> if the authentication succeeded, or <code>false</code> if this <code>LoginModule</code>
+     *             should be ignored
      *
      * @exception LoginException if the commit fails
      */
@@ -208,20 +197,16 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
 
 
     /**
-     * Initialize this <code>LoginModule</code> with the specified
-     * configuration information.
+     * Initialize this <code>LoginModule</code> with the specified configuration information.
      *
-     * @param subject The <code>Subject</code> to be authenticated
-     * @param callbackHandler A <code>CallbackHandler</code> for communicating
-     *  with the end user as necessary
-     * @param sharedState State information shared with other
-     *  <code>LoginModule</code> instances
-     * @param options Configuration information for this specific
-     *  <code>LoginModule</code> instance
+     * @param subject         The <code>Subject</code> to be authenticated
+     * @param callbackHandler A <code>CallbackHandler</code> for communicating with the end user as necessary
+     * @param sharedState     State information shared with other <code>LoginModule</code> instances
+     * @param options         Configuration information for this specific <code>LoginModule</code> instance
      */
     @Override
-    public void initialize(Subject subject, CallbackHandler callbackHandler,
-                           Map<String,?> sharedState, Map<String,?> options) {
+    public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState,
+            Map<String, ?> options) {
         if (log.isDebugEnabled()) {
             log.debug("Init");
         }
@@ -252,7 +237,7 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
             credentialHandler = new MessageDigestCredentialHandler();
         }
 
-        for (Entry<String,?> entry : options.entrySet()) {
+        for (Entry<String, ?> entry : options.entrySet()) {
             if ("pathname".equals(entry.getKey())) {
                 continue;
             }
@@ -262,8 +247,7 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
             // Skip any non-String values since any value we are interested in
             // will be a String.
             if (entry.getValue() instanceof String) {
-                IntrospectionUtils.setProperty(credentialHandler, entry.getKey(),
-                        (String) entry.getValue());
+                IntrospectionUtils.setProperty(credentialHandler, entry.getKey(), (String) entry.getValue());
             }
         }
         setCredentialHandler(credentialHandler);
@@ -276,9 +260,8 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
     /**
      * Phase 1 of authenticating a <code>Subject</code>.
      *
-     * @return <code>true</code> if the authentication succeeded, or
-     *  <code>false</code> if this <code>LoginModule</code> should be
-     *  ignored
+     * @return <code>true</code> if the authentication succeeded, or <code>false</code> if this <code>LoginModule</code>
+     *             should be ignored
      *
      * @exception LoginException if the authentication fails
      */
@@ -313,8 +296,7 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
         try {
             callbackHandler.handle(callbacks);
             username = ((NameCallback) callbacks[0]).getName();
-            password =
-                new String(((PasswordCallback) callbacks[1]).getPassword());
+            password = new String(((PasswordCallback) callbacks[1]).getPassword());
             nonce = ((TextInputCallback) callbacks[2]).getText();
             nc = ((TextInputCallback) callbacks[3]).getText();
             cnonce = ((TextInputCallback) callbacks[4]).getText();
@@ -331,8 +313,7 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
             // BASIC or FORM
             principal = super.authenticate(username, password);
         } else if (authMethod.equals(HttpServletRequest.DIGEST_AUTH)) {
-            principal = super.authenticate(username, password, nonce, nc,
-                    cnonce, qop, realmName, md5a2);
+            principal = super.authenticate(username, password, nonce, nc, cnonce, qop, realmName, md5a2);
         } else if (authMethod.equals(HttpServletRequest.CLIENT_CERT_AUTH)) {
             principal = super.getPrincipal(username);
         } else {
@@ -355,8 +336,7 @@ public class JAASMemoryLoginModule extends MemoryRealm implements LoginModule {
     /**
      * Log out this user.
      *
-     * @return <code>true</code> in all cases because the
-     *  <code>LoginModule</code> should not be ignored
+     * @return <code>true</code> in all cases because the <code>LoginModule</code> should not be ignored
      *
      * @exception LoginException if logging out failed
      */
diff --git a/java/org/apache/catalina/realm/JAASRealm.java b/java/org/apache/catalina/realm/JAASRealm.java
index 1a0c876a76..a24b3d5346 100644
--- a/java/org/apache/catalina/realm/JAASRealm.java
+++ b/java/org/apache/catalina/realm/JAASRealm.java
@@ -42,61 +42,50 @@ import org.apache.juli.logging.LogFactory;
 import org.apache.tomcat.util.ExceptionUtils;
 
 /**
- * <p>Implementation of <b>Realm</b> that authenticates users via the <em>Java
- * Authentication and Authorization Service</em> (JAAS).  JAAS support requires
- * either JDK 1.4 (which includes it as part of the standard platform) or
- * JDK 1.3 (with the plug-in <code>jaas.jar</code> file).</p>
- *
- * <p>The value configured for the <code>appName</code> property is passed to
- * the <code>javax.security.auth.login.LoginContext</code> constructor, to
- * specify the <em>application name</em> used to select the set of relevant
- * <code>LoginModules</code> required.</p>
- *
- * <p>The JAAS Specification describes the result of a successful login as a
- * <code>javax.security.auth.Subject</code> instance, which can contain zero
- * or more <code>java.security.Principal</code> objects in the return value
- * of the <code>Subject.getPrincipals()</code> method.  However, it provides
- * no guidance on how to distinguish Principals that describe the individual
- * user (and are thus appropriate to return as the value of
- * request.getUserPrincipal() in a web application) from the Principal(s)
- * that describe the authorized roles for this user.  To maintain as much
- * independence as possible from the underlying <code>LoginMethod</code>
- * implementation executed by JAAS, the following policy is implemented by
- * this Realm:</p>
+ * <p>
+ * Implementation of <b>Realm</b> that authenticates users via the <em>Java Authentication and Authorization
+ * Service</em> (JAAS). JAAS support requires either JDK 1.4 (which includes it as part of the standard platform) or JDK
+ * 1.3 (with the plug-in <code>jaas.jar</code> file).
+ * </p>
+ * <p>
+ * The value configured for the <code>appName</code> property is passed to the
+ * <code>javax.security.auth.login.LoginContext</code> constructor, to specify the <em>application name</em> used to
+ * select the set of relevant <code>LoginModules</code> required.
+ * </p>
+ * <p>
+ * The JAAS Specification describes the result of a successful login as a <code>javax.security.auth.Subject</code>
+ * instance, which can contain zero or more <code>java.security.Principal</code> objects in the return value of the
+ * <code>Subject.getPrincipals()</code> method. However, it provides no guidance on how to distinguish Principals that
+ * describe the individual user (and are thus appropriate to return as the value of request.getUserPrincipal() in a web
+ * application) from the Principal(s) that describe the authorized roles for this user. To maintain as much independence
+ * as possible from the underlying <code>LoginMethod</code> implementation executed by JAAS, the following policy is
+ * implemented by this Realm:
+ * </p>
  * <ul>
- * <li>The JAAS <code>LoginModule</code> is assumed to return a
- *     <code>Subject</code> with at least one <code>Principal</code> instance
- *     representing the user himself or herself, and zero or more separate
- *     <code>Principals</code> representing the security roles authorized
- *     for this user.</li>
- * <li>On the <code>Principal</code> representing the user, the Principal
- *     name is an appropriate value to return via the Servlet API method
- *     <code>HttpServletRequest.getRemoteUser()</code>.</li>
- * <li>On the <code>Principals</code> representing the security roles, the
- *     name is the name of the authorized security role.</li>
- * <li>This Realm will be configured with two lists of fully qualified Java
- *     class names of classes that implement
- *     <code>java.security.Principal</code> - one that identifies class(es)
- *     representing a user, and one that identifies class(es) representing
- *     a security role.</li>
- * <li>As this Realm iterates over the <code>Principals</code> returned by
- *     <code>Subject.getPrincipals()</code>, it will identify the first
- *     <code>Principal</code> that matches the "user classes" list as the
- *     <code>Principal</code> for this user.</li>
- * <li>As this Realm iterates over the <code>Principals</code> returned by
- *     <code>Subject.getPrincipals()</code>, it will accumulate the set of
- *     all <code>Principals</code> matching the "role classes" list as
- *     identifying the security roles for this user.</li>
- * <li>It is a configuration error for the JAAS login method to return a
- *     validated <code>Subject</code> without a <code>Principal</code> that
- *     matches the "user classes" list.</li>
- * <li>By default, the enclosing Container's name serves as the
- *     application name used to obtain the JAAS LoginContext ("Catalina" in
- *     a default installation). Tomcat must be able to find an application
- *     with this name in the JAAS configuration file. Here is a hypothetical
- *     JAAS configuration file entry for a database-oriented login module that uses
- *     a Tomcat-managed JNDI database resource:
- *     <blockquote><pre>
+ * <li>The JAAS <code>LoginModule</code> is assumed to return a <code>Subject</code> with at least one
+ * <code>Principal</code> instance representing the user himself or herself, and zero or more separate
+ * <code>Principals</code> representing the security roles authorized for this user.</li>
+ * <li>On the <code>Principal</code> representing the user, the Principal name is an appropriate value to return via the
+ * Servlet API method <code>HttpServletRequest.getRemoteUser()</code>.</li>
+ * <li>On the <code>Principals</code> representing the security roles, the name is the name of the authorized security
+ * role.</li>
+ * <li>This Realm will be configured with two lists of fully qualified Java class names of classes that implement
+ * <code>java.security.Principal</code> - one that identifies class(es) representing a user, and one that identifies
+ * class(es) representing a security role.</li>
+ * <li>As this Realm iterates over the <code>Principals</code> returned by <code>Subject.getPrincipals()</code>, it will
+ * identify the first <code>Principal</code> that matches the "user classes" list as the <code>Principal</code> for this
+ * user.</li>
+ * <li>As this Realm iterates over the <code>Principals</code> returned by <code>Subject.getPrincipals()</code>, it will
+ * accumulate the set of all <code>Principals</code> matching the "role classes" list as identifying the security roles
+ * for this user.</li>
+ * <li>It is a configuration error for the JAAS login method to return a validated <code>Subject</code> without a
+ * <code>Principal</code> that matches the "user classes" list.</li>
+ * <li>By default, the enclosing Container's name serves as the application name used to obtain the JAAS LoginContext
+ * ("Catalina" in a default installation). Tomcat must be able to find an application with this name in the JAAS
+ * configuration file. Here is a hypothetical JAAS configuration file entry for a database-oriented login module that
+ * uses a Tomcat-managed JNDI database resource: <blockquote>
+ *
+ * <pre>
  * Catalina {
  * org.foobar.auth.DatabaseLoginModule REQUIRED
  *   JNDI_RESOURCE=jdbc/AuthDB
@@ -108,19 +97,20 @@ import org.apache.tomcat.util.ExceptionUtils;
  *   ROLE_NAME_COLUMN=name
  *   PRINCIPAL_FACTORY=org.foobar.auth.impl.SimplePrincipalFactory;
  * };
- * </pre></blockquote></li>
- * <li>To set the JAAS configuration file
- *     location, set the <code>CATALINA_OPTS</code> environment variable
- *     similar to the following:
- *     <blockquote><code>CATALINA_OPTS="-Djava.security.auth.login.config=$CATALINA_HOME/conf/jaas.config"</code></blockquote>
+ * </pre>
+ *
+ * </blockquote></li>
+ * <li>To set the JAAS configuration file location, set the <code>CATALINA_OPTS</code> environment variable similar to
+ * the following:
+ * <blockquote><code>CATALINA_OPTS="-Djava.security.auth.login.config=$CATALINA_HOME/conf/jaas.config"</code></blockquote>
  * </li>
- * <li>As part of the login process, JAASRealm registers its own <code>CallbackHandler</code>,
- *     called (unsurprisingly) <code>JAASCallbackHandler</code>. This handler supplies the
- *     HTTP requests's username and credentials to the user-supplied <code>LoginModule</code></li>
- * <li>As with other <code>Realm</code> implementations, digested passwords are supported if
- *     the <code>&lt;Realm&gt;</code> element in <code>server.xml</code> contains a
- *     <code>digest</code> attribute; <code>JAASCallbackHandler</code> will digest the password
- *     prior to passing it back to the <code>LoginModule</code></li>
+ * <li>As part of the login process, JAASRealm registers its own <code>CallbackHandler</code>, called (unsurprisingly)
+ * <code>JAASCallbackHandler</code>. This handler supplies the HTTP requests's username and credentials to the
+ * user-supplied <code>LoginModule</code></li>
+ * <li>As with other <code>Realm</code> implementations, digested passwords are supported if the
+ * <code>&lt;Realm&gt;</code> element in <code>server.xml</code> contains a <code>digest</code> attribute;
+ * <code>JAASCallbackHandler</code> will digest the password prior to passing it back to the
+ * <code>LoginModule</code></li>
  * </ul>
  *
  * @author Craig R. McClanahan
@@ -134,8 +124,8 @@ public class JAASRealm extends RealmBase {
 
 
     /**
-     * The application name passed to the JAAS <code>LoginContext</code>,
-     * which uses it to select the set of relevant <code>LoginModule</code>s.
+     * The application name passed to the JAAS <code>LoginContext</code>, which uses it to select the set of relevant
+     * <code>LoginModule</code>s.
      */
     protected String appName = null;
 
@@ -153,16 +143,14 @@ public class JAASRealm extends RealmBase {
 
 
     /**
-     * Whether to use context ClassLoader or default ClassLoader.
-     * True means use context ClassLoader, and True is the default
-     * value.
+     * Whether to use context ClassLoader or default ClassLoader. True means use context ClassLoader, and True is the
+     * default value.
      */
     protected boolean useContextClassLoader = true;
 
 
     /**
-     * Path to find a JAAS configuration file, if not set global JVM JAAS
-     * configuration will be used.
+     * Path to find a JAAS configuration file, if not set global JVM JAAS configuration will be used.
      */
     protected String configFile;
 
@@ -170,11 +158,10 @@ public class JAASRealm extends RealmBase {
     protected volatile boolean jaasConfigurationLoaded = false;
 
     /**
-     * Keeps track if JAAS invocation of login modules was successful or not. By
-     * default it is true unless we detect JAAS login module can't perform the
-     * login. This will be used for realm's {@link #isAvailable()} status so
-     * that {@link LockOutRealm} will not lock the user out if JAAS login
-     * modules are unavailable to perform the actual login.
+     * Keeps track if JAAS invocation of login modules was successful or not. By default it is true unless we detect
+     * JAAS login module can't perform the login. This will be used for realm's {@link #isAvailable()} status so that
+     * {@link LockOutRealm} will not lock the user out if JAAS login modules are unavailable to perform the actual
+     * login.
      */
     private volatile boolean invocationSuccess = true;
 
@@ -189,6 +176,7 @@ public class JAASRealm extends RealmBase {
 
     /**
      * Set the JAAS configuration file.
+     *
      * @param configFile The JAAS configuration file
      */
     public void setConfigFile(String configFile) {
@@ -197,8 +185,8 @@ public class JAASRealm extends RealmBase {
 
     /**
      * Set the JAAS <code>LoginContext</code> app name.
-     * @param name The application name that will be used to retrieve
-     *  the set of relevant <code>LoginModule</code>s
+     *
+     * @param name The application name that will be used to retrieve the set of relevant <code>LoginModule</code>s
      */
     public void setAppName(String name) {
         appName = name;
@@ -212,8 +200,7 @@ public class JAASRealm extends RealmBase {
     }
 
     /**
-     * Sets whether to use the context or default ClassLoader.
-     * True means use context ClassLoader.
+     * Sets whether to use the context or default ClassLoader. True means use context ClassLoader.
      *
      * @param useContext True means use context ClassLoader
      */
@@ -222,8 +209,7 @@ public class JAASRealm extends RealmBase {
     }
 
     /**
-     * Returns whether to use the context or default ClassLoader.
-     * True means to use the context ClassLoader.
+     * Returns whether to use the context or default ClassLoader. True means to use the context ClassLoader.
      *
      * @return The value of useContextClassLoader
      */
@@ -242,8 +228,7 @@ public class JAASRealm extends RealmBase {
     }
 
     /**
-     * Comma-delimited list of <code>java.security.Principal</code> classes
-     * that represent security roles.
+     * Comma-delimited list of <code>java.security.Principal</code> classes that represent security roles.
      */
     protected String roleClassNames = null;
 
@@ -252,10 +237,10 @@ public class JAASRealm extends RealmBase {
     }
 
     /**
-     * Sets the list of comma-delimited classes that represent roles. The
-     * classes in the list must implement <code>java.security.Principal</code>.
-     * The supplied list of classes will be parsed when {@link #start()} is
+     * Sets the list of comma-delimited classes that represent roles. The classes in the list must implement
+     * <code>java.security.Principal</code>. The supplied list of classes will be parsed when {@link #start()} is
      * called.
+     *
      * @param roleClassNames The class names list
      */
     public void setRoleClassNames(String roleClassNames) {
@@ -263,13 +248,12 @@ public class JAASRealm extends RealmBase {
     }
 
     /**
-     * Parses a comma-delimited list of class names, and store the class names
-     * in the provided List. Each class must implement
-     * <code>java.security.Principal</code>.
+     * Parses a comma-delimited list of class names, and store the class names in the provided List. Each class must
+     * implement <code>java.security.Principal</code>.
      *
      * @param classNamesString a comma-delimited list of fully qualified class names.
-     * @param classNamesList the list in which the class names will be stored.
-     *        The list is cleared before being populated.
+     * @param classNamesList   the list in which the class names will be stored. The list is cleared before being
+     *                             populated.
      */
     protected void parseClassNames(String classNamesString, List<String> classNamesList) {
         classNamesList.clear();
@@ -288,8 +272,7 @@ public class JAASRealm extends RealmBase {
                 continue;
             }
             try {
-                Class<?> principalClass = Class.forName(className, false,
-                        loader);
+                Class<?> principalClass = Class.forName(className, false, loader);
                 if (Principal.class.isAssignableFrom(principalClass)) {
                     classNamesList.add(className);
                 } else {
@@ -302,8 +285,7 @@ public class JAASRealm extends RealmBase {
     }
 
     /**
-     * Comma-delimited list of <code>java.security.Principal</code> classes
-     * that represent individual users.
+     * Comma-delimited list of <code>java.security.Principal</code> classes that represent individual users.
      */
     protected String userClassNames = null;
 
@@ -312,10 +294,10 @@ public class JAASRealm extends RealmBase {
     }
 
     /**
-     * Sets the list of comma-delimited classes that represent individual
-     * users. The classes in the list must implement
-     * <code>java.security.Principal</code>. The supplied list of classes will
-     * be parsed when {@link #start()} is called.
+     * Sets the list of comma-delimited classes that represent individual users. The classes in the list must implement
+     * <code>java.security.Principal</code>. The supplied list of classes will be parsed when {@link #start()} is
+     * called.
+     *
      * @param userClassNames The class names list
      */
     public void setUserClassNames(String userClassNames) {
@@ -326,44 +308,40 @@ public class JAASRealm extends RealmBase {
     // --------------------------------------------------------- Public Methods
 
     /**
-     * Return the <code>Principal</code> associated with the specified username
-     * and credentials, if there is one; otherwise return <code>null</code>.
+     * Return the <code>Principal</code> associated with the specified username and credentials, if there is one;
+     * otherwise return <code>null</code>.
+     *
+     * @param username    Username of the <code>Principal</code> to look up
+     * @param credentials Password or other credentials to use in authenticating this username
      *
-     * @param username Username of the <code>Principal</code> to look up
-     * @param credentials Password or other credentials to use in
-     *  authenticating this username
      * @return the associated principal, or <code>null</code> if there is none.
      */
     @Override
     public Principal authenticate(String username, String credentials) {
-        return authenticate(username,
-                new JAASCallbackHandler(this, username, credentials));
+        return authenticate(username, new JAASCallbackHandler(this, username, credentials));
     }
 
 
     /**
-     * Return the <code>Principal</code> associated with the specified username
-     * and digest, if there is one; otherwise return <code>null</code>.
+     * Return the <code>Principal</code> associated with the specified username and digest, if there is one; otherwise
+     * return <code>null</code>.
+     *
+     * @param username     Username of the <code>Principal</code> to look up
+     * @param clientDigest Digest to use in authenticating this username
+     * @param nonce        Server generated nonce
+     * @param nc           Nonce count
+     * @param cnonce       Client generated nonce
+     * @param qop          Quality of protection applied to the message
+     * @param realmName    Realm name
+     * @param md5a2        Second MD5 digest used to calculate the digest MD5(Method + ":" + uri)
      *
-     * @param username      Username of the <code>Principal</code> to look up
-     * @param clientDigest  Digest to use in authenticating this username
-     * @param nonce         Server generated nonce
-     * @param nc            Nonce count
-     * @param cnonce        Client generated nonce
-     * @param qop           Quality of protection applied to the message
-     * @param realmName     Realm name
-     * @param md5a2         Second MD5 digest used to calculate the digest
-     *                          MD5(Method + ":" + uri)
      * @return the associated principal, or <code>null</code> if there is none.
      */
     @Override
-    public Principal authenticate(String username, String clientDigest,
-            String nonce, String nc, String cnonce, String qop,
-            String realmName, String md5a2) {
-        return authenticate(username,
-                new JAASCallbackHandler(this, username, clientDigest, nonce,
-                        nc, cnonce, qop, realmName, md5a2,
-                        HttpServletRequest.DIGEST_AUTH));
+    public Principal authenticate(String username, String clientDigest, String nonce, String nc, String cnonce,
+            String qop, String realmName, String md5a2) {
+        return authenticate(username, new JAASCallbackHandler(this, username, clientDigest, nonce, nc, cnonce, qop,
+                realmName, md5a2, HttpServletRequest.DIGEST_AUTH));
     }
 
 
@@ -375,21 +353,22 @@ public class JAASRealm extends RealmBase {
 
     /**
      * Perform the actual JAAS authentication.
-     * @param username The user name
+     *
+     * @param username        The user name
      * @param callbackHandler The callback handler
+     *
      * @return the associated principal, or <code>null</code> if there is none.
      */
-    protected Principal authenticate(String username,
-            CallbackHandler callbackHandler) {
+    protected Principal authenticate(String username, CallbackHandler callbackHandler) {
 
         // Establish a LoginContext to use for authentication
         try {
             LoginContext loginContext = null;
-            if( appName==null ) {
-                appName="Tomcat";
+            if (appName == null) {
+                appName = "Tomcat";
             }
 
-            if( log.isDebugEnabled()) {
+            if (log.isDebugEnabled()) {
                 log.debug(sm.getString("jaasRealm.beginLogin", username, appName));
             }
 
@@ -398,14 +377,12 @@ public class JAASRealm extends RealmBase {
 
             if (!isUseContextClassLoader()) {
                 ocl = Thread.currentThread().getContextClassLoader();
-                Thread.currentThread().setContextClassLoader(
-                        this.getClass().getClassLoader());
+                Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
             }
 
             try {
                 Configuration config = getConfig();
-                loginContext = new LoginContext(
-                        appName, null, callbackHandler, config);
+                loginContext = new LoginContext(appName, null, callbackHandler, config);
             } catch (Throwable e) {
                 ExceptionUtils.handleThrowable(e);
                 log.error(sm.getString("jaasRealm.unexpectedError"), e);
@@ -414,12 +391,12 @@ public class JAASRealm extends RealmBase {
                 invocationSuccess = false;
                 return null;
             } finally {
-                if(!isUseContextClassLoader()) {
+                if (!isUseContextClassLoader()) {
                     Thread.currentThread().setContextClassLoader(ocl);
                 }
             }
 
-            if( log.isDebugEnabled()) {
+            if (log.isDebugEnabled()) {
                 log.debug("Login context created " + username);
             }
 
@@ -434,7 +411,7 @@ public class JAASRealm extends RealmBase {
                 // of the JAAS operation to keep variable consistent.
                 invocationSuccess = true;
                 if (subject == null) {
-                    if( log.isDebugEnabled()) {
+                    if (log.isDebugEnabled()) {
                         log.debug(sm.getString("jaasRealm.failedLogin", username));
                     }
                     return null;
@@ -478,7 +455,7 @@ public class JAASRealm extends RealmBase {
                 return null;
             }
 
-            if( log.isDebugEnabled()) {
+            if (log.isDebugEnabled()) {
                 log.debug(sm.getString("jaasRealm.loginContextCreated", username));
             }
 
@@ -493,9 +470,9 @@ public class JAASRealm extends RealmBase {
             }
 
             return principal;
-        } catch( Throwable t) {
-            log.error( "error ", t);
-            //JAAS throws exception different than LoginException so mark the realm as unavailable
+        } catch (Throwable t) {
+            log.error("error ", t);
+            // JAAS throws exception different than LoginException so mark the realm as unavailable
             invocationSuccess = false;
             return null;
         }
@@ -503,9 +480,8 @@ public class JAASRealm extends RealmBase {
 
 
     /**
-     * @return the password associated with the given principal's user name. This
-     * always returns null as the JAASRealm has no way of obtaining this
-     * information.
+     * @return the password associated with the given principal's user name. This always returns null as the JAASRealm
+     *             has no way of obtaining this information.
      */
     @Override
     protected String getPassword(String username) {
@@ -519,31 +495,27 @@ public class JAASRealm extends RealmBase {
     @Override
     protected Principal getPrincipal(String username) {
 
-        return authenticate(username,
-                new JAASCallbackHandler(this, username, null, null, null, null,
-                        null, null, null, HttpServletRequest.CLIENT_CERT_AUTH));
+        return authenticate(username, new JAASCallbackHandler(this, username, null, null, null, null, null, null, null,
+                HttpServletRequest.CLIENT_CERT_AUTH));
 
     }
 
 
     /**
-     * Identify and return a <code>java.security.Principal</code> instance
-     * representing the authenticated user for the specified <code>Subject</code>.
-     * The Principal is constructed by scanning the list of Principals returned
-     * by the JAASLoginModule. The first <code>Principal</code> object that matches
-     * one of the class names supplied as a "user class" is the user Principal.
-     * This object is returned to the caller.
-     * Any remaining principal objects returned by the LoginModules are mapped to
-     * roles, but only if their respective classes match one of the "role class" classes.
+     * Identify and return a <code>java.security.Principal</code> instance representing the authenticated user for the
+     * specified <code>Subject</code>. The Principal is constructed by scanning the list of Principals returned by the
+     * JAASLoginModule. The first <code>Principal</code> object that matches one of the class names supplied as a "user
+     * class" is the user Principal. This object is returned to the caller. Any remaining principal objects returned by
+     * the LoginModules are mapped to roles, but only if their respective classes match one of the "role class" classes.
      * If a user Principal cannot be constructed, return <code>null</code>.
-     * @param username The associated user name
-     * @param subject The <code>Subject</code> representing the logged-in user
-     * @param loginContext Associated with the Principal so
-     *                     {@link LoginContext#logout()} can be called later
+     *
+     * @param username     The associated user name
+     * @param subject      The <code>Subject</code> representing the logged-in user
+     * @param loginContext Associated with the Principal so {@link LoginContext#logout()} can be called later
+     *
      * @return the principal object
      */
-    protected Principal createPrincipal(String username, Subject subject,
-            LoginContext loginContext) {
+    protected Principal createPrincipal(String username, Subject subject, LoginContext loginContext) {
         // Prepare to scan the Principals for this Subject
 
         List<String> roles = new ArrayList<>();
@@ -553,20 +525,20 @@ public class JAASRealm extends RealmBase {
         for (Principal principal : subject.getPrincipals()) {
             String principalClass = principal.getClass().getName();
 
-            if( log.isDebugEnabled() ) {
+            if (log.isDebugEnabled()) {
                 log.debug(sm.getString("jaasRealm.checkPrincipal", principal, principalClass));
             }
 
             if (userPrincipal == null && userClasses.contains(principalClass)) {
                 userPrincipal = principal;
-                if( log.isDebugEnabled() ) {
+                if (log.isDebugEnabled()) {
                     log.debug(sm.getString("jaasRealm.userPrincipalSuccess", principal.getName()));
                 }
             }
 
             if (roleClasses.contains(principalClass)) {
                 roles.add(principal.getName());
-                if( log.isDebugEnabled() ) {
+                if (log.isDebugEnabled()) {
                     log.debug(sm.getString("jaasRealm.rolePrincipalAdd", principal.getName()));
                 }
             }
@@ -588,30 +560,28 @@ public class JAASRealm extends RealmBase {
         }
 
         // Return the resulting Principal for our authenticated user
-        return new GenericPrincipal(username, null, roles, userPrincipal,
-                loginContext);
+        return new GenericPrincipal(username, null, roles, userPrincipal, loginContext);
     }
 
     /**
-     * Ensure the given name is legal for JAAS configuration.
-     * Added for Bugzilla 30869, made protected for easy customization
-     * in case my implementation is insufficient, which I think is
-     * very likely.
+     * Ensure the given name is legal for JAAS configuration. Added for Bugzilla 30869, made protected for easy
+     * customization in case my implementation is insufficient, which I think is very likely.
      *
      * @param src The name to validate
+     *
      * @return A string that's a valid JAAS realm name
      */
     protected String makeLegalForJAAS(final String src) {
         String result = src;
 
         // Default name is "other" per JAAS spec
-        if(result == null) {
+        if (result == null) {
             result = "other";
         }
 
         // Strip leading slash if present, as Sun JAAS impl
         // barfs on it (see Bugzilla 30869 bug report).
-        if(result.startsWith("/")) {
+        if (result.startsWith("/")) {
             result = result.substring(1);
         }
 
@@ -623,12 +593,11 @@ public class JAASRealm extends RealmBase {
 
 
     /**
-     * Prepare for the beginning of active use of the public methods of this
-     * component and implement the requirements of
+     * Prepare for the beginning of active use of the public methods of this component and implement the requirements of
      * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
      *
-     * @exception LifecycleException if this component detects a fatal error
-     *  that prevents this component from being used
+     * @exception LifecycleException if this component detects a fatal error that prevents this component from being
+     *                                   used
      */
     @Override
     protected void startInternal() throws LifecycleException {
@@ -644,6 +613,7 @@ public class JAASRealm extends RealmBase {
 
     /**
      * Load custom JAAS Configuration.
+     *
      * @return the loaded configuration
      */
     protected Configuration getConfig() {
@@ -661,10 +631,9 @@ public class JAASRealm extends RealmBase {
                 URL resource = Thread.currentThread().getContextClassLoader().getResource(configFile);
                 URI uri = resource.toURI();
                 @SuppressWarnings("unchecked")
-                Class<Configuration> sunConfigFile = (Class<Configuration>)
-                Class.forName("com.sun.security.auth.login.ConfigFile");
-                Constructor<Configuration> constructor =
-                        sunConfigFile.getConstructor(URI.class);
+                Class<Configuration> sunConfigFile = (Class<Configuration>) Class
+                        .forName("com.sun.security.auth.login.ConfigFile");
+                Constructor<Configuration> constructor = sunConfigFile.getConstructor(URI.class);
                 Configuration config = constructor.newInstance(uri);
                 this.jaasConfiguration = config;
                 this.jaasConfigurationLoaded = true;
@@ -672,8 +641,7 @@ public class JAASRealm extends RealmBase {
             }
         } catch (InvocationTargetException ex) {
             throw new RuntimeException(ex.getCause());
-        } catch (SecurityException | URISyntaxException | ReflectiveOperationException |
-                IllegalArgumentException ex) {
+        } catch (SecurityException | URISyntaxException | ReflectiveOperationException | IllegalArgumentException ex) {
             throw new RuntimeException(ex);
         }
     }
diff --git a/java/org/apache/catalina/realm/JDBCRealm.java b/java/org/apache/catalina/realm/JDBCRealm.java
index 8ea0a1f3f3..7019946724 100644
--- a/java/org/apache/catalina/realm/JDBCRealm.java
+++ b/java/org/apache/catalina/realm/JDBCRealm.java
@@ -31,26 +31,22 @@ import org.apache.tomcat.util.ExceptionUtils;
 
 
 /**
- * Implementation of <b>Realm</b> that works with any JDBC supported database.
- * See the JDBCRealm.howto for more details on how to set up the database and
- * for configuration options.
- *
- * <p>For a <b>Realm</b> implementation that supports connection pooling and
- * doesn't require synchronisation of <code>authenticate()</code>,
- * <code>getPassword()</code>, <code>roles()</code> and
- * <code>getPrincipal()</code> or the ugly connection logic use the
- * <code>DataSourceRealm</code>.</p>
+ * Implementation of <b>Realm</b> that works with any JDBC supported database. See the JDBCRealm.howto for more details
+ * on how to set up the database and for configuration options.
+ * <p>
+ * For a <b>Realm</b> implementation that supports connection pooling and doesn't require synchronisation of
+ * <code>authenticate()</code>, <code>getPassword()</code>, <code>roles()</code> and <code>getPrincipal()</code> or the
+ * ugly connection logic use the <code>DataSourceRealm</code>.
+ * </p>
  *
  * @author Craig R. McClanahan
  * @author Carson McDonald
  * @author Ignacio Ortega
  *
- * @deprecated Will be removed in Tomcat 10 onwards. Use the DataSourceRealm
- *             instead.
+ * @deprecated Will be removed in Tomcat 10 onwards. Use the DataSourceRealm instead.
  */
 @Deprecated
-public class JDBCRealm
-    extends RealmBase {
+public class JDBCRealm extends RealmBase {
 
 
     // ----------------------------------------------------- Instance Variables
@@ -99,8 +95,7 @@ public class JDBCRealm
 
 
     /**
-     * The PreparedStatement to use for identifying the roles for
-     * a specified user.
+     * The PreparedStatement to use for identifying the roles for a specified user.
      */
     protected PreparedStatement preparedRoles = null;
 
@@ -181,8 +176,8 @@ public class JDBCRealm
      *
      * @param connectionURL The new connection URL
      */
-    public void setConnectionURL( String connectionURL ) {
-      this.connectionURL = connectionURL;
+    public void setConnectionURL(String connectionURL) {
+        this.connectionURL = connectionURL;
     }
 
     /**
@@ -197,8 +192,8 @@ public class JDBCRealm
      *
      * @param driverName The driver name
      */
-    public void setDriverName( String driverName ) {
-      this.driverName = driverName;
+    public void setDriverName(String driverName) {
+        this.driverName = driverName;
     }
 
     /**
@@ -213,7 +208,7 @@ public class JDBCRealm
      *
      * @param roleNameCol The column name
      */
-    public void setRoleNameCol( String roleNameCol ) {
+    public void setRoleNameCol(String roleNameCol) {
         this.roleNameCol = roleNameCol;
     }
 
@@ -229,8 +224,8 @@ public class JDBCRealm
      *
      * @param userCredCol The column name
      */
-    public void setUserCredCol( String userCredCol ) {
-       this.userCredCol = userCredCol;
+    public void setUserCredCol(String userCredCol) {
+        this.userCredCol = userCredCol;
     }
 
     /**
@@ -245,8 +240,8 @@ public class JDBCRealm
      *
      * @param userNameCol The column name
      */
-    public void setUserNameCol( String userNameCol ) {
-       this.userNameCol = userNameCol;
+    public void setUserNameCol(String userNameCol) {
+        this.userNameCol = userNameCol;
     }
 
     /**
@@ -261,7 +256,7 @@ public class JDBCRealm
      *
      * @param userRoleTable The table name
      */
-    public void setUserRoleTable( String userRoleTable ) {
+    public void setUserRoleTable(String userRoleTable) {
         this.userRoleTable = userRoleTable;
     }
 
@@ -277,26 +272,22 @@ public class JDBCRealm
      *
      * @param userTable The table name
      */
-    public void setUserTable( String userTable ) {
-      this.userTable = userTable;
+    public void setUserTable(String userTable) {
+        this.userTable = userTable;
     }
 
 
     // --------------------------------------------------------- Public Methods
 
     /**
-     * Return the Principal associated with the specified username and
-     * credentials, if there is one; otherwise return <code>null</code>.
-     *
-     * If there are any errors with the JDBC connection, executing
-     * the query or anything we return null (don't authenticate). This
-     * event is also logged, and the connection will be closed so that
-     * a subsequent request will automatically re-open it.
+     * Return the Principal associated with the specified username and credentials, if there is one; otherwise return
+     * <code>null</code>. If there are any errors with the JDBC connection, executing the query or anything we return
+     * null (don't authenticate). This event is also logged, and the connection will be closed so that a subsequent
+     * request will automatically re-open it.
      *
+     * @param username    Username of the Principal to look up
+     * @param credentials Password or other credentials to use in authenticating this username
      *
-     * @param username Username of the Principal to look up
-     * @param credentials Password or other credentials to use in
-     *  authenticating this username
      * @return the associated principal, or <code>null</code> if there is none.
      */
     @Override
@@ -311,15 +302,14 @@ public class JDBCRealm
         // connection may try to be opened again. On normal conditions (including
         // invalid login - the above is only used once.
         int numberOfTries = 2;
-        while (numberOfTries>0) {
+        while (numberOfTries > 0) {
             try {
 
                 // Ensure that we have an open database connection
                 open();
 
                 // Acquire a Principal object for this user
-                Principal principal = authenticate(dbConnection,
-                                                   username, credentials);
+                Principal principal = authenticate(dbConnection, username, credentials);
 
 
                 // Return the Principal (if any)
@@ -356,22 +346,18 @@ public class JDBCRealm
      * Attempt to authenticate the user with the provided credentials.
      *
      * @param dbConnection The database connection to be used
-     * @param username Username of the Principal to look up
-     * @param credentials Password or other credentials to use in authenticating
-     *                    this username
+     * @param username     Username of the Principal to look up
+     * @param credentials  Password or other credentials to use in authenticating this username
      *
-     * @return Return the Principal associated with the specified username and
-     *         credentials, if there is one; otherwise return <code>null</code>.
+     * @return Return the Principal associated with the specified username and credentials, if there is one; otherwise
+     *             return <code>null</code>.
      */
-    public synchronized Principal authenticate(Connection dbConnection,
-                                               String username,
-                                               String credentials) {
+    public synchronized Principal authenticate(Connection dbConnection, String username, String credentials) {
         // No user or no credentials
         // Can't possibly authenticate, don't bother the database then
         if (username == null || credentials == null) {
             if (containerLog.isTraceEnabled()) {
-                containerLog.trace(sm.getString("jdbcRealm.authenticateFailure",
-                                                username));
+                containerLog.trace(sm.getString("jdbcRealm.authenticateFailure", username));
             }
             return null;
         }
@@ -385,8 +371,7 @@ public class JDBCRealm
             getCredentialHandler().mutate(credentials);
 
             if (containerLog.isTraceEnabled()) {
-                containerLog.trace(sm.getString("jdbcRealm.authenticateFailure",
-                                                username));
+                containerLog.trace(sm.getString("jdbcRealm.authenticateFailure", username));
             }
             return null;
         }
@@ -396,13 +381,11 @@ public class JDBCRealm
 
         if (validated) {
             if (containerLog.isTraceEnabled()) {
-                containerLog.trace(sm.getString("jdbcRealm.authenticateSuccess",
-                                                username));
+                containerLog.trace(sm.getString("jdbcRealm.authenticateSuccess", username));
             }
         } else {
             if (containerLog.isTraceEnabled()) {
-                containerLog.trace(sm.getString("jdbcRealm.authenticateFailure",
-                                                username));
+                containerLog.trace(sm.getString("jdbcRealm.authenticateFailure", username));
             }
             return null;
         }
@@ -455,23 +438,24 @@ public class JDBCRealm
         } catch (SQLException e) {
             containerLog.warn(sm.getString("jdbcRealm.close"), e); // Just log it here
         } finally {
-           this.dbConnection = null;
+            this.dbConnection = null;
         }
 
     }
 
 
     /**
-     * Return a PreparedStatement configured to perform the SELECT required
-     * to retrieve user credentials for the specified username.
+     * Return a PreparedStatement configured to perform the SELECT required to retrieve user credentials for the
+     * specified username.
      *
      * @param dbConnection The database connection to be used
-     * @param username Username for which credentials should be retrieved
+     * @param username     Username for which credentials should be retrieved
+     *
      * @return the prepared statement
+     *
      * @exception SQLException if a database error occurs
      */
-    protected PreparedStatement credentials(Connection dbConnection, String username)
-            throws SQLException {
+    protected PreparedStatement credentials(Connection dbConnection, String username) throws SQLException {
 
         if (preparedCredentials == null) {
             StringBuilder sb = new StringBuilder("SELECT ");
@@ -482,16 +466,15 @@ public class JDBCRealm
             sb.append(userNameCol);
             sb.append(" = ?");
 
-            if(containerLog.isDebugEnabled()) {
+            if (containerLog.isDebugEnabled()) {
                 containerLog.debug("credentials query: " + sb.toString());
             }
 
-            preparedCredentials =
-                dbConnection.prepareStatement(sb.toString());
+            preparedCredentials = dbConnection.prepareStatement(sb.toString());
         }
 
         if (username == null) {
-            preparedCredentials.setNull(1,java.sql.Types.VARCHAR);
+            preparedCredentials.setNull(1, java.sql.Types.VARCHAR);
         } else {
             preparedCredentials.setString(1, username);
         }
@@ -502,7 +485,9 @@ public class JDBCRealm
 
     /**
      * Get the password for the specified user.
+     *
      * @param username The user name
+     *
      * @return the password associated with the given principal's user name.
      */
     @Override
@@ -557,22 +542,24 @@ public class JDBCRealm
 
     /**
      * Get the principal associated with the specified user.
+     *
      * @param username The user name
+     *
      * @return the Principal associated with the given user name.
      */
     @Override
     protected synchronized Principal getPrincipal(String username) {
 
-        return new GenericPrincipal(username,
-                                     getPassword(username),
-                                     getRoles(username));
+        return new GenericPrincipal(username, getPassword(username), getRoles(username));
 
     }
 
 
     /**
      * Return the roles associated with the given user name.
+     *
      * @param username The user name
+     *
      * @return an array list of the role names
      */
     protected ArrayList<String> getRoles(String username) {
@@ -592,7 +579,7 @@ public class JDBCRealm
         // connection may try to be opened again. On normal conditions (including
         // invalid login - the above is only used once.
         int numberOfTries = 2;
-        while (numberOfTries>0) {
+        while (numberOfTries > 0) {
             try {
                 // Ensure that we have an open database connection
                 open();
@@ -604,7 +591,7 @@ public class JDBCRealm
 
                     while (rs.next()) {
                         String role = rs.getString(1);
-                        if (null!=role) {
+                        if (null != role) {
                             roleList.add(role.trim());
                         }
                     }
@@ -631,9 +618,10 @@ public class JDBCRealm
 
 
     /**
-     * Open (if necessary) and return a database connection for use by
-     * this Realm.
+     * Open (if necessary) and return a database connection for use by this Realm.
+     *
      * @return the opened connection
+     *
      * @exception SQLException if a database error occurs
      */
     protected Connection open() throws SQLException {
@@ -664,8 +652,7 @@ public class JDBCRealm
         }
         dbConnection = driver.connect(connectionURL, props);
         if (dbConnection == null) {
-            throw new SQLException(sm.getString(
-                    "jdbcRealm.open.invalidurl",driverName, connectionURL));
+            throw new SQLException(sm.getString("jdbcRealm.open.invalidurl", driverName, connectionURL));
         }
         dbConnection.setAutoCommit(false);
         return dbConnection;
@@ -674,16 +661,17 @@ public class JDBCRealm
 
 
     /**
-     * Return a PreparedStatement configured to perform the SELECT required
-     * to retrieve user roles for the specified username.
+     * Return a PreparedStatement configured to perform the SELECT required to retrieve user roles for the specified
+     * username.
      *
      * @param dbConnection The database connection to be used
-     * @param username Username for which roles should be retrieved
+     * @param username     Username for which roles should be retrieved
+     *
      * @return the prepared statement
+     *
      * @exception SQLException if a database error occurs
      */
-    protected synchronized PreparedStatement roles(Connection dbConnection, String username)
-            throws SQLException {
+    protected synchronized PreparedStatement roles(Connection dbConnection, String username) throws SQLException {
 
         if (preparedRoles == null) {
             StringBuilder sb = new StringBuilder("SELECT ");
@@ -710,12 +698,11 @@ public class JDBCRealm
     // ------------------------------------------------------ Lifecycle Methods
 
     /**
-     * Prepare for the beginning of active use of the public methods of this
-     * component and implement the requirements of
+     * Prepare for the beginning of active use of the public methods of this component and implement the requirements of
      * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
      *
-     * @exception LifecycleException if this component detects a fatal error
-     *  that prevents this component from being used
+     * @exception LifecycleException if this component detects a fatal error that prevents this component from being
+     *                                   used
      */
     @Override
     protected void startInternal() throws LifecycleException {
@@ -733,14 +720,12 @@ public class JDBCRealm
 
 
     /**
-     * Gracefully terminate the active use of the public methods of this
-     * component and implement the requirements of
+     * Gracefully terminate the active use of the public methods of this component and implement the requirements of
      * {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
      *
-     * @exception LifecycleException if this component detects a fatal error
-     *  that needs to be reported
+     * @exception LifecycleException if this component detects a fatal error that needs to be reported
      */
-     @Override
+    @Override
     protected void stopInternal() throws LifecycleException {
 
         super.stopInternal();
diff --git a/java/org/apache/catalina/realm/JNDIRealm.java b/java/org/apache/catalina/realm/JNDIRealm.java
index f885be0f01..0ac18ce0da 100644
--- a/java/org/apache/catalina/realm/JNDIRealm.java
+++ b/java/org/apache/catalina/realm/JNDIRealm.java
@@ -70,113 +70,76 @@ import org.ietf.jgss.GSSCredential;
 import org.ietf.jgss.GSSName;
 
 /**
- * <p>Implementation of <strong>Realm</strong> that works with a directory
- * server accessed via the Java Naming and Directory Interface (JNDI) APIs.
- * The following constraints are imposed on the data structure in the
- * underlying directory server:</p>
+ * <p>
+ * Implementation of <strong>Realm</strong> that works with a directory server accessed via the Java Naming and
+ * Directory Interface (JNDI) APIs. The following constraints are imposed on the data structure in the underlying
+ * directory server:
+ * </p>
  * <ul>
- *
- * <li>Each user that can be authenticated is represented by an individual
- *     element in the top level <code>DirContext</code> that is accessed
- *     via the <code>connectionURL</code> property.</li>
- *
- * <li>If a socket connection cannot be made to the <code>connectURL</code>
- *     an attempt will be made to use the <code>alternateURL</code> if it
- *     exists.</li>
- *
- * <li>Each user element has a distinguished name that can be formed by
- *     substituting the presented username into a pattern configured by the
- *     <code>userPattern</code> property.</li>
- *
- * <li>Alternatively, if the <code>userPattern</code> property is not
- *     specified, a unique element can be located by searching the directory
- *     context. In this case:
- *     <ul>
- *     <li>The <code>userSearch</code> pattern specifies the search filter
- *         after substitution of the username.</li>
- *     <li>The <code>userBase</code> property can be set to the element that
- *         is the base of the subtree containing users.  If not specified,
- *         the search base is the top-level context.</li>
- *     <li>The <code>userSubtree</code> property can be set to
- *         <code>true</code> if you wish to search the entire subtree of the
- *         directory context.  The default value of <code>false</code>
- *         requests a search of only the current level.</li>
- *    </ul>
+ * <li>Each user that can be authenticated is represented by an individual element in the top level
+ * <code>DirContext</code> that is accessed via the <code>connectionURL</code> property.</li>
+ * <li>If a socket connection cannot be made to the <code>connectURL</code> an attempt will be made to use the
+ * <code>alternateURL</code> if it exists.</li>
+ * <li>Each user element has a distinguished name that can be formed by substituting the presented username into a
+ * pattern configured by the <code>userPattern</code> property.</li>
+ * <li>Alternatively, if the <code>userPattern</code> property is not specified, a unique element can be located by
+ * searching the directory context. In this case:
+ * <ul>
+ * <li>The <code>userSearch</code> pattern specifies the search filter after substitution of the username.</li>
+ * <li>The <code>userBase</code> property can be set to the element that is the base of the subtree containing users. If
+ * not specified, the search base is the top-level context.</li>
+ * <li>The <code>userSubtree</code> property can be set to <code>true</code> if you wish to search the entire subtree of
+ * the directory context. The default value of <code>false</code> requests a search of only the current level.</li>
+ * </ul>
  * </li>
- *
- * <li>The user may be authenticated by binding to the directory with the
- *      username and password presented. This method is used when the
- *      <code>userPassword</code> property is not specified.</li>
- *
- * <li>The user may be authenticated by retrieving the value of an attribute
- *     from the directory and comparing it explicitly with the value presented
- *     by the user. This method is used when the <code>userPassword</code>
- *     property is specified, in which case:
- *     <ul>
- *     <li>The element for this user must contain an attribute named by the
- *         <code>userPassword</code> property.
- *     <li>The value of the user password attribute is either a cleartext
- *         String, or the result of passing a cleartext String through the
- *         <code>RealmBase.digest()</code> method (using the standard digest
- *         support included in <code>RealmBase</code>).
- *     <li>The user is considered to be authenticated if the presented
- *         credentials (after being passed through
- *         <code>RealmBase.digest()</code>) are equal to the retrieved value
- *         for the user password attribute.</li>
- *     </ul></li>
- *
- * <li>Each group of users that has been assigned a particular role may be
- *     represented by an individual element in the top level
- *     <code>DirContext</code> that is accessed via the
- *     <code>connectionURL</code> property.  This element has the following
- *     characteristics:
- *     <ul>
- *     <li>The set of all possible groups of interest can be selected by a
- *         search pattern configured by the <code>roleSearch</code>
- *         property.</li>
- *     <li>The <code>roleSearch</code> pattern optionally includes pattern
- *         replacements "{0}" for the distinguished name, and/or "{1}" for
- *         the username, and/or "{2}" the value of an attribute from the
- *         user's directory entry (the attribute is specified by the
- *         <code>userRoleAttribute</code> property), of the authenticated user
- *         for which roles will be retrieved.</li>
- *     <li>The <code>roleBase</code> property can be set to the element that
- *         is the base of the search for matching roles.  If not specified,
- *         the entire context will be searched.</li>
- *     <li>The <code>roleSubtree</code> property can be set to
- *         <code>true</code> if you wish to search the entire subtree of the
- *         directory context.  The default value of <code>false</code>
- *         requests a search of only the current level.</li>
- *     <li>The element includes an attribute (whose name is configured by
- *         the <code>roleName</code> property) containing the name of the
- *         role represented by this element.</li>
- *     </ul></li>
- *
- * <li>In addition, roles may be represented by the values of an attribute
- * in the user's element whose name is configured by the
- * <code>userRoleName</code> property.</li>
- *
- * <li>A default role can be assigned to each user that was successfully
- * authenticated by setting the <code>commonRole</code> property to the
- * name of this role. The role doesn't have to exist in the directory.</li>
- *
- * <li>If the directory server contains nested roles, you can search for them
- * by setting <code>roleNested</code> to <code>true</code>.
- * The default value is <code>false</code>, so role searches will not find
- * nested roles.</li>
- *
- * <li>Note that the standard <code>&lt;security-role-ref&gt;</code> element in
- *     the web application deployment descriptor allows applications to refer
- *     to roles programmatically by names other than those used in the
- *     directory server itself.</li>
+ * <li>The user may be authenticated by binding to the directory with the username and password presented. This method
+ * is used when the <code>userPassword</code> property is not specified.</li>
+ * <li>The user may be authenticated by retrieving the value of an attribute from the directory and comparing it
+ * explicitly with the value presented by the user. This method is used when the <code>userPassword</code> property is
+ * specified, in which case:
+ * <ul>
+ * <li>The element for this user must contain an attribute named by the <code>userPassword</code> property.
+ * <li>The value of the user password attribute is either a cleartext String, or the result of passing a cleartext
+ * String through the <code>RealmBase.digest()</code> method (using the standard digest support included in
+ * <code>RealmBase</code>).
+ * <li>The user is considered to be authenticated if the presented credentials (after being passed through
+ * <code>RealmBase.digest()</code>) are equal to the retrieved value for the user password attribute.</li>
  * </ul>
- *
- * <p><strong>WARNING</strong> - There is a reported bug against the Netscape
- * provider code (com.netscape.jndi.ldap.LdapContextFactory) with respect to
- * successfully authenticated a non-existing user. The
- * report is here: https://bz.apache.org/bugzilla/show_bug.cgi?id=11210 .
- * With luck, Netscape has updated their provider code and this is not an
- * issue. </p>
+ * </li>
+ * <li>Each group of users that has been assigned a particular role may be represented by an individual element in the
+ * top level <code>DirContext</code> that is accessed via the <code>connectionURL</code> property. This element has the
+ * following characteristics:
+ * <ul>
+ * <li>The set of all possible groups of interest can be selected by a search pattern configured by the
+ * <code>roleSearch</code> property.</li>
+ * <li>The <code>roleSearch</code> pattern optionally includes pattern replacements "{0}" for the distinguished name,
+ * and/or "{1}" for the username, and/or "{2}" the value of an attribute from the user's directory entry (the attribute
+ * is specified by the <code>userRoleAttribute</code> property), of the authenticated user for which roles will be
+ * retrieved.</li>
+ * <li>The <code>roleBase</code> property can be set to the element that is the base of the search for matching roles.
+ * If not specified, the entire context will be searched.</li>
+ * <li>The <code>roleSubtree</code> property can be set to <code>true</code> if you wish to search the entire subtree of
+ * the directory context. The default value of <code>false</code> requests a search of only the current level.</li>
+ * <li>The element includes an attribute (whose name is configured by the <code>roleName</code> property) containing the
+ * name of the role represented by this element.</li>
+ * </ul>
+ * </li>
+ * <li>In addition, roles may be represented by the values of an attribute in the user's element whose name is
+ * configured by the <code>userRoleName</code> property.</li>
+ * <li>A default role can be assigned to each user that was successfully authenticated by setting the
+ * <code>commonRole</code> property to the name of this role. The role doesn't have to exist in the directory.</li>
+ * <li>If the directory server contains nested roles, you can search for them by setting <code>roleNested</code> to
+ * <code>true</code>. The default value is <code>false</code>, so role searches will not find nested roles.</li>
+ * <li>Note that the standard <code>&lt;security-role-ref&gt;</code> element in the web application deployment
+ * descriptor allows applications to refer to roles programmatically by names other than those used in the directory
+ * server itself.</li>
+ * </ul>
+ * <p>
+ * <strong>WARNING</strong> - There is a reported bug against the Netscape provider code
+ * (com.netscape.jndi.ldap.LdapContextFactory) with respect to successfully authenticated a non-existing user. The
+ * report is here: https://bz.apache.org/bugzilla/show_bug.cgi?id=11210 . With luck, Netscape has updated their provider
+ * code and this is not an issue.
+ * </p>
  *
  * @author John Holman
  * @author Craig R. McClanahan
@@ -186,7 +149,7 @@ public class JNDIRealm extends RealmBase {
     // ----------------------------------------------------- Instance Variables
 
     /**
-     *  The type of authentication to use
+     * The type of authentication to use
      */
     protected String authentication = null;
 
@@ -206,9 +169,8 @@ public class JNDIRealm extends RealmBase {
     protected String connectionURL = null;
 
     /**
-     * The JNDI context factory used to acquire our InitialContext.  By
-     * default, assumes use of an LDAP server using the standard JNDI LDAP
-     * provider.
+     * The JNDI context factory used to acquire our InitialContext. By default, assumes use of an LDAP server using the
+     * standard JNDI LDAP provider.
      */
     protected String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
 
@@ -218,31 +180,27 @@ public class JNDIRealm extends RealmBase {
     protected String derefAliases = null;
 
     /**
-     * Constant that holds the name of the environment property for specifying
-     * the manner in which aliases should be dereferenced.
+     * Constant that holds the name of the environment property for specifying the manner in which aliases should be
+     * dereferenced.
      */
     public static final String DEREF_ALIASES = "java.naming.ldap.derefAliases";
 
     /**
-     * The protocol that will be used in the communication with the
-     * directory server.
+     * The protocol that will be used in the communication with the directory server.
      */
     protected String protocol = null;
 
     /**
-     * Should we ignore PartialResultExceptions when iterating over NamingEnumerations?
-     * Microsoft Active Directory often returns referrals, which lead
-     * to PartialResultExceptions. Unfortunately there's no stable way to detect,
-     * if the Exceptions really come from an AD referral.
-     * Set to true to ignore PartialResultExceptions.
+     * Should we ignore PartialResultExceptions when iterating over NamingEnumerations? Microsoft Active Directory often
+     * returns referrals, which lead to PartialResultExceptions. Unfortunately there's no stable way to detect, if the
+     * Exceptions really come from an AD referral. Set to true to ignore PartialResultExceptions.
      */
     protected boolean adCompat = false;
 
     /**
-     * How should we handle referrals?  Microsoft Active Directory often returns
-     * referrals. If you need to follow them set referrals to "follow".
-     * Caution: if your DNS is not part of AD, the LDAP client lib might try
-     * to resolve your domain name in DNS to find another LDAP server.
+     * How should we handle referrals? Microsoft Active Directory often returns referrals. If you need to follow them
+     * set referrals to "follow". Caution: if your DNS is not part of AD, the LDAP client lib might try to resolve your
+     * domain name in DNS to find another LDAP server.
      */
     protected String referrals = null;
 
@@ -252,16 +210,14 @@ public class JNDIRealm extends RealmBase {
     protected String userBase = "";
 
     /**
-     * The message format used to search for a user, with "{0}" marking
-     * the spot where the username goes.
+     * The message format used to search for a user, with "{0}" marking the spot where the username goes.
      */
     protected String userSearch = null;
 
     /**
-     * When searching for users, should the search be performed as the user
-     * currently being authenticated? If false, {@link #connectionName} and
-     * {@link #connectionPassword} will be used if specified, else an anonymous
-     * connection will be used.
+     * When searching for users, should the search be performed as the user currently being authenticated? If false,
+     * {@link #connectionName} and {@link #connectionPassword} will be used if specified, else an anonymous connection
+     * will be used.
      */
     private boolean userSearchAsUser = false;
 
@@ -276,27 +232,21 @@ public class JNDIRealm extends RealmBase {
     protected String userPassword = null;
 
     /**
-     * The name of the attribute inside the users
-     * directory entry where the value will be
-     * taken to search for roles
-     * This attribute is not used during a nested search
+     * The name of the attribute inside the users directory entry where the value will be taken to search for roles This
+     * attribute is not used during a nested search
      */
     protected String userRoleAttribute = null;
 
     /**
-     * A string of LDAP user patterns or paths, ":"-separated
-     * These will be used to form the distinguished name of a
-     * user, with "{0}" marking the spot where the specified username
-     * goes.
-     * This is similar to userPattern, but allows for multiple searches
-     * for a user.
+     * A string of LDAP user patterns or paths, ":"-separated These will be used to form the distinguished name of a
+     * user, with "{0}" marking the spot where the specified username goes. This is similar to userPattern, but allows
+     * for multiple searches for a user.
      */
     protected String[] userPatternArray = null;
 
     /**
-     * The message format used to form the distinguished name of a
-     * user, with "{0}" marking the spot where the specified username
-     * goes.
+     * The message format used to form the distinguished name of a user, with "{0}" marking the spot where the specified
+     * username goes.
      */
     protected String userPattern = null;
 
@@ -306,8 +256,7 @@ public class JNDIRealm extends RealmBase {
     protected String roleBase = "";
 
     /**
-     * The name of an attribute in the user's entry containing
-     * roles for that user
+     * The name of an attribute in the user's entry containing roles for that user
      */
     protected String userRoleName = null;
 
@@ -317,9 +266,8 @@ public class JNDIRealm extends RealmBase {
     protected String roleName = null;
 
     /**
-     * The message format used to select roles for a user, with "{0}" marking
-     * the spot where the distinguished name of the user goes. The "{1}"
-     * and "{2}" are described in the Configuration Reference.
+     * The message format used to select roles for a user, with "{0}" marking the spot where the distinguished name of
+     * the user goes. The "{1}" and "{2}" are described in the Configuration Reference.
      */
     protected String roleSearch = null;
 
@@ -334,9 +282,8 @@ public class JNDIRealm extends RealmBase {
     protected boolean roleNested = false;
 
     /**
-     * When searching for user roles, should the search be performed as the user
-     * currently being authenticated? If false, {@link #connectionName} and
-     * {@link #connectionPassword} will be used if specified, else an anonymous
+     * When searching for user roles, should the search be performed as the user currently being authenticated? If
+     * false, {@link #connectionName} and {@link #connectionPassword} will be used if specified, else an anonymous
      * connection will be used.
      */
     protected boolean roleSearchAsUser = false;
@@ -347,51 +294,46 @@ public class JNDIRealm extends RealmBase {
     protected String alternateURL;
 
     /**
-     * The number of connection attempts.  If greater than zero we use the
-     * alternate url.
+     * The number of connection attempts. If greater than zero we use the alternate url.
      */
     protected int connectionAttempt = 0;
 
     /**
-     *  Add this role to every authenticated user
+     * Add this role to every authenticated user
      */
     protected String commonRole = null;
 
     /**
-     * The timeout, in milliseconds, to use when trying to create a connection
-     * to the directory. The default is 5000 (5 seconds).
+     * The timeout, in milliseconds, to use when trying to create a connection to the directory. The default is 5000 (5
+     * seconds).
      */
     protected String connectionTimeout = "5000";
 
     /**
-     * The timeout, in milliseconds, to use when trying to read from a connection
-     * to the directory. The default is 5000 (5 seconds).
+     * The timeout, in milliseconds, to use when trying to read from a connection to the directory. The default is 5000
+     * (5 seconds).
      */
     protected String readTimeout = "5000";
 
     /**
-     * The sizeLimit (also known as the countLimit) to use when the realm is
-     * configured with {@link #userSearch}. Zero for no limit.
+     * The sizeLimit (also known as the countLimit) to use when the realm is configured with {@link #userSearch}. Zero
+     * for no limit.
      */
     protected long sizeLimit = 0;
 
     /**
-     * The timeLimit (in milliseconds) to use when the realm is configured with
-     * {@link #userSearch}. Zero for no limit.
+     * The timeLimit (in milliseconds) to use when the realm is configured with {@link #userSearch}. Zero for no limit.
      */
     protected int timeLimit = 0;
 
     /**
-     * Should delegated credentials from the SPNEGO authenticator be used if
-     * available
+     * Should delegated credentials from the SPNEGO authenticator be used if available
      */
     protected boolean useDelegatedCredential = true;
 
     /**
-     * The QOP that should be used for the connection to the LDAP server after
-     * authentication. This value is used to set the
-     * <code>javax.security.sasl.qop</code> environment property for the LDAP
-     * connection.
+     * The QOP that should be used for the connection to the LDAP server after authentication. This value is used to set
+     * the <code>javax.security.sasl.qop</code> environment property for the LDAP connection.
      */
     protected String spnegoDelegationQop = "auth-conf";
 
@@ -403,14 +345,13 @@ public class JNDIRealm extends RealmBase {
     private StartTlsResponse tls = null;
 
     /**
-     * The list of enabled cipher suites used for establishing tls connections.
-     * <code>null</code> means to use the default cipher suites.
+     * The list of enabled cipher suites used for establishing tls connections. <code>null</code> means to use the
+     * default cipher suites.
      */
     private String[] cipherSuitesArray = null;
 
     /**
-     * Verifier for hostnames in a StartTLS secured connection. <code>null</code>
-     * means to use the default verifier.
+     * Verifier for hostnames in a StartTLS secured connection. <code>null</code> means to use the default verifier.
      */
     private HostnameVerifier hostnameVerifier = null;
 
@@ -420,20 +361,17 @@ public class JNDIRealm extends RealmBase {
     private SSLSocketFactory sslSocketFactory = null;
 
     /**
-     * Name of the class of the {@link SSLSocketFactory}. <code>null</code>
-     * means to use the default factory.
+     * Name of the class of the {@link SSLSocketFactory}. <code>null</code> means to use the default factory.
      */
     private String sslSocketFactoryClassName;
 
     /**
-     * Comma separated list of cipher suites to use for StartTLS. If empty, the
-     * default suites are used.
+     * Comma separated list of cipher suites to use for StartTLS. If empty, the default suites are used.
      */
     private String cipherSuites;
 
     /**
-     * Name of the class of the {@link HostnameVerifier}. <code>null</code>
-     * means to use the default verifier.
+     * Name of the class of the {@link HostnameVerifier}. <code>null</code> means to use the default verifier.
      */
     private String hostNameVerifierClassName;
 
@@ -465,9 +403,8 @@ public class JNDIRealm extends RealmBase {
     protected int connectionPoolSize = 1;
 
     /**
-     * Whether to use context ClassLoader or default ClassLoader.
-     * True means use context ClassLoader, and True is the default
-     * value.
+     * Whether to use context ClassLoader or default ClassLoader. True means use context ClassLoader, and True is the
+     * default value.
      */
     protected boolean useContextClassLoader = true;
 
@@ -613,17 +550,17 @@ public class JNDIRealm extends RealmBase {
     /**
      * @return the current settings for handling PartialResultExceptions
      */
-    public boolean getAdCompat () {
+    public boolean getAdCompat() {
         return adCompat;
     }
 
 
     /**
-     * How do we handle PartialResultExceptions?
-     * True: ignore all PartialResultExceptions.
+     * How do we handle PartialResultExceptions? True: ignore all PartialResultExceptions.
+     *
      * @param adCompat <code>true</code> to ignore partial results
      */
-    public void setAdCompat (boolean adCompat) {
+    public void setAdCompat(boolean adCompat) {
         this.adCompat = adCompat;
     }
 
@@ -631,17 +568,18 @@ public class JNDIRealm extends RealmBase {
     /**
      * @return the current settings for handling JNDI referrals.
      */
-    public String getReferrals () {
+    public String getReferrals() {
         return referrals;
     }
 
 
     /**
-     * How do we handle JNDI referrals? ignore, follow, or throw
-     * (see javax.naming.Context.REFERRAL for more information).
+     * How do we handle JNDI referrals? ignore, follow, or throw (see javax.naming.Context.REFERRAL for more
+     * information).
+     *
      * @param referrals The referral handling
      */
-    public void setReferrals (String referrals) {
+    public void setReferrals(String referrals) {
         this.referrals = referrals;
     }
 
@@ -867,12 +805,10 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Set the message format pattern for selecting users in this Realm.
-     * This may be one simple pattern, or multiple patterns to be tried,
-     * separated by parentheses. (for example, either "cn={0}", or
-     * "(cn={0})(cn={0},o=myorg)" Full LDAP search strings are also supported,
-     * but only the "OR", "|" syntax, so "(|(cn={0})(cn={0},o=myorg))" is
-     * also valid. Complex search strings with &amp;, etc are NOT supported.
+     * Set the message format pattern for selecting users in this Realm. This may be one simple pattern, or multiple
+     * patterns to be tried, separated by parentheses. (for example, either "cn={0}", or "(cn={0})(cn={0},o=myorg)" Full
+     * LDAP search strings are also supported, but only the "OR", "|" syntax, so "(|(cn={0})(cn={0},o=myorg))" is also
+     * valid. Complex search strings with &amp;, etc are NOT supported.
      *
      * @param userPattern The new user pattern
      */
@@ -1012,9 +948,7 @@ public class JNDIRealm extends RealmBase {
     /**
      * Flag whether StartTLS should be used when connecting to the ldap server
      *
-     * @param useStartTls
-     *            {@code true} when StartTLS should be used. Default is
-     *            {@code false}.
+     * @param useStartTls {@code true} when StartTLS should be used. Default is {@code false}.
      */
     public void setUseStartTls(boolean useStartTls) {
         this.useStartTls = useStartTls;
@@ -1022,8 +956,7 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * @return list of the allowed cipher suites when connections are made using
-     *         StartTLS
+     * @return list of the allowed cipher suites when connections are made using StartTLS
      */
     private String[] getCipherSuitesArray() {
         if (cipherSuites == null || cipherSuitesArray != null) {
@@ -1034,19 +967,17 @@ public class JNDIRealm extends RealmBase {
             this.cipherSuitesArray = null;
         } else {
             this.cipherSuitesArray = cipherSuites.trim().split("\\s*,\\s*");
-            containerLog.debug(sm.getString("jndiRealm.cipherSuites",
-                    Arrays.toString(this.cipherSuitesArray)));
+            containerLog.debug(sm.getString("jndiRealm.cipherSuites", Arrays.toString(this.cipherSuitesArray)));
         }
         return this.cipherSuitesArray;
     }
 
 
     /**
-     * Set the allowed cipher suites when opening a connection using StartTLS.
-     * The cipher suites are expected as a comma separated list.
+     * Set the allowed cipher suites when opening a connection using StartTLS. The cipher suites are expected as a comma
+     * separated list.
      *
-     * @param suites
-     *            comma separated list of allowed cipher suites
+     * @param suites comma separated list of allowed cipher suites
      */
     public void setCipherSuites(String suites) {
         this.cipherSuites = suites;
@@ -1054,8 +985,7 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * @return the connection pool size, or the default value 1 if pooling
-     *   is disabled
+     * @return the connection pool size, or the default value 1 if pooling is disabled
      */
     public int getConnectionPoolSize() {
         return connectionPoolSize;
@@ -1064,6 +994,7 @@ public class JNDIRealm extends RealmBase {
 
     /**
      * Set the connection pool size
+     *
      * @param connectionPoolSize the new pool size
      */
     public void setConnectionPoolSize(int connectionPoolSize) {
@@ -1072,9 +1003,8 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * @return name of the {@link HostnameVerifier} class used for connections
-     *         using StartTLS, or the empty string, if the default verifier
-     *         should be used.
+     * @return name of the {@link HostnameVerifier} class used for connections using StartTLS, or the empty string, if
+     *             the default verifier should be used.
      */
     public String getHostnameVerifierClassName() {
         if (this.hostnameVerifier == null) {
@@ -1085,12 +1015,10 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Set the {@link HostnameVerifier} to be used when opening connections
-     * using StartTLS. An instance of the given class name will be constructed
-     * using the default constructor.
+     * Set the {@link HostnameVerifier} to be used when opening connections using StartTLS. An instance of the given
+     * class name will be constructed using the default constructor.
      *
-     * @param verifierClassName
-     *            class name of the {@link HostnameVerifier} to be constructed
+     * @param verifierClassName class name of the {@link HostnameVerifier} to be constructed
      */
     public void setHostnameVerifierClassName(String verifierClassName) {
         if (verifierClassName != null) {
@@ -1102,8 +1030,8 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * @return the {@link HostnameVerifier} to use for peer certificate
-     *         verification when opening connections using StartTLS.
+     * @return the {@link HostnameVerifier} to use for peer certificate verification when opening connections using
+     *             StartTLS.
      */
     public HostnameVerifier getHostnameVerifier() {
         if (this.hostnameVerifier != null) {
@@ -1118,26 +1046,22 @@ public class JNDIRealm extends RealmBase {
                 this.hostnameVerifier = (HostnameVerifier) o;
                 return this.hostnameVerifier;
             } else {
-                throw new IllegalArgumentException(sm.getString(
-                        "jndiRealm.invalidHostnameVerifier",
-                        hostNameVerifierClassName));
+                throw new IllegalArgumentException(
+                        sm.getString("jndiRealm.invalidHostnameVerifier", hostNameVerifierClassName));
             }
         } catch (ReflectiveOperationException | SecurityException e) {
-            throw new IllegalArgumentException(sm.getString(
-                    "jndiRealm.invalidHostnameVerifier",
-                    hostNameVerifierClassName), e);
+            throw new IllegalArgumentException(
+                    sm.getString("jndiRealm.invalidHostnameVerifier", hostNameVerifierClassName), e);
         }
     }
 
 
     /**
-     * Set the {@link SSLSocketFactory} to be used when opening connections
-     * using StartTLS. An instance of the factory with the given name will be
-     * created using the default constructor. The SSLSocketFactory can also be
-     * set using {@link JNDIRealm#setSslProtocol(String) setSslProtocol(String)}.
+     * Set the {@link SSLSocketFactory} to be used when opening connections using StartTLS. An instance of the factory
+     * with the given name will be created using the default constructor. The SSLSocketFactory can also be set using
+     * {@link JNDIRealm#setSslProtocol(String) setSslProtocol(String)}.
      *
-     * @param factoryClassName
-     *            class name of the factory to be constructed
+     * @param factoryClassName class name of the factory to be constructed
      */
     public void setSslSocketFactoryClassName(String factoryClassName) {
         this.sslSocketFactoryClassName = factoryClassName;
@@ -1147,8 +1071,7 @@ public class JNDIRealm extends RealmBase {
     /**
      * Set the ssl protocol to be used for connections using StartTLS.
      *
-     * @param protocol
-     *            one of the allowed ssl protocol names
+     * @param protocol one of the allowed ssl protocol names
      */
     public void setSslProtocol(String protocol) {
         this.sslProtocol = protocol;
@@ -1156,8 +1079,7 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * @return the list of supported ssl protocols by the default
-     *         {@link SSLContext}
+     * @return the list of supported ssl protocols by the default {@link SSLContext}
      */
     private String[] getSupportedSslProtocols() {
         try {
@@ -1169,16 +1091,14 @@ public class JNDIRealm extends RealmBase {
     }
 
 
-    private Object constructInstance(String className)
-            throws ReflectiveOperationException {
+    private Object constructInstance(String className) throws ReflectiveOperationException {
         Class<?> clazz = Class.forName(className);
         return clazz.getConstructor().newInstance();
     }
 
 
     /**
-     * Sets whether to use the context or default ClassLoader.
-     * True means use context ClassLoader.
+     * Sets whether to use the context or default ClassLoader. True means use context ClassLoader.
      *
      * @param useContext True means use context ClassLoader
      */
@@ -1188,8 +1108,7 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Returns whether to use the context or default ClassLoader.
-     * True means to use the context ClassLoader.
+     * Returns whether to use the context or default ClassLoader. True means to use the context ClassLoader.
      *
      * @return The value of useContextClassLoader
      */
@@ -1201,17 +1120,14 @@ public class JNDIRealm extends RealmBase {
     // ---------------------------------------------------------- Realm Methods
 
     /**
-     * Return the Principal associated with the specified username and
-     * credentials, if there is one; otherwise return <code>null</code>.
+     * Return the Principal associated with the specified username and credentials, if there is one; otherwise return
+     * <code>null</code>. If there are any errors with the JDBC connection, executing the query or anything we return
+     * null (don't authenticate). This event is also logged, and the connection will be closed so that a subsequent
+     * request will automatically re-open it.
      *
-     * If there are any errors with the JDBC connection, executing
-     * the query or anything we return null (don't authenticate). This
-     * event is also logged, and the connection will be closed so that
-     * a subsequent request will automatically re-open it.
+     * @param username    Username of the Principal to look up
+     * @param credentials Password or other credentials to use in authenticating this username
      *
-     * @param username Username of the Principal to look up
-     * @param credentials Password or other credentials to use in
-     *  authenticating this username
      * @return the associated principal, or <code>null</code> if there is none.
      */
     @Override
@@ -1236,7 +1152,7 @@ public class JNDIRealm extends RealmBase {
 
             try {
 
-                // Occasionally the directory context will timeout.  Try one more
+                // Occasionally the directory context will timeout. Try one more
                 // time before giving up.
 
                 // Authenticate the specified username if possible
@@ -1244,18 +1160,14 @@ public class JNDIRealm extends RealmBase {
 
             } catch (NullPointerException | NamingException e) {
                 /*
-                 * BZ 61313
-                 * NamingException may or may not indicate an error that is
-                 * recoverable via fail over. Therefore a decision needs to be
-                 * made whether to fail over or not. Generally, attempting to
-                 * fail over when it is not appropriate is better than not
-                 * failing over when it is appropriate so the code always
+                 * BZ 61313 NamingException may or may not indicate an error that is recoverable via fail over.
+                 * Therefore a decision needs to be made whether to fail over or not. Generally, attempting to fail over
+                 * when it is not appropriate is better than not failing over when it is appropriate so the code always
                  * attempts to fail over for NamingExceptions.
                  */
 
                 /*
-                 * BZ 42449
-                 * Catch NPE - Kludge Sun's LDAP provider with broken SSL.
+                 * BZ 42449 Catch NPE - Kludge Sun's LDAP provider with broken SSL.
                  */
 
                 // log the exception so we know it's there.
@@ -1302,13 +1214,13 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Return the Principal associated with the specified username and
-     * credentials, if there is one; otherwise return <code>null</code>.
+     * Return the Principal associated with the specified username and credentials, if there is one; otherwise return
+     * <code>null</code>.
+     *
+     * @param connection  The directory context
+     * @param username    Username of the Principal to look up
+     * @param credentials Password or other credentials to use in authenticating this username
      *
-     * @param connection The directory context
-     * @param username Username of the Principal to look up
-     * @param credentials Password or other credentials to use in
-     *  authenticating this username
      * @return the associated principal, or <code>null</code> if there is none.
      *
      * @exception NamingException if a directory server error occurs
@@ -1390,10 +1302,8 @@ public class JNDIRealm extends RealmBase {
 
 
     /*
-     * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553
-     * This method can be removed and the class loader switch moved back to
-     * open() once it is known that Tomcat must be running on a JVM that
-     * includes a fix for
+     * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553 This method can be removed and the class loader switch moved
+     * back to open() once it is known that Tomcat must be running on a JVM that includes a fix for
      * https://bugs.openjdk.java.net/browse/JDK-8273874
      */
     @Override
@@ -1414,15 +1324,13 @@ public class JNDIRealm extends RealmBase {
 
 
     /*
-     * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553
-     * This method can be removed and the class loader switch moved back to
-     * open() once it is known that Tomcat must be running on a JVM that
-     * includes a fix for
+     * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553 This method can be removed and the class loader switch moved
+     * back to open() once it is known that Tomcat must be running on a JVM that includes a fix for
      * https://bugs.openjdk.java.net/browse/JDK-8273874
      */
     @Override
-    public Principal authenticate(String username, String clientDigest, String nonce, String nc,
-            String cnonce, String qop, String realm, String md5a2) {
+    public Principal authenticate(String username, String clientDigest, String nonce, String nc, String cnonce,
+            String qop, String realm, String md5a2) {
         ClassLoader ocl = null;
         try {
             if (!isUseContextClassLoader()) {
@@ -1439,10 +1347,8 @@ public class JNDIRealm extends RealmBase {
 
 
     /*
-     * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553
-     * This method can be removed and the class loader switch moved back to
-     * open() once it is known that Tomcat must be running on a JVM that
-     * includes a fix for
+     * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553 This method can be removed and the class loader switch moved
+     * back to open() once it is known that Tomcat must be running on a JVM that includes a fix for
      * https://bugs.openjdk.java.net/browse/JDK-8273874
      */
     @Override
@@ -1463,10 +1369,8 @@ public class JNDIRealm extends RealmBase {
 
 
     /*
-     * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553
-     * This method can be removed and the class loader switch moved back to
-     * open() once it is known that Tomcat must be running on a JVM that
-     * includes a fix for
+     * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553 This method can be removed and the class loader switch moved
+     * back to open() once it is known that Tomcat must be running on a JVM that includes a fix for
      * https://bugs.openjdk.java.net/browse/JDK-8273874
      */
     @Override
@@ -1487,10 +1391,8 @@ public class JNDIRealm extends RealmBase {
 
 
     /*
-     * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553
-     * This method can be removed and the class loader switch moved back to
-     * open() once it is known that Tomcat must be running on a JVM that
-     * includes a fix for
+     * https://bz.apache.org/bugzilla/show_bug.cgi?id=65553 This method can be removed and the class loader switch moved
+     * back to open() once it is known that Tomcat must be running on a JVM that includes a fix for
      * https://bugs.openjdk.java.net/browse/JDK-8273874
      */
     @Override
@@ -1513,13 +1415,14 @@ public class JNDIRealm extends RealmBase {
     // ------------------------------------------------------ Protected Methods
 
     /**
-     * Return a User object containing information about the user
-     * with the specified username, if found in the directory;
-     * otherwise return <code>null</code>.
+     * Return a User object containing information about the user with the specified username, if found in the
+     * directory; otherwise return <code>null</code>.
      *
      * @param connection The directory context
-     * @param username Username to be looked up
+     * @param username   Username to be looked up
+     *
      * @return the User object
+     *
      * @exception NamingException if a directory server error occurs
      *
      * @see #getUser(JNDIConnection, String, String, int)
@@ -1530,14 +1433,15 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Return a User object containing information about the user
-     * with the specified username, if found in the directory;
-     * otherwise return <code>null</code>.
+     * Return a User object containing information about the user with the specified username, if found in the
+     * directory; otherwise return <code>null</code>.
      *
-     * @param connection The directory context
-     * @param username Username to be looked up
+     * @param connection  The directory context
+     * @param username    Username to be looked up
      * @param credentials User credentials (optional)
+     *
      * @return the User object
+     *
      * @exception NamingException if a directory server error occurs
      *
      * @see #getUser(JNDIConnection, String, String, int)
@@ -1548,21 +1452,19 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Return a User object containing information about the user
-     * with the specified username, if found in the directory;
-     * otherwise return <code>null</code>.
+     * Return a User object containing information about the user with the specified username, if found in the
+     * directory; otherwise return <code>null</code>. If the <code>userPassword</code> configuration attribute is
+     * specified, the value of that attribute is retrieved from the user's directory entry. If the
+     * <code>userRoleName</code> configuration attribute is specified, all values of that attribute are retrieved from
+     * the directory entry.
      *
-     * If the <code>userPassword</code> configuration attribute is
-     * specified, the value of that attribute is retrieved from the
-     * user's directory entry. If the <code>userRoleName</code>
-     * configuration attribute is specified, all values of that
-     * attribute are retrieved from the directory entry.
-     *
-     * @param connection The directory context
-     * @param username Username to be looked up
-     * @param credentials User credentials (optional)
+     * @param connection     The directory context
+     * @param username       Username to be looked up
+     * @param credentials    User credentials (optional)
      * @param curUserPattern Index into userPatternFormatArray
+     *
      * @return the User object
+     *
      * @exception NamingException if a directory server error occurs
      */
     protected User getUser(JNDIConnection connection, String username, String credentials, int curUserPattern)
@@ -1616,16 +1518,16 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Use the distinguished name to locate the directory
-     * entry for the user with the specified username and
-     * return a User object; otherwise return <code>null</code>.
+     * Use the distinguished name to locate the directory entry for the user with the specified username and return a
+     * User object; otherwise return <code>null</code>.
      *
-     * @param context The directory context
+     * @param context  The directory context
      * @param username The username
-     * @param attrIds String[]containing names of attributes to
-     * @param dn Distinguished name of the user
-     * retrieve.
+     * @param attrIds  String[]containing names of attributes to
+     * @param dn       Distinguished name of the user retrieve.
+     *
      * @return the User object
+     *
      * @exception NamingException if a directory server error occurs
      */
     protected User getUserByPattern(DirContext context, String username, String[] attrIds, String dn)
@@ -1633,7 +1535,7 @@ public class JNDIRealm extends RealmBase {
 
         // If no attributes are requested, no need to look for them
         if (attrIds == null || attrIds.length == 0) {
-            return new User(username, dn, null, null,null);
+            return new User(username, dn, null, null, null);
         }
 
         // Get required attributes from user entry
@@ -1669,18 +1571,19 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Use the <code>UserPattern</code> configuration attribute to
-     * locate the directory entry for the user with the specified
-     * username and return a User object; otherwise return
-     * <code>null</code>.
+     * Use the <code>UserPattern</code> configuration attribute to locate the directory entry for the user with the
+     * specified username and return a User object; otherwise return <code>null</code>.
      *
-     * @param connection The directory context
-     * @param username The username
-     * @param credentials User credentials (optional)
-     * @param attrIds String[]containing names of attributes to
+     * @param connection     The directory context
+     * @param username       The username
+     * @param credentials    User credentials (optional)
+     * @param attrIds        String[]containing names of attributes to
      * @param curUserPattern Index into userPatternFormatArray
+     *
      * @return the User object
+     *
      * @exception NamingException if a directory server error occurs
+     *
      * @see #getUserByPattern(DirContext, String, String[], String)
      */
     protected User getUserByPattern(JNDIConnection connection, String username, String credentials, String[] attrIds,
@@ -1695,8 +1598,8 @@ public class JNDIRealm extends RealmBase {
         // Form the DistinguishedName from the user pattern.
         // Escape in case username contains a character with special meaning in
         // an attribute value.
-        String dn = connection.userPatternFormatArray[curUserPattern].format(
-                new String[] { doAttributeValueEscaping(username) });
+        String dn = connection.userPatternFormatArray[curUserPattern]
+                .format(new String[] { doAttributeValueEscaping(username) });
 
         try {
             user = getUserByPattern(connection.context, username, attrIds, dn);
@@ -1718,14 +1621,15 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Search the directory to return a User object containing
-     * information about the user with the specified username, if
-     * found in the directory; otherwise return <code>null</code>.
+     * Search the directory to return a User object containing information about the user with the specified username,
+     * if found in the directory; otherwise return <code>null</code>.
      *
      * @param connection The directory context
-     * @param username The username
-     * @param attrIds String[]containing names of attributes to retrieve.
+     * @param username   The username
+     * @param attrIds    String[]containing names of attributes to retrieve.
+     *
      * @return the User object
+     *
      * @exception NamingException if a directory server error occurs
      */
     protected User getUserBySearch(JNDIConnection connection, String username, String[] attrIds)
@@ -1830,18 +1734,17 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Check whether the given User can be authenticated with the
-     * given credentials. If the <code>userPassword</code>
-     * configuration attribute is specified, the credentials
-     * previously retrieved from the directory are compared explicitly
-     * with those presented by the user. Otherwise the presented
-     * credentials are checked by binding to the directory as the
-     * user.
+     * Check whether the given User can be authenticated with the given credentials. If the <code>userPassword</code>
+     * configuration attribute is specified, the credentials previously retrieved from the directory are compared
+     * explicitly with those presented by the user. Otherwise the presented credentials are checked by binding to the
+     * directory as the user.
      *
-     * @param context The directory context
-     * @param user The User to be authenticated
+     * @param context     The directory context
+     * @param user        The User to be authenticated
      * @param credentials The credentials presented by the user
+     *
      * @return <code>true</code> if the credentials are validated
+     *
      * @exception NamingException if a directory server error occurs
      */
     protected boolean checkCredentials(DirContext context, User user, String credentials) throws NamingException {
@@ -1866,13 +1769,14 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Check whether the credentials presented by the user match those
-     * retrieved from the directory.
+     * Check whether the credentials presented by the user match those retrieved from the directory.
      *
-     * @param context The directory context
-     * @param info The User to be authenticated
+     * @param context     The directory context
+     * @param info        The User to be authenticated
      * @param credentials Authentication credentials
+     *
      * @return <code>true</code> if the credentials are validated
+     *
      * @exception NamingException if a directory server error occurs
      */
     protected boolean compareCredentials(DirContext context, User info, String credentials) throws NamingException {
@@ -1894,10 +1798,12 @@ public class JNDIRealm extends RealmBase {
     /**
      * Check credentials by binding to the directory as the user
      *
-     * @param context The directory context
-     * @param user The User to be authenticated
+     * @param context     The directory context
+     * @param user        The User to be authenticated
      * @param credentials Authentication credentials
+     *
      * @return <code>true</code> if the credentials are validated
+     *
      * @exception NamingException if a directory server error occurs
      */
     protected boolean bindAsUser(DirContext context, User user, String credentials) throws NamingException {
@@ -1924,12 +1830,11 @@ public class JNDIRealm extends RealmBase {
         boolean validated = false;
         try {
             if (containerLog.isTraceEnabled()) {
-                containerLog.trace("  binding as "  + dn);
+                containerLog.trace("  binding as " + dn);
             }
             context.getAttributes("", null);
             validated = true;
-        }
-        catch (AuthenticationException e) {
+        } catch (AuthenticationException e) {
             if (containerLog.isTraceEnabled()) {
                 containerLog.trace("  bind attempt failed");
             }
@@ -1942,12 +1847,12 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Configure the context to use the provided credentials for
-     * authentication.
+     * Configure the context to use the provided credentials for authentication.
+     *
+     * @param context     DirContext to configure
+     * @param dn          Distinguished name of user
+     * @param credentials Credentials of user
      *
-     * @param context      DirContext to configure
-     * @param dn           Distinguished name of user
-     * @param credentials  Credentials of user
      * @exception NamingException if a directory server error occurs
      */
     private void userCredentialsAdd(DirContext context, String dn, String credentials) throws NamingException {
@@ -1958,11 +1863,11 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Configure the context to use {@link #connectionName} and
-     * {@link #connectionPassword} if specified or an anonymous connection if
-     * those attributes are not specified.
+     * Configure the context to use {@link #connectionName} and {@link #connectionPassword} if specified or an anonymous
+     * connection if those attributes are not specified.
+     *
+     * @param context DirContext to configure
      *
-     * @param context      DirContext to configure
      * @exception NamingException if a directory server error occurs
      */
     private void userCredentialsRemove(DirContext context) throws NamingException {
@@ -1982,14 +1887,14 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Return a List of roles associated with the given User.  Any
-     * roles present in the user's directory entry are supplemented by
-     * a directory search. If no roles are associated with this user,
-     * a zero-length List is returned.
+     * Return a List of roles associated with the given User. Any roles present in the user's directory entry are
+     * supplemented by a directory search. If no roles are associated with this user, a zero-length List is returned.
      *
      * @param connection The directory context we are searching
-     * @param user The User to be checked
+     * @param user       The User to be checked
+     *
      * @return the list of role names
+     *
      * @exception NamingException if a directory server error occurs
      */
     protected List<String> getRoles(JNDIConnection connection, User user) throws NamingException {
@@ -2037,17 +1942,16 @@ public class JNDIRealm extends RealmBase {
         // Set up parameters for an appropriate search filter
         // The dn is already attribute value escaped but the others are not
         // This is a filter so all input will require filter escaping
-        String filter = connection.roleFormat.format(new String[] {
-                doFilterEscaping(dn),
-                doFilterEscaping(doAttributeValueEscaping(username)),
-                doFilterEscaping(doAttributeValueEscaping(userRoleId)) });
+        String filter = connection.roleFormat
+                .format(new String[] { doFilterEscaping(dn), doFilterEscaping(doAttributeValueEscaping(username)),
+                        doFilterEscaping(doAttributeValueEscaping(userRoleId)) });
         SearchControls controls = new SearchControls();
         if (roleSubtree) {
             controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
         } else {
             controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
         }
-        controls.setReturningAttributes(new String[] {roleName});
+        controls.setReturningAttributes(new String[] { roleName });
 
         String base = null;
         if (connection.roleBaseFormat != null) {
@@ -2057,7 +1961,7 @@ public class JNDIRealm extends RealmBase {
             for (int i = 0; i < name.size(); i++) {
                 // May have been returned with \<char> escaping rather than
                 // \<hex><hex>. Make sure it is \<hex><hex>.
-                nameParts[i] =  convertToHexEscape(name.get(i));
+                nameParts[i] = convertToHexEscape(name.get(i));
             }
             base = connection.roleBaseFormat.format(nameParts);
         } else {
@@ -2069,7 +1973,7 @@ public class JNDIRealm extends RealmBase {
                 isRoleSearchAsUser());
 
         if (results == null) {
-            return list;  // Should never happen, but just in case ...
+            return list; // Should never happen, but just in case ...
         }
 
         Map<String, String> groupMap = new HashMap<>();
@@ -2098,7 +2002,7 @@ public class JNDIRealm extends RealmBase {
             Set<Entry<String, String>> entries = groupMap.entrySet();
             containerLog.trace("  Found " + entries.size() + " direct roles");
             for (Entry<String, String> entry : entries) {
-                containerLog.trace(  "  Found direct role " + entry.getKey() + " -> " + entry.getValue());
+                containerLog.trace("  Found direct role " + entry.getKey() + " -> " + entry.getValue());
             }
         }
 
@@ -2117,14 +2021,13 @@ public class JNDIRealm extends RealmBase {
                     // Group key is already value escaped if required
                     // Group value is not value escaped
                     // Everything needs to be filter escaped
-                    filter = connection.roleFormat.format(new String[] {
-                            doFilterEscaping(group.getKey()),
+                    filter = connection.roleFormat.format(new String[] { doFilterEscaping(group.getKey()),
                             doFilterEscaping(doAttributeValueEscaping(group.getValue())),
                             doFilterEscaping(doAttributeValueEscaping(group.getValue())) });
 
                     if (containerLog.isTraceEnabled()) {
-                        containerLog.trace("Perform a nested group search with base "+ roleBase +
-                                " and filter " + filter);
+                        containerLog
+                                .trace("Perform a nested group search with base " + roleBase + " and filter " + filter);
                     }
 
                     results = searchAsUser(connection.context, user, base, filter, controls, isRoleSearchAsUser());
@@ -2166,26 +2069,20 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Perform the search on the context as the {@code dn}, when
-     * {@code searchAsUser} is {@code true}, otherwise search the context with
-     * the default credentials.
+     * Perform the search on the context as the {@code dn}, when {@code searchAsUser} is {@code true}, otherwise search
+     * the context with the default credentials.
+     *
+     * @param context      context to search on
+     * @param user         user to bind on
+     * @param base         base to start the search from
+     * @param filter       filter to use for the search
+     * @param controls     controls to use for the search
+     * @param searchAsUser {@code true} when the search should be done as user, or {@code false} for using the default
+     *                         credentials
      *
-     * @param context
-     *            context to search on
-     * @param user
-     *            user to bind on
-     * @param base
-     *            base to start the search from
-     * @param filter
-     *            filter to use for the search
-     * @param controls
-     *            controls to use for the search
-     * @param searchAsUser
-     *            {@code true} when the search should be done as user, or
-     *            {@code false} for using the default credentials
      * @return enumeration with all found entries
-     * @throws NamingException
-     *             if a directory server error occurs
+     *
+     * @throws NamingException if a directory server error occurs
      */
     private NamingEnumeration<SearchResult> searchAsUser(DirContext context, User user, String base, String filter,
             SearchControls controls, boolean searchAsUser) throws NamingException {
@@ -2208,8 +2105,10 @@ public class JNDIRealm extends RealmBase {
      * Return a String representing the value of the specified attribute.
      *
      * @param attrId Attribute name
-     * @param attrs Attributes containing the required value
+     * @param attrs  Attributes containing the required value
+     *
      * @return the attribute value
+     *
      * @exception NamingException if a directory server error occurs
      */
     private String getAttributeValue(String attrId, Attributes attrs) throws NamingException {
@@ -2245,9 +2144,11 @@ public class JNDIRealm extends RealmBase {
      * Add values of a specified attribute to a list
      *
      * @param attrId Attribute name
-     * @param attrs Attributes containing the new values
+     * @param attrs  Attributes containing the new values
      * @param values ArrayList containing values found so far
+     *
      * @return the list of attribute values
+     *
      * @exception NamingException if a directory server error occurs
      */
     private ArrayList<String> addAttributeValues(String attrId, Attributes attrs, ArrayList<String> values)
@@ -2268,8 +2169,8 @@ public class JNDIRealm extends RealmBase {
         }
         NamingEnumeration<?> e = attr.getAll();
         try {
-            while(e.hasMore()) {
-                String value = (String)e.next();
+            while (e.hasMore()) {
+                String value = (String) e.next();
                 values.add(value);
             }
         } catch (PartialResultException ex) {
@@ -2341,7 +2242,9 @@ public class JNDIRealm extends RealmBase {
 
     /**
      * Get the password for the specified user.
+     *
      * @param username The user name
+     *
      * @return the password associated with the given principal's user name.
      */
     @Override
@@ -2357,7 +2260,7 @@ public class JNDIRealm extends RealmBase {
             // Ensure that we have a directory context available
             connection = get();
 
-            // Occasionally the directory context will timeout.  Try one more
+            // Occasionally the directory context will timeout. Try one more
             // time before giving up.
             try {
                 user = getUser(connection, username, null);
@@ -2399,7 +2302,9 @@ public class JNDIRealm extends RealmBase {
 
     /**
      * Get the principal associated with the specified certificate.
+     *
      * @param username The user name
+     *
      * @return the Principal associated with the given certificate.
      */
     @Override
@@ -2434,7 +2339,7 @@ public class JNDIRealm extends RealmBase {
             // Ensure that we have a directory context available
             connection = get();
 
-            // Occasionally the directory context will timeout.  Try one more
+            // Occasionally the directory context will timeout. Try one more
             // time before giving up.
             try {
 
@@ -2478,10 +2383,13 @@ public class JNDIRealm extends RealmBase {
 
     /**
      * Get the principal associated with the specified certificate.
-     * @param connection The directory context
-     * @param username The user name
+     *
+     * @param connection    The directory context
+     * @param username      The user name
      * @param gssCredential The credentials
+     *
      * @return the Principal associated with the given certificate.
+     *
      * @exception NamingException if a directory server error occurs
      */
     protected Principal getPrincipal(JNDIConnection connection, String username, GSSCredential gssCredential)
@@ -2501,7 +2409,7 @@ public class JNDIRealm extends RealmBase {
                 context.addToEnvironment("javax.security.sasl.server.authentication", "true");
                 context.addToEnvironment("javax.security.sasl.qop", spnegoDelegationQop);
                 // Note: Subject already set in SPNEGO authenticator so no need
-                //       for Subject.doAs() here
+                // for Subject.doAs() here
             }
             user = getUser(connection, username);
             if (user != null) {
@@ -2523,13 +2431,12 @@ public class JNDIRealm extends RealmBase {
     }
 
 
-    private void restoreEnvironmentParameter(DirContext context,
-            String parameterName, Hashtable<?, ?> preservedEnvironment) {
+    private void restoreEnvironmentParameter(DirContext context, String parameterName,
+            Hashtable<?, ?> preservedEnvironment) {
         try {
             context.removeFromEnvironment(parameterName);
             if (preservedEnvironment != null && preservedEnvironment.containsKey(parameterName)) {
-                context.addToEnvironment(parameterName,
-                        preservedEnvironment.get(parameterName));
+                context.addToEnvironment(parameterName, preservedEnvironment.get(parameterName));
             }
         } catch (NamingException e) {
             // Ignore
@@ -2538,9 +2445,10 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Open (if necessary) and return a connection to the configured
-     * directory server for this Realm.
+     * Open (if necessary) and return a connection to the configured directory server for this Realm.
+     *
      * @return the connection
+     *
      * @exception NamingException if a directory server error occurs
      */
     protected JNDIConnection get() throws NamingException {
@@ -2582,8 +2490,8 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Create a new connection wrapper, along with the
-     * message formats.
+     * Create a new connection wrapper, along with the message formats.
+     *
      * @return the new connection
      */
     protected JNDIConnection create() {
@@ -2610,7 +2518,9 @@ public class JNDIRealm extends RealmBase {
 
     /**
      * Create a new connection to the directory server.
+     *
      * @param connection The directory server connection wrapper
+     *
      * @throws NamingException if a directory server error occurs
      */
     protected void open(JNDIConnection connection) throws NamingException {
@@ -2672,14 +2582,10 @@ public class JNDIRealm extends RealmBase {
             if (o instanceof SSLSocketFactory) {
                 return sslSocketFactory;
             } else {
-                throw new IllegalArgumentException(sm.getString(
-                        "jndiRealm.invalidSslSocketFactory",
-                        className));
+                throw new IllegalArgumentException(sm.getString("jndiRealm.invalidSslSocketFactory", className));
             }
         } catch (ReflectiveOperationException | SecurityException e) {
-            throw new IllegalArgumentException(sm.getString(
-                    "jndiRealm.invalidSslSocketFactory",
-                    className), e);
+            throw new IllegalArgumentException(sm.getString("jndiRealm.invalidSslSocketFactory", className), e);
         }
     }
 
@@ -2696,21 +2602,20 @@ public class JNDIRealm extends RealmBase {
             return sslContext.getSocketFactory();
         } catch (NoSuchAlgorithmException | KeyManagementException e) {
             List<String> allowedProtocols = Arrays.asList(getSupportedSslProtocols());
-            throw new IllegalArgumentException(sm.getString("jndiRealm.invalidSslProtocol",
-                    protocol, allowedProtocols), e);
+            throw new IllegalArgumentException(sm.getString("jndiRealm.invalidSslProtocol", protocol, allowedProtocols),
+                    e);
         }
     }
 
 
     /**
-     * Create a tls enabled LdapContext and set the StartTlsResponse tls
-     * instance variable.
+     * Create a tls enabled LdapContext and set the StartTlsResponse tls instance variable.
+     *
+     * @param env Environment to use for context creation
      *
-     * @param env
-     *            Environment to use for context creation
      * @return configured {@link LdapContext}
-     * @throws NamingException
-     *             when something goes wrong while negotiating the connection
+     *
+     * @throws NamingException when something goes wrong while negotiating the connection
      */
     private DirContext createTlsDirContext(Hashtable<String, String> env) throws NamingException {
         Map<String, Object> savedEnv = new HashMap<>();
@@ -2753,9 +2658,9 @@ public class JNDIRealm extends RealmBase {
      *
      * @return java.util.Hashtable the configuration for the directory context.
      */
-    protected Hashtable<String,String> getDirectoryContextEnvironment() {
+    protected Hashtable<String, String> getDirectoryContextEnvironment() {
 
-        Hashtable<String,String> env = new Hashtable<>();
+        Hashtable<String, String> env = new Hashtable<>();
 
         // Configure our directory context environment.
         if (containerLog.isDebugEnabled() && connectionAttempt == 0) {
@@ -2801,12 +2706,11 @@ public class JNDIRealm extends RealmBase {
     // ------------------------------------------------------ Lifecycle Methods
 
     /**
-     * Prepare for the beginning of active use of the public methods of this
-     * component and implement the requirements of
+     * Prepare for the beginning of active use of the public methods of this component and implement the requirements of
      * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
      *
-     * @exception LifecycleException if this component detects a fatal error
-     *  that prevents this component from being used
+     * @exception LifecycleException if this component detects a fatal error that prevents this component from being
+     *                                   used
      */
     @Override
     protected void startInternal() throws LifecycleException {
@@ -2846,12 +2750,10 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Gracefully terminate the active use of the public methods of this
-     * component and implement the requirements of
+     * Gracefully terminate the active use of the public methods of this component and implement the requirements of
      * {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
      *
-     * @exception LifecycleException if this component detects a fatal error
-     *  that needs to be reported
+     * @exception LifecycleException if this component detects a fatal error that needs to be reported
      */
     @Override
     protected void stopInternal() throws LifecycleException {
@@ -2868,13 +2770,12 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Given a string containing LDAP patterns for user locations (separated by
-     * parentheses in a pseudo-LDAP search string format -
-     * "(location1)(location2)", returns an array of those paths.  Real LDAP
-     * search strings are supported as well (though only the "|" "OR" type).
+     * Given a string containing LDAP patterns for user locations (separated by parentheses in a pseudo-LDAP search
+     * string format - "(location1)(location2)", returns an array of those paths. Real LDAP search strings are supported
+     * as well (though only the "|" "OR" type).
+     *
+     * @param userPatternString - a string LDAP search paths surrounded by parentheses
      *
-     * @param userPatternString - a string LDAP search paths surrounded by
-     * parentheses
      * @return a parsed string array
      */
     protected String[] parseUserPatternString(String userPatternString) {
@@ -2884,7 +2785,7 @@ public class JNDIRealm extends RealmBase {
             int startParenLoc = userPatternString.indexOf('(');
             if (startParenLoc == -1) {
                 // no parens here; return whole thing
-                return new String[] {userPatternString};
+                return new String[] { userPatternString };
             }
             int startingPoint = 0;
             while (startParenLoc > -1) {
@@ -2892,18 +2793,18 @@ public class JNDIRealm extends RealmBase {
                 // weed out escaped open parens and parens enclosing the
                 // whole statement (in the case of valid LDAP search
                 // strings: (|(something)(somethingelse))
-                while ( (userPatternString.charAt(startParenLoc + 1) == '|') ||
-                        (startParenLoc != 0 && userPatternString.charAt(startParenLoc - 1) == '\\') ) {
-                    startParenLoc = userPatternString.indexOf('(', startParenLoc+1);
+                while ((userPatternString.charAt(startParenLoc + 1) == '|') ||
+                        (startParenLoc != 0 && userPatternString.charAt(startParenLoc - 1) == '\\')) {
+                    startParenLoc = userPatternString.indexOf('(', startParenLoc + 1);
                 }
-                endParenLoc = userPatternString.indexOf(')', startParenLoc+1);
+                endParenLoc = userPatternString.indexOf(')', startParenLoc + 1);
                 // weed out escaped end-parens
                 while (userPatternString.charAt(endParenLoc - 1) == '\\') {
-                    endParenLoc = userPatternString.indexOf(')', endParenLoc+1);
+                    endParenLoc = userPatternString.indexOf(')', endParenLoc + 1);
                 }
-                String nextPathPart = userPatternString.substring(startParenLoc+1, endParenLoc);
+                String nextPathPart = userPatternString.substring(startParenLoc + 1, endParenLoc);
                 pathList.add(nextPathPart);
-                startingPoint = endParenLoc+1;
+                startingPoint = endParenLoc + 1;
                 startParenLoc = userPatternString.indexOf('(', startingPoint);
             }
             return pathList.toArray(new String[0]);
@@ -2913,16 +2814,9 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Given an LDAP search string, returns the string with certain characters
-     * escaped according to RFC 2254 guidelines.
-     * The character mapping is as follows:
-     *     char -&gt;  Replacement
-     *    ---------------------------
-     *     *  -&gt; \2a
-     *     (  -&gt; \28
-     *     )  -&gt; \29
-     *     \  -&gt; \5c
-     *     \0 -&gt; \00
+     * Given an LDAP search string, returns the string with certain characters escaped according to RFC 2254 guidelines.
+     * The character mapping is as follows: char -&gt; Replacement --------------------------- * -&gt; \2a ( -&gt; \28 )
+     * -&gt; \29 \ -&gt; \5c \0 -&gt; \00
      *
      * @param inString string to escape according to RFC 2254 guidelines
      *
@@ -2937,16 +2831,9 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Given an LDAP search string, returns the string with certain characters
-     * escaped according to RFC 2254 guidelines.
-     * The character mapping is as follows:
-     *     char -&gt;  Replacement
-     *    ---------------------------
-     *     *  -&gt; \2a
-     *     (  -&gt; \28
-     *     )  -&gt; \29
-     *     \  -&gt; \5c
-     *     \0 -&gt; \00
+     * Given an LDAP search string, returns the string with certain characters escaped according to RFC 2254 guidelines.
+     * The character mapping is as follows: char -&gt; Replacement --------------------------- * -&gt; \2a ( -&gt; \28 )
+     * -&gt; \29 \ -&gt; \5c \0 -&gt; \00
      *
      * @param inString string to escape according to RFC 2254 guidelines
      *
@@ -2988,15 +2875,17 @@ public class JNDIRealm extends RealmBase {
      * Returns the distinguished name of a search result.
      *
      * @param context Our DirContext
-     * @param base The base DN
-     * @param result The search result
+     * @param base    The base DN
+     * @param result  The search result
+     *
      * @return String containing the distinguished name
+     *
      * @exception NamingException if a directory server error occurs
      */
     protected String getDistinguishedName(DirContext context, String base, SearchResult result) throws NamingException {
-        // Get the entry's distinguished name.  For relative results, this means
+        // Get the entry's distinguished name. For relative results, this means
         // we need to composite a name with the base name, the context name, and
-        // the result name.  For non-relative names, use the returned name.
+        // the result name. For non-relative names, use the returned name.
         String resultName = result.getName();
         Name name;
         if (result.isRelative()) {
@@ -3022,11 +2911,11 @@ public class JNDIRealm extends RealmBase {
                 URI userNameUri = new URI(resultName);
                 String pathComponent = userNameUri.getPath();
                 // Should not ever have an empty path component, since that is /{DN}
-                if (pathComponent.length() < 1 ) {
+                if (pathComponent.length() < 1) {
                     throw new InvalidNameException("Search returned unparseable absolute name: " + resultName);
                 }
                 name = parser.parse(pathComponent.substring(1));
-            } catch ( URISyntaxException e ) {
+            } catch (URISyntaxException e) {
                 throw new InvalidNameException("Search returned unparseable absolute name: " + resultName);
             }
         }
@@ -3041,11 +2930,11 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Implements the necessary escaping to represent an attribute value as a
-     * String as per RFC 4514.
+     * Implements the necessary escaping to represent an attribute value as a String as per RFC 4514.
      *
      * @param input The original attribute value
-     * @return      The string representation of the attribute value
+     *
+     * @return The string representation of the attribute value
      */
     protected String doAttributeValueEscaping(String input) {
         if (input == null) {
@@ -3058,7 +2947,7 @@ public class JNDIRealm extends RealmBase {
             char c = input.charAt(i);
             switch (c) {
                 case ' ': {
-                    if (i == 0 || i == (len -1)) {
+                    if (i == 0 || i == (len - 1)) {
                         result.append("\\20");
                     } else {
                         result.append(c);
@@ -3066,7 +2955,7 @@ public class JNDIRealm extends RealmBase {
                     break;
                 }
                 case '#': {
-                    if (i == 0 ) {
+                    if (i == 0) {
                         result.append("\\23");
                     } else {
                         result.append(c);
@@ -3239,32 +3128,27 @@ public class JNDIRealm extends RealmBase {
 
 
     /**
-     * Class holding the connection to the directory plus the associated
-     * non thread safe message formats.
+     * Class holding the connection to the directory plus the associated non thread safe message formats.
      */
     protected static class JNDIConnection {
 
         /**
-         * The MessageFormat object associated with the current
-         * <code>userSearch</code>.
+         * The MessageFormat object associated with the current <code>userSearch</code>.
          */
         public MessageFormat userSearchFormat = null;
 
         /**
-         * An array of MessageFormat objects associated with the current
-         * <code>userPatternArray</code>.
+         * An array of MessageFormat objects associated with the current <code>userPatternArray</code>.
          */
         public MessageFormat[] userPatternFormatArray = null;
 
         /**
-         * The MessageFormat object associated with the current
-         * <code>roleBase</code>.
+         * The MessageFormat object associated with the current <code>roleBase</code>.
          */
         public MessageFormat roleBaseFormat = null;
 
         /**
-         * The MessageFormat object associated with the current
-         * <code>roleSearch</code>.
+         * The MessageFormat object associated with the current <code>roleSearch</code>.
          */
         public MessageFormat roleFormat = null;
 
diff --git a/java/org/apache/catalina/realm/LockOutRealm.java b/java/org/apache/catalina/realm/LockOutRealm.java
index abaee00b37..d061fb30cf 100644
--- a/java/org/apache/catalina/realm/LockOutRealm.java
+++ b/java/org/apache/catalina/realm/LockOutRealm.java
@@ -31,80 +31,70 @@ import org.ietf.jgss.GSSException;
 import org.ietf.jgss.GSSName;
 
 /**
- * This class extends the CombinedRealm (hence it can wrap other Realms) to
- * provide a user lock out mechanism if there are too many failed
- * authentication attempts in a given period of time. To ensure correct
- * operation, there is a reasonable degree of synchronisation in this Realm.
- * This Realm does not require modification to the underlying Realms or the
- * associated user storage mechanisms. It achieves this by recording all failed
- * logins, including those for users that do not exist. To prevent a DOS by
- * deliberating making requests with invalid users (and hence causing this cache
- * to grow) the size of the list of users that have failed authentication is
- * limited.
+ * This class extends the CombinedRealm (hence it can wrap other Realms) to provide a user lock out mechanism if there
+ * are too many failed authentication attempts in a given period of time. To ensure correct operation, there is a
+ * reasonable degree of synchronisation in this Realm. This Realm does not require modification to the underlying Realms
+ * or the associated user storage mechanisms. It achieves this by recording all failed logins, including those for users
+ * that do not exist. To prevent a DOS by deliberating making requests with invalid users (and hence causing this cache
+ * to grow) the size of the list of users that have failed authentication is limited.
  */
 public class LockOutRealm extends CombinedRealm {
 
     private static final Log log = LogFactory.getLog(LockOutRealm.class);
 
     /**
-     * The number of times in a row a user has to fail authentication to be
-     * locked out. Defaults to 5.
+     * The number of times in a row a user has to fail authentication to be locked out. Defaults to 5.
      */
     protected int failureCount = 5;
 
     /**
-     * The time (in seconds) a user is locked out for after too many
-     * authentication failures. Defaults to 300 (5 minutes).
+     * The time (in seconds) a user is locked out for after too many authentication failures. Defaults to 300 (5
+     * minutes).
      */
     protected int lockOutTime = 300;
 
     /**
-     * Number of users that have failed authentication to keep in cache. Over
-     * time the cache will grow to this size and may not shrink. Defaults to
-     * 1000.
+     * Number of users that have failed authentication to keep in cache. Over time the cache will grow to this size and
+     * may not shrink. Defaults to 1000.
      */
     protected int cacheSize = 1000;
 
     /**
-     * If a failed user is removed from the cache because the cache is too big
-     * before it has been in the cache for at least this period of time (in
-     * seconds) a warning message will be logged. Defaults to 3600 (1 hour).
+     * If a failed user is removed from the cache because the cache is too big before it has been in the cache for at
+     * least this period of time (in seconds) a warning message will be logged. Defaults to 3600 (1 hour).
      */
     protected int cacheRemovalWarningTime = 3600;
 
     /**
-     * Users whose last authentication attempt failed. Entries will be ordered
-     * in access order from least recent to most recent.
+     * Users whose last authentication attempt failed. Entries will be ordered in access order from least recent to most
+     * recent.
      */
-    protected Map<String,LockRecord> failedUsers = null;
+    protected Map<String, LockRecord> failedUsers = null;
 
 
     /**
-     * Prepare for the beginning of active use of the public methods of this
-     * component and implement the requirements of
+     * Prepare for the beginning of active use of the public methods of this component and implement the requirements of
      * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
      *
-     * @exception LifecycleException if this component detects a fatal error
-     *  that prevents this component from being used
+     * @exception LifecycleException if this component detects a fatal error that prevents this component from being
+     *                                   used
      */
     @Override
     protected synchronized void startInternal() throws LifecycleException {
         // Configure the list of failed users to delete the oldest entry once it
         // exceeds the specified size
-        failedUsers = new LinkedHashMap<String, LockRecord>(cacheSize, 0.75f,
-                true) {
+        failedUsers = new LinkedHashMap<String, LockRecord>(cacheSize, 0.75f, true) {
             private static final long serialVersionUID = 1L;
+
             @Override
-            protected boolean removeEldestEntry(
-                    Map.Entry<String, LockRecord> eldest) {
+            protected boolean removeEldestEntry(Map.Entry<String, LockRecord> eldest) {
                 if (size() > cacheSize) {
                     // Check to see if this element has been removed too quickly
-                    long timeInCache = (System.currentTimeMillis() -
-                            eldest.getValue().getLastFailureTime())/1000;
+                    long timeInCache = (System.currentTimeMillis() - eldest.getValue().getLastFailureTime()) / 1000;
 
                     if (timeInCache < cacheRemovalWarningTime) {
-                        log.warn(sm.getString("lockOutRealm.removeWarning",
-                                eldest.getKey(), Long.valueOf(timeInCache)));
+                        log.warn(
+                                sm.getString("lockOutRealm.removeWarning", eldest.getKey(), Long.valueOf(timeInCache)));
                     }
                     return true;
                 }
@@ -117,36 +107,31 @@ public class LockOutRealm extends CombinedRealm {
 
 
     /**
-     * Return the Principal associated with the specified username, which
-     * matches the digest calculated using the given parameters using the
-     * method described in RFC 2069; otherwise return <code>null</code>.
+     * Return the Principal associated with the specified username, which matches the digest calculated using the given
+     * parameters using the method described in RFC 2069; otherwise return <code>null</code>.
      *
-     * @param username Username of the Principal to look up
+     * @param username     Username of the Principal to look up
      * @param clientDigest Digest which has been submitted by the client
-     * @param nonce Unique (or supposedly unique) token which has been used
-     * for this request
-     * @param realmName Realm name
-     * @param md5a2 Second MD5 digest used to calculate the digest :
-     * MD5(Method + ":" + uri)
+     * @param nonce        Unique (or supposedly unique) token which has been used for this request
+     * @param realmName    Realm name
+     * @param md5a2        Second MD5 digest used to calculate the digest : MD5(Method + ":" + uri)
      */
     @Override
-    public Principal authenticate(String username, String clientDigest,
-            String nonce, String nc, String cnonce, String qop,
-            String realmName, String md5a2) {
+    public Principal authenticate(String username, String clientDigest, String nonce, String nc, String cnonce,
+            String qop, String realmName, String md5a2) {
 
-        Principal authenticatedUser = super.authenticate(username, clientDigest, nonce, nc, cnonce,
-                qop, realmName, md5a2);
+        Principal authenticatedUser = super.authenticate(username, clientDigest, nonce, nc, cnonce, qop, realmName,
+                md5a2);
         return filterLockedAccounts(username, authenticatedUser);
     }
 
 
     /**
-     * Return the Principal associated with the specified username and
-     * credentials, if there is one; otherwise return <code>null</code>.
+     * Return the Principal associated with the specified username and credentials, if there is one; otherwise return
+     * <code>null</code>.
      *
-     * @param username Username of the Principal to look up
-     * @param credentials Password or other credentials to use in
-     *  authenticating this username
+     * @param username    Username of the Principal to look up
+     * @param credentials Password or other credentials to use in authenticating this username
      */
     @Override
     public Principal authenticate(String username, String credentials) {
@@ -156,16 +141,16 @@ public class LockOutRealm extends CombinedRealm {
 
 
     /**
-     * Return the Principal associated with the specified chain of X509
-     * client certificates.  If there is none, return <code>null</code>.
+     * Return the Principal associated with the specified chain of X509 client certificates. If there is none, return
+     * <code>null</code>.
      *
-     * @param certs Array of client certificates, with the first one in
-     *  the array being the certificate of the client itself.
+     * @param certs Array of client certificates, with the first one in the array being the certificate of the client
+     *                  itself.
      */
     @Override
     public Principal authenticate(X509Certificate[] certs) {
         String username = null;
-        if (certs != null && certs.length >0) {
+        if (certs != null && certs.length > 0) {
             username = certs[0].getSubjectX500Principal().toString();
         }
 
@@ -214,8 +199,8 @@ public class LockOutRealm extends CombinedRealm {
 
 
     /*
-     * Filters authenticated principals to ensure that <code>null</code> is
-     * returned for any user that is currently locked out.
+     * Filters authenticated principals to ensure that <code>null</code> is returned for any user that is currently
+     * locked out.
      */
     private Principal filterLockedAccounts(String username, Principal authenticatedUser) {
         // Register all failed authentications
@@ -238,8 +223,7 @@ public class LockOutRealm extends CombinedRealm {
 
 
     /**
-     * Unlock the specified username. This will remove all records of
-     * authentication failures for this user.
+     * Unlock the specified username. This will remove all records of authentication failures for this user.
      *
      * @param username The user to unlock
      */
@@ -249,9 +233,8 @@ public class LockOutRealm extends CombinedRealm {
     }
 
     /*
-     * Checks to see if the current user is locked. If this is associated with
-     * a login attempt, then the last access time will be recorded and any
-     * attempt to authenticated a locked user will log a warning.
+     * Checks to see if the current user is locked. If this is associated with a login attempt, then the last access
+     * time will be recorded and any attempt to authenticated a locked user will log a warning.
      */
     public boolean isLocked(String username) {
         LockRecord lockRecord = null;
@@ -266,8 +249,7 @@ public class LockOutRealm extends CombinedRealm {
 
         // Check to see if user is locked
         if (lockRecord.getFailures() >= failureCount &&
-                (System.currentTimeMillis() -
-                        lockRecord.getLastFailureTime())/1000 < lockOutTime) {
+                (System.currentTimeMillis() - lockRecord.getLastFailureTime()) / 1000 < lockOutTime) {
             return true;
         }
 
@@ -277,8 +259,7 @@ public class LockOutRealm extends CombinedRealm {
 
 
     /*
-     * After successful authentication, any record of previous authentication
-     * failure is removed.
+     * After successful authentication, any record of previous authentication failure is removed.
      */
     private synchronized void registerAuthSuccess(String username) {
         // Successful authentication means removal from the list of failed users
@@ -287,8 +268,7 @@ public class LockOutRealm extends CombinedRealm {
 
 
     /*
-     * After a failed authentication, add the record of the failed
-     * authentication.
+     * After a failed authentication, add the record of the failed authentication.
      */
     private void registerAuthFailure(String username) {
         LockRecord lockRecord = null;
@@ -299,9 +279,7 @@ public class LockOutRealm extends CombinedRealm {
             } else {
                 lockRecord = failedUsers.get(username);
                 if (lockRecord.getFailures() >= failureCount &&
-                        ((System.currentTimeMillis() -
-                                lockRecord.getLastFailureTime())/1000)
-                                > lockOutTime) {
+                        ((System.currentTimeMillis() - lockRecord.getLastFailureTime()) / 1000) > lockOutTime) {
                     // User was previously locked out but lockout has now
                     // expired so reset failure count
                     lockRecord.setFailures(0);
@@ -313,8 +291,8 @@ public class LockOutRealm extends CombinedRealm {
 
 
     /**
-     * Get the number of failed authentication attempts required to lock the
-     * user account.
+     * Get the number of failed authentication attempts required to lock the user account.
+     *
      * @return the failureCount
      */
     public int getFailureCount() {
@@ -323,8 +301,8 @@ public class LockOutRealm extends CombinedRealm {
 
 
     /**
-     * Set the number of failed authentication attempts required to lock the
-     * user account.
+     * Set the number of failed authentication attempts required to lock the user account.
+     *
      * @param failureCount the failureCount to set
      */
     public void setFailureCount(int failureCount) {
@@ -334,6 +312,7 @@ public class LockOutRealm extends CombinedRealm {
 
     /**
      * Get the period for which an account will be locked.
+     *
      * @return the lockOutTime
      */
     public int getLockOutTime() {
@@ -343,6 +322,7 @@ public class LockOutRealm extends CombinedRealm {
 
     /**
      * Set the period for which an account will be locked.
+     *
      * @param lockOutTime the lockOutTime to set
      */
     public void setLockOutTime(int lockOutTime) {
@@ -351,8 +331,8 @@ public class LockOutRealm extends CombinedRealm {
 
 
     /**
-     * Get the maximum number of users for which authentication failure will be
-     * kept in the cache.
+     * Get the maximum number of users for which authentication failure will be kept in the cache.
+     *
      * @return the cacheSize
      */
     public int getCacheSize() {
@@ -361,8 +341,8 @@ public class LockOutRealm extends CombinedRealm {
 
 
     /**
-     * Set the maximum number of users for which authentication failure will be
-     * kept in the cache.
+     * Set the maximum number of users for which authentication failure will be kept in the cache.
+     *
      * @param cacheSize the cacheSize to set
      */
     public void setCacheSize(int cacheSize) {
@@ -371,9 +351,9 @@ public class LockOutRealm extends CombinedRealm {
 
 
     /**
-     * Get the minimum period a failed authentication must remain in the cache
-     * to avoid generating a warning if it is removed from the cache to make
-     * space for a new entry.
+     * Get the minimum period a failed authentication must remain in the cache to avoid generating a warning if it is
+     * removed from the cache to make space for a new entry.
+     *
      * @return the cacheRemovalWarningTime
      */
     public int getCacheRemovalWarningTime() {
@@ -382,9 +362,9 @@ public class LockOutRealm extends CombinedRealm {
 
 
     /**
-     * Set the minimum period a failed authentication must remain in the cache
-     * to avoid generating a warning if it is removed from the cache to make
-     * space for a new entry.
+     * Set the minimum period a failed authentication must remain in the cache to avoid generating a warning if it is
+     * removed from the cache to make space for a new entry.
+     *
      * @param cacheRemovalWarningTime the cacheRemovalWarningTime to set
      */
     public void setCacheRemovalWarningTime(int cacheRemovalWarningTime) {
diff --git a/java/org/apache/catalina/realm/MemoryRealm.java b/java/org/apache/catalina/realm/MemoryRealm.java
index 76095bf07b..9362ff8036 100644
--- a/java/org/apache/catalina/realm/MemoryRealm.java
+++ b/java/org/apache/catalina/realm/MemoryRealm.java
@@ -32,18 +32,16 @@ import org.apache.tomcat.util.file.ConfigFileLoader;
 
 
 /**
- * Simple implementation of <b>Realm</b> that reads an XML file to configure
- * the valid users, passwords, and roles.  The file format (and default file
- * location) are identical to those currently supported by Tomcat 3.X.
+ * Simple implementation of <b>Realm</b> that reads an XML file to configure the valid users, passwords, and roles. The
+ * file format (and default file location) are identical to those currently supported by Tomcat 3.X.
  * <p>
- * <strong>IMPLEMENTATION NOTE</strong>: It is assumed that the in-memory
- * collection representing our defined users (and their roles) is initialized
- * at application startup and never modified again.  Therefore, no thread
- * synchronization is performed around accesses to the principals collection.
+ * <strong>IMPLEMENTATION NOTE</strong>: It is assumed that the in-memory collection representing our defined users (and
+ * their roles) is initialized at application startup and never modified again. Therefore, no thread synchronization is
+ * performed around accesses to the principals collection.
  *
  * @author Craig R. McClanahan
  */
-public class MemoryRealm  extends RealmBase {
+public class MemoryRealm extends RealmBase {
 
     private static final Log log = LogFactory.getLog(MemoryRealm.class);
 
@@ -58,8 +56,8 @@ public class MemoryRealm  extends RealmBase {
 
 
     /**
-     * The pathname (absolute or relative to Catalina's current working
-     * directory) of the XML file containing our database information.
+     * The pathname (absolute or relative to Catalina's current working directory) of the XML file containing our
+     * database information.
      */
     private String pathname = "conf/tomcat-users.xml";
 
@@ -67,7 +65,7 @@ public class MemoryRealm  extends RealmBase {
     /**
      * The set of valid Principals for this Realm, keyed by user name.
      */
-    private final Map<String,GenericPrincipal> principals = new HashMap<>();
+    private final Map<String, GenericPrincipal> principals = new HashMap<>();
 
 
     // ------------------------------------------------------------- Properties
@@ -83,8 +81,8 @@ public class MemoryRealm  extends RealmBase {
 
 
     /**
-     * Set the pathname of our XML file containing user definitions.  If a
-     * relative pathname is specified, it is resolved against "catalina.base".
+     * Set the pathname of our XML file containing user definitions. If a relative pathname is specified, it is resolved
+     * against "catalina.base".
      *
      * @param pathname The new pathname
      */
@@ -99,12 +97,12 @@ public class MemoryRealm  extends RealmBase {
 
 
     /**
-     * Return the Principal associated with the specified username and
-     * credentials, if there is one; otherwise return <code>null</code>.
+     * Return the Principal associated with the specified username and credentials, if there is one; otherwise return
+     * <code>null</code>.
+     *
+     * @param username    Username of the Principal to look up
+     * @param credentials Password or other credentials to use in authenticating this username
      *
-     * @param username Username of the Principal to look up
-     * @param credentials Password or other credentials to use in
-     *  authenticating this username
      * @return the associated principal, or <code>null</code> if there is none.
      */
     @Override
@@ -121,7 +119,7 @@ public class MemoryRealm  extends RealmBase {
 
         GenericPrincipal principal = principals.get(username);
 
-        if(principal == null || principal.getPassword() == null) {
+        if (principal == null || principal.getPassword() == null) {
             // User was not found in the database or the password was null
             // Waste a bit of time as not to reveal that the user does not exist.
             getCredentialHandler().mutate(credentials);
@@ -156,7 +154,7 @@ public class MemoryRealm  extends RealmBase {
      *
      * @param username User's username
      * @param password User's password (clear text)
-     * @param roles Comma-delimited set of roles associated with this user
+     * @param roles    Comma-delimited set of roles associated with this user
      */
     void addUser(String username, String password, String roles) {
 
@@ -174,8 +172,7 @@ public class MemoryRealm  extends RealmBase {
         }
 
         // Construct and cache the Principal for this user
-        GenericPrincipal principal =
-            new GenericPrincipal(username, password, list);
+        GenericPrincipal principal = new GenericPrincipal(username, password, list);
         principals.put(username, principal);
 
     }
@@ -185,8 +182,8 @@ public class MemoryRealm  extends RealmBase {
 
 
     /**
-     * @return a configured <code>Digester</code> to use for processing
-     * the XML input file, creating a new one if necessary.
+     * @return a configured <code>Digester</code> to use for processing the XML input file, creating a new one if
+     *             necessary.
      */
     protected Digester getDigester() {
         synchronized (digesterLock) {
@@ -235,12 +232,11 @@ public class MemoryRealm  extends RealmBase {
     // ------------------------------------------------------ Lifecycle Methods
 
     /**
-     * Prepare for the beginning of active use of the public methods of this
-     * component and implement the requirements of
+     * Prepare for the beginning of active use of the public methods of this component and implement the requirements of
      * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
      *
-     * @exception LifecycleException if this component detects a fatal error
-     *  that prevents this component from being used
+     * @exception LifecycleException if this component detects a fatal error that prevents this component from being
+     *                                   used
      */
     @Override
     protected void startInternal() throws LifecycleException {
diff --git a/java/org/apache/catalina/realm/MemoryRuleSet.java b/java/org/apache/catalina/realm/MemoryRuleSet.java
index 9a114e9787..b8d1227884 100644
--- a/java/org/apache/catalina/realm/MemoryRuleSet.java
+++ b/java/org/apache/catalina/realm/MemoryRuleSet.java
@@ -22,8 +22,9 @@ import org.apache.tomcat.util.digester.RuleSet;
 import org.xml.sax.Attributes;
 
 /**
- * <p><strong>RuleSet</strong> for recognizing the users defined in the
- * XML file processed by <code>MemoryRealm</code>.</p>
+ * <p>
+ * <strong>RuleSet</strong> for recognizing the users defined in the XML file processed by <code>MemoryRealm</code>.
+ * </p>
  *
  * @author Craig R. McClanahan
  */
@@ -41,8 +42,7 @@ public class MemoryRuleSet implements RuleSet {
     // ------------------------------------------------------------ Constructor
 
     /**
-     * Construct an instance of this <code>RuleSet</code> with the default
-     * matching pattern prefix.
+     * Construct an instance of this <code>RuleSet</code> with the default matching pattern prefix.
      */
     public MemoryRuleSet() {
         this("tomcat-users/");
@@ -50,11 +50,9 @@ public class MemoryRuleSet implements RuleSet {
 
 
     /**
-     * Construct an instance of this <code>RuleSet</code> with the specified
-     * matching pattern prefix.
+     * Construct an instance of this <code>RuleSet</code> with the specified matching pattern prefix.
      *
-     * @param prefix Prefix for matching pattern rules (including the
-     *  trailing slash character)
+     * @param prefix Prefix for matching pattern rules (including the trailing slash character)
      */
     public MemoryRuleSet(String prefix) {
         this.prefix = prefix;
@@ -65,13 +63,12 @@ public class MemoryRuleSet implements RuleSet {
 
 
     /**
-     * <p>Add the set of Rule instances defined in this RuleSet to the
-     * specified <code>Digester</code> instance, associating them with
-     * our namespace URI (if any).  This method should only be called
-     * by a Digester instance.</p>
+     * <p>
+     * Add the set of Rule instances defined in this RuleSet to the specified <code>Digester</code> instance,
+     * associating them with our namespace URI (if any). This method should only be called by a Digester instance.
+     * </p>
      *
-     * @param digester Digester instance to which the new Rule instances
-     *  should be added.
+     * @param digester Digester instance to which the new Rule instances should be added.
      */
     @Override
     public void addRuleInstances(Digester digester) {
@@ -104,8 +101,7 @@ final class MemoryUserRule extends Rule {
      * @param attributes The attribute list for this element
      */
     @Override
-    public void begin(String namespace, String name, Attributes attributes)
-        throws Exception {
+    public void begin(String namespace, String name, Attributes attributes) throws Exception {
 
         String username = attributes.getValue("username");
         if (username == null) {
@@ -114,8 +110,7 @@ final class MemoryUserRule extends Rule {
         String password = attributes.getValue("password");
         String roles = attributes.getValue("roles");
 
-        MemoryRealm realm =
-            (MemoryRealm) digester.peek(digester.getCount() - 1);
+        MemoryRealm realm = (MemoryRealm) digester.peek(digester.getCount() - 1);
         realm.addUser(username, password, roles);
 
     }
diff --git a/java/org/apache/catalina/realm/MessageDigestCredentialHandler.java b/java/org/apache/catalina/realm/MessageDigestCredentialHandler.java
index d43465c801..7945af8490 100644
--- a/java/org/apache/catalina/realm/MessageDigestCredentialHandler.java
+++ b/java/org/apache/catalina/realm/MessageDigestCredentialHandler.java
@@ -32,22 +32,21 @@ import org.apache.tomcat.util.security.ConcurrentMessageDigest;
 /**
  * This credential handler supports the following forms of stored passwords:
  * <ul>
- * <li><b>encodedCredential</b> - a hex encoded digest of the password digested
- *     using the configured digest</li>
- * <li><b>{MD5}encodedCredential</b> - a Base64 encoded MD5 digest of the
- *     password</li>
- * <li><b>{SHA}encodedCredential</b> - a Base64 encoded SHA1 digest of the
- *     password</li>
- * <li><b>{SSHA}encodedCredential</b> - 20 byte Base64 encoded SHA1 digest
- *     followed by variable length salt.
- *     <pre>{SSHA}&lt;sha-1 digest:20&gt;&lt;salt:n&gt;</pre></li>
- * <li><b>salt$iterationCount$encodedCredential</b> - a hex encoded salt,
- *     iteration code and a hex encoded credential, each separated by $</li>
- * </ul>
+ * <li><b>encodedCredential</b> - a hex encoded digest of the password digested using the configured digest</li>
+ * <li><b>{MD5}encodedCredential</b> - a Base64 encoded MD5 digest of the password</li>
+ * <li><b>{SHA}encodedCredential</b> - a Base64 encoded SHA1 digest of the password</li>
+ * <li><b>{SSHA}encodedCredential</b> - 20 byte Base64 encoded SHA1 digest followed by variable length salt.
+ *
+ * <pre>
+ * {SSHA}&lt;sha-1 digest:20&gt;&lt;salt:n&gt;
+ * </pre>
  *
+ * </li>
+ * <li><b>salt$iterationCount$encodedCredential</b> - a hex encoded salt, iteration code and a hex encoded credential,
+ * each separated by $</li>
+ * </ul>
  * <p>
- * If the stored password form does not include an iteration count then an
- * iteration count of 1 is used.
+ * If the stored password form does not include an iteration count then an iteration count of 1 is used.
  * <p>
  * If the stored password form does not include salt then no salt is used.
  */
@@ -109,8 +108,8 @@ public class MessageDigestCredentialHandler extends DigestCredentialHandlerBase
                 // Server is storing digested passwords with a prefix indicating
                 // the digest type
                 String base64ServerDigest = storedCredentials.substring(5);
-                byte[] userDigest = ConcurrentMessageDigest.digest(
-                        getAlgorithm(), inputCredentials.getBytes(StandardCharsets.ISO_8859_1));
+                byte[] userDigest = ConcurrentMessageDigest.digest(getAlgorithm(),
+                        inputCredentials.getBytes(StandardCharsets.ISO_8859_1));
                 String base64UserDigest = Base64.encodeBase64String(userDigest);
 
                 return DigestCredentialHandlerBase.equals(base64UserDigest, base64ServerDigest, false);
@@ -134,8 +133,7 @@ public class MessageDigestCredentialHandler extends DigestCredentialHandlerBase
                 // Generate the digested form of the user provided password
                 // using the salt
                 byte[] userDigestBytes = ConcurrentMessageDigest.digest(getAlgorithm(),
-                        inputCredentials.getBytes(StandardCharsets.ISO_8859_1),
-                        serverSaltBytes);
+                        inputCredentials.getBytes(StandardCharsets.ISO_8859_1), serverSaltBytes);
 
                 return Arrays.equals(userDigestBytes, serverDigestBytes);
             } else if (storedCredentials.indexOf('$') > -1) {
diff --git a/java/org/apache/catalina/realm/NestedCredentialHandler.java b/java/org/apache/catalina/realm/NestedCredentialHandler.java
index 91390f255f..286c3e03a4 100644
--- a/java/org/apache/catalina/realm/NestedCredentialHandler.java
+++ b/java/org/apache/catalina/realm/NestedCredentialHandler.java
@@ -38,11 +38,8 @@ public class NestedCredentialHandler implements CredentialHandler {
 
 
     /**
-     * The input credentials will be passed to the first nested
-     * {@link CredentialHandler}. If no nested {@link CredentialHandler} are
-     * configured then <code>null</code> will be returned.
-     *
-     * {@inheritDoc}
+     * The input credentials will be passed to the first nested {@link CredentialHandler}. If no nested
+     * {@link CredentialHandler} are configured then <code>null</code> will be returned. {@inheritDoc}
      */
     @Override
     public String mutate(String inputCredentials) {
diff --git a/java/org/apache/catalina/realm/NullRealm.java b/java/org/apache/catalina/realm/NullRealm.java
index e801b5e6d7..83e4693d9c 100644
--- a/java/org/apache/catalina/realm/NullRealm.java
+++ b/java/org/apache/catalina/realm/NullRealm.java
@@ -19,9 +19,8 @@ package org.apache.catalina.realm;
 import java.security.Principal;
 
 /**
- * Minimal Realm implementation that always returns null when an attempt is made
- * to validate a user name and password. It is intended to be used as a default
- * Realm implementation when no other Realm is specified.
+ * Minimal Realm implementation that always returns null when an attempt is made to validate a user name and password.
+ * It is intended to be used as a default Realm implementation when no other Realm is specified.
  */
 public class NullRealm extends RealmBase {
 
diff --git a/java/org/apache/catalina/realm/RealmBase.java b/java/org/apache/catalina/realm/RealmBase.java
index dbce28d313..b68ae6100a 100644
--- a/java/org/apache/catalina/realm/RealmBase.java
+++ b/java/org/apache/catalina/realm/RealmBase.java
@@ -63,9 +63,8 @@ import org.ietf.jgss.GSSException;
 import org.ietf.jgss.GSSName;
 
 /**
- * Simple implementation of <b>Realm</b> that reads an XML file to configure
- * the valid users, passwords, and roles.  The file format (and default file
- * location) are identical to those currently supported by Tomcat 3.X.
+ * Simple implementation of <b>Realm</b> that reads an XML file to configure the valid users, passwords, and roles. The
+ * file format (and default file location) are identical to those currently supported by Tomcat 3.X.
  *
  * @author Craig R. McClanahan
  */
@@ -73,8 +72,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
     private static final Log log = LogFactory.getLog(RealmBase.class);
 
-    private static final List<Class<? extends DigestCredentialHandlerBase>> credentialHandlerClasses =
-            new ArrayList<>();
+    private static final List<Class<? extends DigestCredentialHandlerBase>> credentialHandlerClasses = new ArrayList<>();
 
     static {
         // Order is important since it determines the search order for a
@@ -120,8 +118,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
     protected boolean validate = true;
 
     /**
-     * The name of the class to use for retrieving user names from X509
-     * certificates.
+     * The name of the class to use for retrieving user names from X509 certificates.
      */
     protected String x509UsernameRetrieverClassName;
 
@@ -137,8 +134,8 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
 
     /**
-     * When processing users authenticated via the GSS-API, should any
-     * &quot;@...&quot; be stripped from the end of the user name?
+     * When processing users authenticated via the GSS-API, should any &quot;@...&quot; be stripped from the end of the
+     * user name?
      */
     protected boolean stripRealmForGss = true;
 
@@ -149,9 +146,8 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
     // ------------------------------------------------------------- Properties
 
     /**
-     * @return The HTTP status code used when the container needs to issue an
-     *         HTTP redirect to meet the requirements of a configured transport
-     *         guarantee.
+     * @return The HTTP status code used when the container needs to issue an HTTP redirect to meet the requirements of
+     *             a configured transport guarantee.
      */
     public int getTransportGuaranteeRedirectStatus() {
         return transportGuaranteeRedirectStatus;
@@ -159,11 +155,10 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
 
     /**
-     * Set the HTTP status code used when the container needs to issue an HTTP
-     * redirect to meet the requirements of a configured transport guarantee.
+     * Set the HTTP status code used when the container needs to issue an HTTP redirect to meet the requirements of a
+     * configured transport guarantee.
      *
-     * @param transportGuaranteeRedirectStatus The status to use. This value is
-     *                                         not validated
+     * @param transportGuaranteeRedirectStatus The status to use. This value is not validated
      */
     public void setTransportGuaranteeRedirectStatus(int transportGuaranteeRedirectStatus) {
         this.transportGuaranteeRedirectStatus = transportGuaranteeRedirectStatus;
@@ -207,6 +202,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
     /**
      * Return the all roles mode.
+     *
      * @return A string representation of the current all roles mode
      */
     public String getAllRolesMode() {
@@ -216,6 +212,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
     /**
      * Set the all roles mode.
+     *
      * @param allRolesMode A string representation of the new all roles mode
      */
     public void setAllRolesMode(String allRolesMode) {
@@ -225,6 +222,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
     /**
      * Return the "validate certificate chains" flag.
+     *
      * @return The value of the validate certificate chains flag
      */
     public boolean getValidate() {
@@ -244,22 +242,20 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
     }
 
     /**
-     * Gets the name of the class that will be used to extract user names
-     * from X509 client certificates.
-     * @return The name of the class that will be used to extract user names
-     *         from X509 client certificates.
+     * Gets the name of the class that will be used to extract user names from X509 client certificates.
+     *
+     * @return The name of the class that will be used to extract user names from X509 client certificates.
      */
     public String getX509UsernameRetrieverClassName() {
         return x509UsernameRetrieverClassName;
     }
 
     /**
-     * Sets the name of the class that will be used to extract user names
-     * from X509 client certificates. The class must implement
-     * X509UsernameRetriever.
+     * Sets the name of the class that will be used to extract user names from X509 client certificates. The class must
+     * implement X509UsernameRetriever.
+     *
+     * @param className The name of the class that will be used to extract user names from X509 client certificates.
      *
-     * @param className The name of the class that will be used to extract user names
-     *                  from X509 client certificates.
      * @see X509UsernameRetriever
      */
     public void setX509UsernameRetrieverClassName(String className) {
@@ -293,8 +289,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
 
     /**
-     * Return the Principal associated with the specified username, if there
-     * is one; otherwise return <code>null</code>.
+     * Return the Principal associated with the specified username, if there is one; otherwise return <code>null</code>.
      *
      * @param username Username of the Principal to look up
      */
@@ -314,22 +309,21 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
 
     /**
-     * Return the Principal associated with the specified username and
-     * credentials, if there is one; otherwise return <code>null</code>.
+     * Return the Principal associated with the specified username and credentials, if there is one; otherwise return
+     * <code>null</code>.
+     *
+     * @param username    Username of the Principal to look up
+     * @param credentials Password or other credentials to use in authenticating this username
      *
-     * @param username Username of the Principal to look up
-     * @param credentials Password or other credentials to use in
-     *  authenticating this username
      * @return the associated principal, or <code>null</code> if there is none.
      */
     @Override
     public Principal authenticate(String username, String credentials) {
         // No user or no credentials
         // Can't possibly authenticate, don't bother doing anything.
-        if(username == null || credentials == null) {
+        if (username == null || credentials == null) {
             if (containerLog.isTraceEnabled()) {
-                containerLog.trace(sm.getString("realmBase.authenticateFailure",
-                                                username));
+                containerLog.trace(sm.getString("realmBase.authenticateFailure", username));
             }
             return null;
         }
@@ -343,8 +337,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
             getCredentialHandler().mutate(credentials);
 
             if (containerLog.isTraceEnabled()) {
-                containerLog.trace(sm.getString("realmBase.authenticateFailure",
-                                                username));
+                containerLog.trace(sm.getString("realmBase.authenticateFailure", username));
             }
             return null;
         }
@@ -353,14 +346,12 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
         if (validated) {
             if (containerLog.isTraceEnabled()) {
-                containerLog.trace(sm.getString("realmBase.authenticateSuccess",
-                                                username));
+                containerLog.trace(sm.getString("realmBase.authenticateSuccess", username));
             }
             return getPrincipal(username);
         } else {
             if (containerLog.isTraceEnabled()) {
-                containerLog.trace(sm.getString("realmBase.authenticateFailure",
-                                                username));
+                containerLog.trace(sm.getString("realmBase.authenticateFailure", username));
             }
             return null;
         }
@@ -368,28 +359,24 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
 
     /**
-     * Try to authenticate with the specified username, which
-     * matches the digest calculated using the given parameters using the
-     * method described in RFC 2617 (which is a superset of RFC 2069).
+     * Try to authenticate with the specified username, which matches the digest calculated using the given parameters
+     * using the method described in RFC 2617 (which is a superset of RFC 2069).
      *
-     * @param username Username of the Principal to look up
+     * @param username     Username of the Principal to look up
      * @param clientDigest Digest which has been submitted by the client
-     * @param nonce Unique (or supposedly unique) token which has been used
-     * for this request
-     * @param nc the nonce counter
-     * @param cnonce the client chosen nonce
-     * @param qop the "quality of protection" (<code>nc</code> and <code>cnonce</code>
-     *        will only be used, if <code>qop</code> is not <code>null</code>).
-     * @param realm Realm name
-     * @param md5a2 Second MD5 digest used to calculate the digest :
-     * MD5(Method + ":" + uri)
+     * @param nonce        Unique (or supposedly unique) token which has been used for this request
+     * @param nc           the nonce counter
+     * @param cnonce       the client chosen nonce
+     * @param qop          the "quality of protection" (<code>nc</code> and <code>cnonce</code> will only be used, if
+     *                         <code>qop</code> is not <code>null</code>).
+     * @param realm        Realm name
+     * @param md5a2        Second MD5 digest used to calculate the digest : MD5(Method + ":" + uri)
+     *
      * @return the associated principal, or <code>null</code> if there is none.
      */
     @Override
-    public Principal authenticate(String username, String clientDigest,
-                                  String nonce, String nc, String cnonce,
-                                  String qop, String realm,
-                                  String md5a2) {
+    public Principal authenticate(String username, String clientDigest, String nonce, String nc, String cnonce,
+            String qop, String realm, String md5a2) {
 
         // In digest auth, digests are always lower case
         String md5a1 = getDigest(username, realm);
@@ -401,25 +388,23 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
         if (qop == null) {
             serverDigestValue = md5a1 + ":" + nonce + ":" + md5a2;
         } else {
-            serverDigestValue = md5a1 + ":" + nonce + ":" + nc + ":" +
-                    cnonce + ":" + qop + ":" + md5a2;
+            serverDigestValue = md5a1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + md5a2;
         }
 
         byte[] valueBytes = null;
         try {
             valueBytes = serverDigestValue.getBytes(getDigestCharset());
         } catch (UnsupportedEncodingException uee) {
-            throw new IllegalArgumentException(sm.getString("realmBase.invalidDigestEncoding", getDigestEncoding()), uee);
+            throw new IllegalArgumentException(sm.getString("realmBase.invalidDigestEncoding", getDigestEncoding()),
+                    uee);
         }
 
         String serverDigest = MD5Encoder.encode(ConcurrentMessageDigest.digestMD5(valueBytes));
 
         if (log.isDebugEnabled()) {
-            log.debug("Digest : " + clientDigest + " Username:" + username
-                    + " ClientDigest:" + clientDigest + " nonce:" + nonce
-                    + " nc:" + nc + " cnonce:" + cnonce + " qop:" + qop
-                    + " realm:" + realm + "md5a2:" + md5a2
-                    + " Server digest:" + serverDigest);
+            log.debug("Digest : " + clientDigest + " Username:" + username + " ClientDigest:" + clientDigest +
+                    " nonce:" + nonce + " nc:" + nc + " cnonce:" + cnonce + " qop:" + qop + " realm:" + realm +
+                    "md5a2:" + md5a2 + " Server digest:" + serverDigest);
         }
 
         if (serverDigest.equals(clientDigest)) {
@@ -431,11 +416,11 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
 
     /**
-     * Return the Principal associated with the specified chain of X509
-     * client certificates.  If there is none, return <code>null</code>.
+     * Return the Principal associated with the specified chain of X509 client certificates. If there is none, return
+     * <code>null</code>.
      *
-     * @param certs Array of client certificates, with the first one in
-     *  the array being the certificate of the client itself.
+     * @param certs Array of client certificates, with the first one in the array being the certificate of the client
+     *                  itself.
      */
     @Override
     public Principal authenticate(X509Certificate certs[]) {
@@ -451,8 +436,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
         if (validate) {
             for (X509Certificate cert : certs) {
                 if (log.isDebugEnabled()) {
-                    log.debug(" Checking validity for '" +
-                            cert.getSubjectX500Principal().toString() + "'");
+                    log.debug(" Checking validity for '" + cert.getSubjectX500Principal().toString() + "'");
                 }
                 try {
                     cert.checkValidity();
@@ -483,20 +467,18 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
                 log.warn(sm.getString("realmBase.gssNameFail"), e);
             }
 
-            if (gssName!= null) {
+            if (gssName != null) {
                 GSSCredential gssCredential = null;
                 if (storeCred) {
                     if (gssContext.getCredDelegState()) {
                         try {
                             gssCredential = gssContext.getDelegCred();
                         } catch (GSSException e) {
-                            log.warn(sm.getString(
-                                    "realmBase.delegatedCredentialFail", gssName), e);
+                            log.warn(sm.getString("realmBase.delegatedCredentialFail", gssName), e);
                         }
                     } else {
                         if (log.isDebugEnabled()) {
-                            log.debug(sm.getString(
-                                    "realmBase.credentialNotDelegated", gssName));
+                            log.debug(sm.getString("realmBase.credentialNotDelegated", gssName));
                         }
                     }
                 }
@@ -526,9 +508,8 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
 
     /**
-     * Execute a periodic task, such as reloading, etc. This method will be
-     * invoked inside the classloading context of this container. Unexpected
-     * throwables will be caught and logged.
+     * Execute a periodic task, such as reloading, etc. This method will be invoked inside the classloading context of
+     * this container. Unexpected throwables will be caught and logged.
      */
     @Override
     public void backgroundProcess() {
@@ -537,15 +518,14 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
 
     /**
-     * Return the SecurityConstraints configured to guard the request URI for
-     * this request, or <code>null</code> if there is no such constraint.
+     * Return the SecurityConstraints configured to guard the request URI for this request, or <code>null</code> if
+     * there is no such constraint.
      *
      * @param request Request we are processing
      * @param context Context the Request is mapped to
      */
     @Override
-    public SecurityConstraint [] findSecurityConstraints(Request request,
-                                                         Context context) {
+    public SecurityConstraint[] findSecurityConstraints(Request request, Context context) {
 
         ArrayList<SecurityConstraint> results = null;
         // Are there any defined security constraints?
@@ -578,9 +558,8 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
             }
 
             if (log.isDebugEnabled()) {
-                log.debug("  Checking constraint '" + constraints[i] +
-                    "' against " + method + " " + uri + " --> " +
-                    constraints[i].included(uri, method));
+                log.debug("  Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " +
+                        constraints[i].included(uri, method));
             }
 
             for (SecurityCollection securityCollection : collections) {
@@ -607,25 +586,24 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
             }
         }
 
-        if(found) {
+        if (found) {
             return resultsToArray(results);
         }
 
         int longest = -1;
 
         for (i = 0; i < constraints.length; i++) {
-            SecurityCollection [] collection = constraints[i].findCollections();
+            SecurityCollection[] collection = constraints[i].findCollections();
 
             // If collection is null, continue to avoid an NPE
             // See Bugzilla 30624
-            if ( collection == null) {
+            if (collection == null) {
                 continue;
             }
 
             if (log.isDebugEnabled()) {
-                log.debug("  Checking constraint '" + constraints[i] +
-                    "' against " + method + " " + uri + " --> " +
-                    constraints[i].included(uri, method));
+                log.debug("  Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " +
+                        constraints[i].included(uri, method));
             }
 
             for (SecurityCollection securityCollection : collection) {
@@ -640,8 +618,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
                 boolean matched = false;
                 int length = -1;
                 for (String pattern : patterns) {
-                    if (pattern.startsWith("/") && pattern.endsWith("/*") &&
-                            pattern.length() >= longest) {
+                    if (pattern.startsWith("/") && pattern.endsWith("/*") && pattern.length() >= longest) {
 
                         if (pattern.length() == 2) {
                             matched = true;
@@ -673,45 +650,43 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
             }
         }
 
-        if(found) {
-            return  resultsToArray(results);
+        if (found) {
+            return resultsToArray(results);
         }
 
         for (i = 0; i < constraints.length; i++) {
-            SecurityCollection [] collection = constraints[i].findCollections();
+            SecurityCollection[] collection = constraints[i].findCollections();
 
             // If collection is null, continue to avoid an NPE
             // See Bugzilla 30624
-            if ( collection == null) {
+            if (collection == null) {
                 continue;
             }
 
             if (log.isDebugEnabled()) {
-                log.debug("  Checking constraint '" + constraints[i] +
-                    "' against " + method + " " + uri + " --> " +
-                    constraints[i].included(uri, method));
+                log.debug("  Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " +
+                        constraints[i].included(uri, method));
             }
 
             boolean matched = false;
             int pos = -1;
-            for(int j=0; j < collection.length; j++){
-                String [] patterns = collection[j].findPatterns();
+            for (int j = 0; j < collection.length; j++) {
+                String[] patterns = collection[j].findPatterns();
 
                 // If patterns is null, continue to avoid an NPE
                 // See Bugzilla 30624
-                if ( patterns == null) {
+                if (patterns == null) {
                     continue;
                 }
 
-                for(int k=0; k < patterns.length && !matched; k++) {
+                for (int k = 0; k < patterns.length && !matched; k++) {
                     String pattern = patterns[k];
-                    if(pattern.startsWith("*.")){
+                    if (pattern.startsWith("*.")) {
                         int slash = uri.lastIndexOf('/');
                         int dot = uri.lastIndexOf('.');
-                        if(slash >= 0 && dot > slash &&
-                           dot != uri.length()-1 &&
-                           uri.length()-dot == pattern.length()-1) {
-                            if(pattern.regionMatches(1,uri,dot,uri.length()-dot)) {
+                        if (slash >= 0 && dot > slash && dot != uri.length() - 1 &&
+                                uri.length() - dot == pattern.length() - 1) {
+                            if (pattern.regionMatches(1, uri, dot, uri.length() - dot)) {
                                 matched = true;
                                 pos = j;
                             }
@@ -719,10 +694,10 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
                     }
                 }
             }
-            if(matched) {
+            if (matched) {
                 found = true;
-                if(collection[pos].findMethod(method)) {
-                    if(results == null) {
+                if (collection[pos].findMethod(method)) {
+                    if (results == null) {
                         results = new ArrayList<>();
                     }
                     results.add(constraints[i]);
@@ -730,23 +705,22 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
             }
         }
 
-        if(found) {
+        if (found) {
             return resultsToArray(results);
         }
 
         for (i = 0; i < constraints.length; i++) {
-            SecurityCollection [] collection = constraints[i].findCollections();
+            SecurityCollection[] collection = constraints[i].findCollections();
 
             // If collection is null, continue to avoid an NPE
             // See Bugzilla 30624
-            if ( collection == null) {
+            if (collection == null) {
                 continue;
             }
 
             if (log.isDebugEnabled()) {
-                log.debug("  Checking constraint '" + constraints[i] +
-                    "' against " + method + " " + uri + " --> " +
-                    constraints[i].included(uri, method));
+                log.debug("  Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " +
+                        constraints[i].included(uri, method));
             }
 
             for (SecurityCollection securityCollection : collection) {
@@ -774,7 +748,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
             }
         }
 
-        if(results == null) {
+        if (results == null) {
             // No applicable security constraint was found
             if (log.isDebugEnabled()) {
                 log.debug("  No applicable constraint located");
@@ -786,33 +760,28 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
     /**
      * Convert an ArrayList to a SecurityConstraint [].
      */
-    private SecurityConstraint [] resultsToArray(
-            ArrayList<SecurityConstraint> results) {
-        if(results == null || results.size() == 0) {
+    private SecurityConstraint[] resultsToArray(ArrayList<SecurityConstraint> results) {
+        if (results == null || results.size() == 0) {
             return null;
         }
-        return results.toArray(new SecurityConstraint [0]);
+        return results.toArray(new SecurityConstraint[0]);
     }
 
 
     /**
-     * Perform access control based on the specified authorization constraint.
-     * Return <code>true</code> if this constraint is satisfied and processing
-     * should continue, or <code>false</code> otherwise.
+     * Perform access control based on the specified authorization constraint. Return <code>true</code> if this
+     * constraint is satisfied and processing should continue, or <code>false</code> otherwise.
      *
-     * @param request Request we are processing
-     * @param response Response we are creating
+     * @param request     Request we are processing
+     * @param response    Response we are creating
      * @param constraints Security constraint we are enforcing
-     * @param context The Context to which client of this class is attached.
+     * @param context     The Context to which client of this class is attached.
      *
      * @exception IOException if an input/output error occurs
      */
     @Override
-    public boolean hasResourcePermission(Request request,
-                                         Response response,
-                                         SecurityConstraint []constraints,
-                                         Context context)
-        throws IOException {
+    public boolean hasResourcePermission(Request request, Response response, SecurityConstraint[] constraints,
+            Context context) throws IOException {
 
         if (constraints == null || constraints.length == 0) {
             return true;
@@ -844,9 +813,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
                     log.debug("Passing all authenticated users");
                 }
                 status = true;
-            }
-            else if (roles.length == 0 && !constraint.getAllRoles() &&
-                    !constraint.getAuthenticatedUsers()) {
+            } else if (roles.length == 0 && !constraint.getAllRoles() && !constraint.getAuthenticatedUsers()) {
                 if (constraint.getAuthConstraint()) {
                     if (log.isDebugEnabled()) {
                         log.debug("No roles");
@@ -878,8 +845,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
             }
         }
 
-        if (!denyfromall && allRolesMode != AllRolesMode.STRICT_MODE &&
-                !status && principal != null) {
+        if (!denyfromall && allRolesMode != AllRolesMode.STRICT_MODE && !status && principal != null) {
             if (log.isDebugEnabled()) {
                 log.debug("Checking for all roles mode: " + allRolesMode);
             }
@@ -910,10 +876,8 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
         }
 
         // Return a "Forbidden" message denying access to this resource
-        if(!status) {
-            response.sendError
-                (HttpServletResponse.SC_FORBIDDEN,
-                 sm.getString("realmBase.forbidden"));
+        if (!status) {
+            response.sendError(HttpServletResponse.SC_FORBIDDEN, sm.getString("realmBase.forbidden"));
         }
         return status;
 
@@ -921,11 +885,8 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
 
     /**
-     * {@inheritDoc}
-     *
-     * This method or {@link #hasRoleInternal(Principal,
-     * String)} can be overridden by Realm implementations, but the default is
-     * adequate when an instance of <code>GenericPrincipal</code> is used to
+     * {@inheritDoc} This method or {@link #hasRoleInternal(Principal, String)} can be overridden by Realm
+     * implementations, but the default is adequate when an instance of <code>GenericPrincipal</code> is used to
      * represent authenticated Principals from this Realm.
      */
     @Override
@@ -959,20 +920,16 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
 
     /**
-     * Check if the specified Principal has the specified
-     * security role, within the context of this Realm.
-     *
-     * This method or {@link #hasRoleInternal(Principal,
-     * String)} can be overridden by Realm implementations, but the default is
-     * adequate when an instance of <code>GenericPrincipal</code> is used to
-     * represent authenticated Principals from this Realm.
+     * Check if the specified Principal has the specified security role, within the context of this Realm. This method
+     * or {@link #hasRoleInternal(Principal, String)} can be overridden by Realm implementations, but the default is
+     * adequate when an instance of <code>GenericPrincipal</code> is used to represent authenticated Principals from
+     * this Realm.
      *
      * @param principal Principal for whom the role is to be checked
-     * @param role Security role to be checked
+     * @param role      Security role to be checked
      *
-     * @return <code>true</code> if the specified Principal has the specified
-     *         security role, within the context of this Realm; otherwise return
-     *         <code>false</code>.
+     * @return <code>true</code> if the specified Principal has the specified security role, within the context of this
+     *             Realm; otherwise return <code>false</code>.
      */
     protected boolean hasRoleInternal(Principal principal, String role) {
         // Should be overridden in JAASRealm - to avoid pretty inefficient conversions
@@ -986,22 +943,19 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
 
     /**
-     * Enforce any user data constraint required by the security constraint
-     * guarding this request URI.  Return <code>true</code> if this constraint
-     * was not violated and processing should continue, or <code>false</code>
-     * if we have created a response already.
+     * Enforce any user data constraint required by the security constraint guarding this request URI. Return
+     * <code>true</code> if this constraint was not violated and processing should continue, or <code>false</code> if we
+     * have created a response already.
      *
-     * @param request Request we are processing
-     * @param response Response we are creating
+     * @param request     Request we are processing
+     * @param response    Response we are creating
      * @param constraints Security constraint being checked
      *
      * @exception IOException if an input/output error occurs
      */
     @Override
-    public boolean hasUserDataPermission(Request request,
-                                         Response response,
-                                         SecurityConstraint []constraints)
-        throws IOException {
+    public boolean hasUserDataPermission(Request request, Response response, SecurityConstraint[] constraints)
+            throws IOException {
 
         // Is there a relevant user data constraint?
         if (constraints == null || constraints.length == 0) {
@@ -1041,9 +995,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
             if (log.isDebugEnabled()) {
                 log.debug("  SSL redirect is disabled");
             }
-            response.sendError
-                (HttpServletResponse.SC_FORBIDDEN,
-                 request.getRequestURI());
+            response.sendError(HttpServletResponse.SC_FORBIDDEN, request.getRequestURI());
             return false;
         }
 
@@ -1054,17 +1006,15 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
         // Protocol
         file.append(protocol).append("://").append(host);
         // Host with port
-        if(redirectPort != 443) {
+        if (redirectPort != 443) {
             file.append(':').append(redirectPort);
         }
         // URI
         file.append(request.getRequestURI());
         String requestedSessionId = request.getRequestedSessionId();
-        if ((requestedSessionId != null) &&
-            request.isRequestedSessionIdFromURL()) {
+        if ((requestedSessionId != null) && request.isRequestedSessionIdFromURL()) {
             file.append(';');
-            file.append(SessionConfig.getSessionUriParamName(
-                    request.getContext()));
+            file.append(SessionConfig.getSessionUriParamName(request.getContext()));
             file.append('=');
             file.append(requestedSessionId);
         }
@@ -1109,12 +1059,11 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
     }
 
     /**
-     * Prepare for the beginning of active use of the public methods of this
-     * component and implement the requirements of
+     * Prepare for the beginning of active use of the public methods of this component and implement the requirements of
      * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
      *
-     * @exception LifecycleException if this component detects a fatal error
-     *  that prevents this component from being used
+     * @exception LifecycleException if this component detects a fatal error that prevents this component from being
+     *                                   used
      */
     @Override
     protected void startInternal() throws LifecycleException {
@@ -1127,12 +1076,10 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
 
     /**
-     * Gracefully terminate the active use of the public methods of this
-     * component and implement the requirements of
+     * Gracefully terminate the active use of the public methods of this component and implement the requirements of
      * {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
      *
-     * @exception LifecycleException if this component detects a fatal error
-     *  that needs to be reported
+     * @exception LifecycleException if this component detects a fatal error that needs to be reported
      */
     @Override
     protected void stopInternal() throws LifecycleException {
@@ -1162,8 +1109,10 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
     /**
      * Return the digest associated with given principal's user name.
-     * @param username the user name
+     *
+     * @param username  the user name
      * @param realmName the realm name
+     *
      * @return the digest for the specified user
      */
     protected String getDigest(String username, String realmName) {
@@ -1172,14 +1121,14 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
             return getPassword(username);
         }
 
-        String digestValue = username + ":" + realmName + ":"
-            + getPassword(username);
+        String digestValue = username + ":" + realmName + ":" + getPassword(username);
 
         byte[] valueBytes = null;
         try {
             valueBytes = digestValue.getBytes(getDigestCharset());
         } catch (UnsupportedEncodingException uee) {
-            throw new IllegalArgumentException(sm.getString("realmBase.invalidDigestEncoding", getDigestEncoding()), uee);
+            throw new IllegalArgumentException(sm.getString("realmBase.invalidDigestEncoding", getDigestEncoding()),
+                    uee);
         }
 
         return MD5Encoder.encode(ConcurrentMessageDigest.digestMD5(valueBytes));
@@ -1207,7 +1156,9 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
     /**
      * Get the password for the specified user.
+     *
      * @param username The user name
+     *
      * @return the password associated with the given principal's user name.
      */
     protected abstract String getPassword(String username);
@@ -1215,13 +1166,15 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
     /**
      * Get the principal associated with the specified certificate.
+     *
      * @param usercert The user certificate
+     *
      * @return the Principal associated with the given certificate.
      */
     protected Principal getPrincipal(X509Certificate usercert) {
         String username = x509UsernameRetriever.getUsername(usercert);
 
-        if(log.isDebugEnabled()) {
+        if (log.isDebugEnabled()) {
             log.debug(sm.getString("realmBase.gotX509Username", username));
         }
 
@@ -1231,7 +1184,9 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
     /**
      * Get the principal associated with the specified user.
+     *
      * @param username The user name
+     *
      * @return the Principal associated with the given user name.
      */
     protected abstract Principal getPrincipal(String username);
@@ -1240,15 +1195,15 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
     /**
      * Get the principal associated with the specified user name.
      *
-     * @param username The user name
+     * @param username      The user name
      * @param gssCredential the GSS credential of the principal
+     *
      * @return the principal associated with the given user name.
-     * @deprecated This will be removed in Tomcat 10 onwards. Use
-     *             {@link #getPrincipal(GSSName, GSSCredential)} instead.
+     *
+     * @deprecated This will be removed in Tomcat 10 onwards. Use {@link #getPrincipal(GSSName, GSSCredential)} instead.
      */
     @Deprecated
-    protected Principal getPrincipal(String username,
-            GSSCredential gssCredential) {
+    protected Principal getPrincipal(String username, GSSCredential gssCredential) {
         Principal p = getPrincipal(username);
 
         if (p instanceof GenericPrincipal) {
@@ -1262,12 +1217,12 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
     /**
      * Get the principal associated with the specified {@link GSSName}.
      *
-     * @param gssName The GSS name
+     * @param gssName       The GSS name
      * @param gssCredential the GSS credential of the principal
+     *
      * @return the principal associated with the given user name.
      */
-    protected Principal getPrincipal(GSSName gssName,
-            GSSCredential gssCredential) {
+    protected Principal getPrincipal(GSSName gssName, GSSCredential gssCredential) {
         String name = gssName.toString();
 
         if (isStripRealmForGss()) {
@@ -1289,10 +1244,9 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
 
     /**
-     * Return the Server object that is the ultimate parent for the container
-     * with which this Realm is associated. If the server cannot be found (eg
-     * because the container hierarchy is not complete), <code>null</code> is
-     * returned.
+     * Return the Server object that is the ultimate parent for the container with which this Realm is associated. If
+     * the server cannot be found (eg because the container hierarchy is not complete), <code>null</code> is returned.
+     *
      * @return the Server associated with the realm
      */
     protected Server getServer() {
@@ -1304,7 +1258,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
             c = c.getParent();
         }
         if (c instanceof Engine) {
-            Service s = ((Engine)c).getService();
+            Service s = ((Engine) c).getService();
             if (s != null) {
                 return s.getServer();
             }
@@ -1316,38 +1270,33 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
     // --------------------------------------------------------- Static Methods
 
     /**
-     * Generate a stored credential string for the given password and associated
-     * parameters.
-     * <p>The following parameters are supported:</p>
+     * Generate a stored credential string for the given password and associated parameters.
+     * <p>
+     * The following parameters are supported:
+     * </p>
      * <ul>
-     * <li><b>-a</b> - The algorithm to use to generate the stored
-     *                 credential. If not specified a default of SHA-512 will be
-     *                 used.</li>
-     * <li><b>-e</b> - The encoding to use for any byte to/from character
-     *                 conversion that may be necessary. If not specified, the
-     *                 system encoding ({@link Charset#defaultCharset()}) will
-     *                 be used.</li>
-     * <li><b>-i</b> - The number of iterations to use when generating the
-     *                 stored credential. If not specified, the default for the
-     *                 CredentialHandler will be used.</li>
-     * <li><b>-s</b> - The length (in bytes) of salt to generate and store as
-     *                 part of the credential. If not specified, the default for
-     *                 the CredentialHandler will be used.</li>
-     * <li><b>-k</b> - The length (in bits) of the key(s), if any, created while
-     *                 generating the credential. If not specified, the default
-     *                 for the CredentialHandler will be used.</li>
-     * <li><b>-h</b> - The fully qualified class name of the CredentialHandler
-     *                 to use. If not specified, the built-in handlers will be
-     *                 tested in turn and the first one to accept the specified
-     *                 algorithm will be used.</li>
+     * <li><b>-a</b> - The algorithm to use to generate the stored credential. If not specified a default of SHA-512
+     * will be used.</li>
+     * <li><b>-e</b> - The encoding to use for any byte to/from character conversion that may be necessary. If not
+     * specified, the system encoding ({@link Charset#defaultCharset()}) will be used.</li>
+     * <li><b>-i</b> - The number of iterations to use when generating the stored credential. If not specified, the
+     * default for the CredentialHandler will be used.</li>
+     * <li><b>-s</b> - The length (in bytes) of salt to generate and store as part of the credential. If not specified,
+     * the default for the CredentialHandler will be used.</li>
+     * <li><b>-k</b> - The length (in bits) of the key(s), if any, created while generating the credential. If not
+     * specified, the default for the CredentialHandler will be used.</li>
+     * <li><b>-h</b> - The fully qualified class name of the CredentialHandler to use. If not specified, the built-in
+     * handlers will be tested in turn and the first one to accept the specified algorithm will be used.</li>
      * </ul>
-     * <p>This generation process currently supports the following
-     * CredentialHandlers, the correct one being selected based on the algorithm
-     * specified:</p>
+     * <p>
+     * This generation process currently supports the following CredentialHandlers, the correct one being selected based
+     * on the algorithm specified:
+     * </p>
      * <ul>
      * <li>{@link MessageDigestCredentialHandler}</li>
      * <li>{@link SecretKeyCredentialHandler}</li>
      * </ul>
+     *
      * @param args The parameters passed on the command line
      */
     public static void main(String args[]) {
@@ -1370,37 +1319,36 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
         int argIndex = 0;
 
-        while (args.length > argIndex + 2 && args[argIndex].length() == 2 &&
-                args[argIndex].charAt(0) == '-' ) {
+        while (args.length > argIndex + 2 && args[argIndex].length() == 2 && args[argIndex].charAt(0) == '-') {
             switch (args[argIndex].charAt(1)) {
-            case 'a': {
-                algorithm = args[argIndex + 1];
-                break;
-            }
-            case 'e': {
-                encoding = args[argIndex + 1];
-                break;
-            }
-            case 'i': {
-                iterations = Integer.parseInt(args[argIndex + 1]);
-                break;
-            }
-            case 's': {
-                saltLength = Integer.parseInt(args[argIndex + 1]);
-                break;
-            }
-            case 'k': {
-                keyLength = Integer.parseInt(args[argIndex + 1]);
-                break;
-            }
-            case 'h': {
-                handlerClassName = args[argIndex + 1];
-                break;
-            }
-            default: {
-                usage();
-                return;
-            }
+                case 'a': {
+                    algorithm = args[argIndex + 1];
+                    break;
+                }
+                case 'e': {
+                    encoding = args[argIndex + 1];
+                    break;
+                }
+                case 'i': {
+                    iterations = Integer.parseInt(args[argIndex + 1]);
+                    break;
+                }
+                case 's': {
+                    saltLength = Integer.parseInt(args[argIndex + 1]);
+                    break;
+                }
+                case 'k': {
+                    keyLength = Integer.parseInt(args[argIndex + 1]);
+                    break;
+                }
+                case 'h': {
+                    handlerClassName = args[argIndex + 1];
+                    break;
+                }
+                default: {
+                    usage();
+                    return;
+                }
             }
             argIndex += 2;
         }
@@ -1408,12 +1356,12 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
         // Determine defaults for -a and -h. The rules are more complex to
         // express than the implementation:
         // - if neither -a nor -h is set, use SHA-512 and
-        //   MessageDigestCredentialHandler
+        // MessageDigestCredentialHandler
         // - if only -a is set the built-in handlers will be searched in order
-        //   (MessageDigestCredentialHandler, SecretKeyCredentialHandler) and
-        //   the first handler that supports the algorithm will be used
+        // (MessageDigestCredentialHandler, SecretKeyCredentialHandler) and
+        // the first handler that supports the algorithm will be used
         // - if only -h is set no default will be used for -a. The handler may
-        //   or may nor support -a and may or may not supply a sensible default
+        // or may nor support -a and may or may not supply a sensible default
         if (algorithm == null && handlerClassName == null) {
             algorithm = "SHA-512";
         }
@@ -1467,12 +1415,11 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
     private static void usage() {
         System.out.println("Usage: RealmBase [-a <algorithm>] [-e <encoding>] " +
-                "[-i <iterations>] [-s <salt-length>] [-k <key-length>] " +
-                "[-h <handler-class-name>] <credentials>");
+                "[-i <iterations>] [-s <salt-length>] [-k <key-length>] " + "[-h <handler-class-name>] <credentials>");
     }
 
 
-    // -------------------- JMX and Registration  --------------------
+    // -------------------- JMX and Registration --------------------
 
     @Override
     public String getObjectNameKeyProperties() {
@@ -1508,15 +1455,14 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
 
         private final String name;
         /**
-         * Use the strict servlet spec interpretation which requires that the user
-         * have one of the web-app/security-role/role-name
+         * Use the strict servlet spec interpretation which requires that the user have one of the
+         * web-app/security-role/role-name
          */
         public static final AllRolesMode STRICT_MODE = new AllRolesMode("strict");
         /** Allow any authenticated user */
         public static final AllRolesMode AUTH_ONLY_MODE = new AllRolesMode("authOnly");
         /**
-         * Allow any authenticated user only if there are no
-         * web-app/security-roles
+         * Allow any authenticated user only if there are no web-app/security-roles
          */
         public static final AllRolesMode STRICT_AUTH_ONLY_MODE = new AllRolesMode("strictAuthOnly");
 
@@ -1529,8 +1475,7 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
             } else if (name.equalsIgnoreCase(STRICT_AUTH_ONLY_MODE.name)) {
                 mode = STRICT_AUTH_ONLY_MODE;
             } else {
-                throw new IllegalStateException(
-                        sm.getString("realmBase.unknownAllRolesMode", name));
+                throw new IllegalStateException(sm.getString("realmBase.unknownAllRolesMode", name));
             }
             return mode;
         }
@@ -1560,20 +1505,21 @@ public abstract class RealmBase extends LifecycleMBeanBase implements Realm {
         }
     }
 
-    private static X509UsernameRetriever createUsernameRetriever(String className)
-        throws LifecycleException {
-        if(null == className || className.trim().isEmpty()) {
+    private static X509UsernameRetriever createUsernameRetriever(String className) throws LifecycleException {
+        if (null == className || className.trim().isEmpty()) {
             return new X509SubjectDnRetriever();
         }
 
         try {
             @SuppressWarnings("unchecked")
-            Class<? extends X509UsernameRetriever> clazz = (Class<? extends X509UsernameRetriever>)Class.forName(className);
+            Class<? extends X509UsernameRetriever> clazz = (Class<? extends X509UsernameRetriever>) Class
+                    .forName(className);
             return clazz.getConstructor().newInstance();
         } catch (ReflectiveOperationException e) {
             throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.newInstance", className), e);
         } catch (ClassCastException e) {
-            throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassCastException", className), e);
+            throw new LifecycleException(
+                    sm.getString("realmBase.createUsernameRetriever.ClassCastException", className), e);
         }
     }
 
diff --git a/java/org/apache/catalina/realm/UserDatabaseRealm.java b/java/org/apache/catalina/realm/UserDatabaseRealm.java
index 822c807d85..588c806143 100644
--- a/java/org/apache/catalina/realm/UserDatabaseRealm.java
+++ b/java/org/apache/catalina/realm/UserDatabaseRealm.java
@@ -34,13 +34,12 @@ import org.apache.naming.ContextBindings;
 import org.apache.tomcat.util.ExceptionUtils;
 
 /**
- * Implementation of {@link org.apache.catalina.Realm} that is based on an
- * implementation of {@link UserDatabase} made available through the JNDI
- * resources configured for this instance of Catalina. Set the
- * <code>resourceName</code> parameter to the JNDI resources name for the
- * configured instance of <code>UserDatabase</code> that we should consult.
+ * Implementation of {@link org.apache.catalina.Realm} that is based on an implementation of {@link UserDatabase} made
+ * available through the JNDI resources configured for this instance of Catalina. Set the <code>resourceName</code>
+ * parameter to the JNDI resources name for the configured instance of <code>UserDatabase</code> that we should consult.
  *
  * @author Craig R. McClanahan
+ *
  * @since 4.1
  */
 public class UserDatabaseRealm extends RealmBase {
@@ -48,15 +47,13 @@ public class UserDatabaseRealm extends RealmBase {
     // ----------------------------------------------------- Instance Variables
 
     /**
-     * The <code>UserDatabase</code> we will use to authenticate users and
-     * identify associated roles.
+     * The <code>UserDatabase</code> we will use to authenticate users and identify associated roles.
      */
     protected volatile UserDatabase database = null;
     private final Object databaseLock = new Object();
 
     /**
-     * The global JNDI name of the <code>UserDatabase</code> resource we will be
-     * utilizing.
+     * The global JNDI name of the <code>UserDatabase</code> resource we will be utilizing.
      */
     protected String resourceName = "UserDatabase";
 
@@ -66,9 +63,8 @@ public class UserDatabaseRealm extends RealmBase {
     private boolean localJndiResource = false;
 
     /**
-     * Use a static principal disconnected from the database. This prevents live
-     * updates to users and roles having an effect on authenticated principals,
-     * but reduces use of the database.
+     * Use a static principal disconnected from the database. This prevents live updates to users and roles having an
+     * effect on authenticated principals, but reduces use of the database.
      */
     private boolean useStaticPrincipal = false;
 
@@ -76,8 +72,7 @@ public class UserDatabaseRealm extends RealmBase {
     // ------------------------------------------------------------- Properties
 
     /**
-     * @return the global JNDI name of the <code>UserDatabase</code> resource we
-     *         will be using.
+     * @return the global JNDI name of the <code>UserDatabase</code> resource we will be using.
      */
     public String getResourceName() {
         return resourceName;
@@ -85,8 +80,7 @@ public class UserDatabaseRealm extends RealmBase {
 
 
     /**
-     * Set the global JNDI name of the <code>UserDatabase</code> resource we
-     * will be using.
+     * Set the global JNDI name of the <code>UserDatabase</code> resource we will be using.
      *
      * @param resourceName The new global JNDI name
      */
@@ -105,6 +99,7 @@ public class UserDatabaseRealm extends RealmBase {
 
     /**
      * Allows using a static principal disconnected from the user database.
+     *
      * @param useStaticPrincipal the new value
      */
     public void setUseStaticPrincipal(boolean useStaticPrincipal) {
@@ -113,12 +108,11 @@ public class UserDatabaseRealm extends RealmBase {
 
 
     /**
-     * Determines whether this Realm is configured to obtain the associated
-     * {@link UserDatabase} from the global JNDI context or a local (web
-     * application) JNDI context.
+     * Determines whether this Realm is configured to obtain the associated {@link UserDatabase} from the global JNDI
+     * context or a local (web application) JNDI context.
      *
-     * @return {@code true} if a local JNDI context will be used, {@code false}
-     *         if the the global JNDI context will be used
+     * @return {@code true} if a local JNDI context will be used, {@code false} if the the global JNDI context will be
+     *             used
      */
     public boolean getLocalJndiResource() {
         return localJndiResource;
@@ -126,11 +120,10 @@ public class UserDatabaseRealm extends RealmBase {
 
 
     /**
-     * Configure whether this Realm obtains the associated {@link UserDatabase}
-     * from the global JNDI context or a local (web application) JNDI context.
+     * Configure whether this Realm obtains the associated {@link UserDatabase} from the global JNDI context or a local
+     * (web application) JNDI context.
      *
-     * @param localJndiResource {@code true} to use a local JNDI context,
-     *                          {@code false} to use the global JNDI context
+     * @param localJndiResource {@code true} to use a local JNDI context, {@code false} to use the global JNDI context
      */
     public void setLocalJndiResource(boolean localJndiResource) {
         this.localJndiResource = localJndiResource;
@@ -211,8 +204,7 @@ public class UserDatabaseRealm extends RealmBase {
 
 
     /*
-     * Can't do this in startInternal() with local JNDI as the local JNDI
-     * context won't be initialised at this point.
+     * Can't do this in startInternal() with local JNDI as the local JNDI context won't be initialised at this point.
      */
     private UserDatabase getUserDatabase() {
         // DCL so database MUST be volatile
@@ -261,12 +253,10 @@ public class UserDatabaseRealm extends RealmBase {
 
 
     /**
-     * Gracefully terminate the active use of the public methods of this
-     * component and implement the requirements of
+     * Gracefully terminate the active use of the public methods of this component and implement the requirements of
      * {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
      *
-     * @exception LifecycleException if this component detects a fatal error
-     *                that needs to be reported
+     * @exception LifecycleException if this component detects a fatal error that needs to be reported
      */
     @Override
     protected void stopInternal() throws LifecycleException {
diff --git a/java/org/apache/catalina/realm/X509SubjectDnRetriever.java b/java/org/apache/catalina/realm/X509SubjectDnRetriever.java
index 6636e810a1..f8d3a4a976 100644
--- a/java/org/apache/catalina/realm/X509SubjectDnRetriever.java
+++ b/java/org/apache/catalina/realm/X509SubjectDnRetriever.java
@@ -19,8 +19,7 @@ package org.apache.catalina.realm;
 import java.security.cert.X509Certificate;
 
 /**
- * An X509UsernameRetriever that returns a certificate's entire
- * SubjectDN as the username.
+ * An X509UsernameRetriever that returns a certificate's entire SubjectDN as the username.
  */
 public class X509SubjectDnRetriever implements X509UsernameRetriever {
 
diff --git a/java/org/apache/catalina/realm/X509UsernameRetriever.java b/java/org/apache/catalina/realm/X509UsernameRetriever.java
index 671fe08d86..d4bc630b3a 100644
--- a/java/org/apache/catalina/realm/X509UsernameRetriever.java
+++ b/java/org/apache/catalina/realm/X509UsernameRetriever.java
@@ -26,8 +26,8 @@ public interface X509UsernameRetriever {
      * Gets a user name from an X509Certificate.
      *
      * @param cert The certificate containing the user name.
-     * @return An appropriate user name obtained from one or more fields
-     *         in the certificate.
+     *
+     * @return An appropriate user name obtained from one or more fields in the certificate.
      */
     public String getUsername(X509Certificate cert);
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


[tomcat] 02/07: Code cleanup (format). No functional change.

Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 3c8ee6e86ba0269ab7fef672772ae3ce1a276078
Author: Mark Thomas <ma...@apache.org>
AuthorDate: Tue Jan 24 11:14:19 2023 +0000

    Code cleanup (format). No functional change.
---
 .../catalina/filters/AddDefaultCharsetFilter.java  |  34 +-
 java/org/apache/catalina/filters/Constants.java    |  37 +-
 java/org/apache/catalina/filters/CorsFilter.java   | 550 +++++++++------------
 .../catalina/filters/CsrfPreventionFilter.java     | 123 ++---
 .../catalina/filters/CsrfPreventionFilterBase.java |  34 +-
 .../org/apache/catalina/filters/ExpiresFilter.java | 438 +++++++---------
 .../catalina/filters/FailedRequestFilter.java      |  25 +-
 java/org/apache/catalina/filters/FilterBase.java   |  30 +-
 .../catalina/filters/HttpHeaderSecurityFilter.java |  15 +-
 .../apache/catalina/filters/RemoteAddrFilter.java  |  17 +-
 .../apache/catalina/filters/RemoteCIDRFilter.java  |  27 +-
 .../apache/catalina/filters/RemoteHostFilter.java  |  16 +-
 .../apache/catalina/filters/RemoteIpFilter.java    | 263 +++++-----
 .../catalina/filters/RequestDumperFilter.java      |  69 ++-
 .../org/apache/catalina/filters/RequestFilter.java |  91 ++--
 .../catalina/filters/RestCsrfPreventionFilter.java |  71 ++-
 .../catalina/filters/SessionInitializerFilter.java |  23 +-
 .../filters/SetCharacterEncodingFilter.java        |  88 ++--
 .../apache/catalina/filters/WebdavFixFilter.java   |  58 +--
 19 files changed, 847 insertions(+), 1162 deletions(-)

diff --git a/java/org/apache/catalina/filters/AddDefaultCharsetFilter.java b/java/org/apache/catalina/filters/AddDefaultCharsetFilter.java
index 98adb4fe52..67175c3e4e 100644
--- a/java/org/apache/catalina/filters/AddDefaultCharsetFilter.java
+++ b/java/org/apache/catalina/filters/AddDefaultCharsetFilter.java
@@ -32,17 +32,13 @@ import org.apache.juli.logging.LogFactory;
 
 
 /**
- * Filter that explicitly sets the default character set for media subtypes of
- * the "text" type to ISO-8859-1, or another user defined character set. RFC2616
- * explicitly states that browsers must use ISO-8859-1 if no character set is
- * defined for media with subtype "text". However, browsers may attempt to
- * auto-detect the character set. This may be exploited by an attacker to
- * perform an XSS attack. Internet Explorer has this behaviour by default. Other
- * browsers have an option to enable it.<br>
- *
- * This filter prevents the attack by explicitly setting a character set. Unless
- * the provided character set is explicitly overridden by the user - in which
- * case they deserve everything they get - the browser will adhere to an
+ * Filter that explicitly sets the default character set for media subtypes of the "text" type to ISO-8859-1, or another
+ * user defined character set. RFC2616 explicitly states that browsers must use ISO-8859-1 if no character set is
+ * defined for media with subtype "text". However, browsers may attempt to auto-detect the character set. This may be
+ * exploited by an attacker to perform an XSS attack. Internet Explorer has this behaviour by default. Other browsers
+ * have an option to enable it.<br>
+ * This filter prevents the attack by explicitly setting a character set. Unless the provided character set is
+ * explicitly overridden by the user - in which case they deserve everything they get - the browser will adhere to an
  * explicitly set character set, thus preventing the XSS attack.
  */
 public class AddDefaultCharsetFilter extends FilterBase {
@@ -67,25 +63,22 @@ public class AddDefaultCharsetFilter extends FilterBase {
     @Override
     public void init(FilterConfig filterConfig) throws ServletException {
         super.init(filterConfig);
-        if (encoding == null || encoding.length() == 0 ||
-                encoding.equalsIgnoreCase("default")) {
+        if (encoding == null || encoding.length() == 0 || encoding.equalsIgnoreCase("default")) {
             encoding = DEFAULT_ENCODING;
         } else if (encoding.equalsIgnoreCase("system")) {
             encoding = Charset.defaultCharset().name();
         } else if (!Charset.isSupported(encoding)) {
-            throw new IllegalArgumentException(sm.getString(
-                    "addDefaultCharset.unsupportedCharset", encoding));
+            throw new IllegalArgumentException(sm.getString("addDefaultCharset.unsupportedCharset", encoding));
         }
     }
 
     @Override
-    public void doFilter(ServletRequest request, ServletResponse response,
-            FilterChain chain) throws IOException, ServletException {
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+            throws IOException, ServletException {
 
         // Wrap the response
         if (response instanceof HttpServletResponse) {
-            ResponseWrapper wrapped =
-                new ResponseWrapper((HttpServletResponse)response, encoding);
+            ResponseWrapper wrapped = new ResponseWrapper((HttpServletResponse) response, encoding);
             chain.doFilter(request, wrapped);
         } else {
             chain.doFilter(request, response);
@@ -93,8 +86,7 @@ public class AddDefaultCharsetFilter extends FilterBase {
     }
 
     /**
-     * Wrapper that adds a character set for text media types if no character
-     * set is specified.
+     * Wrapper that adds a character set for text media types if no character set is specified.
      */
     public static class ResponseWrapper extends HttpServletResponseWrapper {
 
diff --git a/java/org/apache/catalina/filters/Constants.java b/java/org/apache/catalina/filters/Constants.java
index ab550b1419..25693aef56 100644
--- a/java/org/apache/catalina/filters/Constants.java
+++ b/java/org/apache/catalina/filters/Constants.java
@@ -20,38 +20,29 @@ package org.apache.catalina.filters;
 /**
  * Manifest constants for this Java package.
  *
- *
  * @author Craig R. McClanahan
  */
 public final class Constants {
 
     /**
-     * The session attribute key under which the CSRF nonce
-     * cache will be stored.
+     * The session attribute key under which the CSRF nonce cache will be stored.
      */
-    public static final String CSRF_NONCE_SESSION_ATTR_NAME =
-        "org.apache.catalina.filters.CSRF_NONCE";
+    public static final String CSRF_NONCE_SESSION_ATTR_NAME = "org.apache.catalina.filters.CSRF_NONCE";
 
     /**
-     * The request attribute key under which the current
-     * requests's CSRF nonce can be found.
+     * The request attribute key under which the current requests's CSRF nonce can be found.
      */
-    public static final String CSRF_NONCE_REQUEST_ATTR_NAME =
-        "org.apache.catalina.filters.CSRF_REQUEST_NONCE";
+    public static final String CSRF_NONCE_REQUEST_ATTR_NAME = "org.apache.catalina.filters.CSRF_REQUEST_NONCE";
 
     /**
-     * The name of the request parameter which carries CSRF nonces
-     * from the client to the server for validation.
+     * The name of the request parameter which carries CSRF nonces from the client to the server for validation.
      */
-    public static final String CSRF_NONCE_REQUEST_PARAM =
-        "org.apache.catalina.filters.CSRF_NONCE";
+    public static final String CSRF_NONCE_REQUEST_PARAM = "org.apache.catalina.filters.CSRF_NONCE";
 
     /**
-     * The servlet context attribute key under which the
-     * CSRF request parameter name can be found.
+     * The servlet context attribute key under which the CSRF request parameter name can be found.
      */
-    public static final String CSRF_NONCE_REQUEST_PARAM_NAME_KEY =
-        "org.apache.catalina.filters.CSRF_NONCE_PARAM_NAME";
+    public static final String CSRF_NONCE_REQUEST_PARAM_NAME_KEY = "org.apache.catalina.filters.CSRF_NONCE_PARAM_NAME";
 
     public static final String METHOD_GET = "GET";
 
@@ -62,16 +53,12 @@ public final class Constants {
     public static final String CSRF_REST_NONCE_HEADER_REQUIRED_VALUE = "Required";
 
     /**
-     * The session attribute key under which the CSRF REST nonce
-     * cache will be stored.
+     * The session attribute key under which the CSRF REST nonce cache will be stored.
      */
-    public static final String CSRF_REST_NONCE_SESSION_ATTR_NAME =
-        "org.apache.catalina.filters.CSRF_REST_NONCE";
+    public static final String CSRF_REST_NONCE_SESSION_ATTR_NAME = "org.apache.catalina.filters.CSRF_REST_NONCE";
 
     /**
-     * The servlet context attribute key under which the
-     * CSRF REST header name can be found.
+     * The servlet context attribute key under which the CSRF REST header name can be found.
      */
-    public static final String CSRF_REST_NONCE_HEADER_NAME_KEY =
-        "org.apache.catalina.filters.CSRF_REST_NONCE_HEADER_NAME";
+    public static final String CSRF_REST_NONCE_HEADER_NAME_KEY = "org.apache.catalina.filters.CSRF_REST_NONCE_HEADER_NAME";
 }
diff --git a/java/org/apache/catalina/filters/CorsFilter.java b/java/org/apache/catalina/filters/CorsFilter.java
index 8b80287f51..ef9705510c 100644
--- a/java/org/apache/catalina/filters/CorsFilter.java
+++ b/java/org/apache/catalina/filters/CorsFilter.java
@@ -43,25 +43,19 @@ import org.apache.tomcat.util.res.StringManager;
 
 /**
  * <p>
- * A {@link javax.servlet.Filter} that enable client-side cross-origin requests
- * by implementing W3C's CORS (<b>C</b>ross-<b>O</b>rigin <b>R</b>esource
- * <b>S</b>haring) specification for resources. Each {@link HttpServletRequest}
- * request is inspected as per specification, and appropriate response headers
- * are added to {@link HttpServletResponse}.
+ * A {@link javax.servlet.Filter} that enable client-side cross-origin requests by implementing W3C's CORS
+ * (<b>C</b>ross-<b>O</b>rigin <b>R</b>esource <b>S</b>haring) specification for resources. Each
+ * {@link HttpServletRequest} request is inspected as per specification, and appropriate response headers are added to
+ * {@link HttpServletResponse}.
  * </p>
- *
  * <p>
- * By default, it also sets following request attributes, that help to
- * determine the nature of the request downstream.
+ * By default, it also sets following request attributes, that help to determine the nature of the request downstream.
  * </p>
  * <ul>
- * <li><b>cors.isCorsRequest:</b> Flag to determine if the request is a CORS
- * request. Set to <code>true</code> if a CORS request; <code>false</code>
- * otherwise.</li>
- * <li><b>cors.request.origin:</b> The Origin URL, i.e. the URL of the page from
- * where the request is originated.</li>
- * <li>
- * <b>cors.request.type:</b> Type of request. Possible values:
+ * <li><b>cors.isCorsRequest:</b> Flag to determine if the request is a CORS request. Set to <code>true</code> if a CORS
+ * request; <code>false</code> otherwise.</li>
+ * <li><b>cors.request.origin:</b> The Origin URL, i.e. the URL of the page from where the request is originated.</li>
+ * <li><b>cors.request.type:</b> Type of request. Possible values:
  * <ul>
  * <li>SIMPLE: A request which is not preceded by a pre-flight request.</li>
  * <li>ACTUAL: A request which is preceded by a pre-flight request.</li>
@@ -70,15 +64,12 @@ import org.apache.tomcat.util.res.StringManager;
  * <li>INVALID_CORS: A cross-origin request which is invalid.</li>
  * </ul>
  * </li>
- * <li><b>cors.request.headers:</b> Request headers sent as
- * 'Access-Control-Request-Headers' header, for pre-flight request.</li>
+ * <li><b>cors.request.headers:</b> Request headers sent as 'Access-Control-Request-Headers' header, for pre-flight
+ * request.</li>
  * </ul>
- *
- * If you extend this class and override one or more of the getXxx() methods,
- * consider whether you also need to override
- * {@link CorsFilter#doFilter(ServletRequest, ServletResponse, FilterChain)} and
- * add appropriate locking so that the {@code doFilter()} method executes with a
- * consistent configuration.
+ * If you extend this class and override one or more of the getXxx() methods, consider whether you also need to override
+ * {@link CorsFilter#doFilter(ServletRequest, ServletResponse, FilterChain)} and add appropriate locking so that the
+ * {@code doFilter()} method executes with a consistent configuration.
  *
  * @see <a href="http://www.w3.org/TR/cors/">CORS specification</a>
  */
@@ -91,8 +82,7 @@ public class CorsFilter extends GenericFilter {
 
 
     /**
-     * A {@link Collection} of origins consisting of zero or more origins that
-     * are allowed access to the resource.
+     * A {@link Collection} of origins consisting of zero or more origins that are allowed access to the resource.
      */
     private final Collection<String> allowedOrigins = new HashSet<>();
 
@@ -102,34 +92,29 @@ public class CorsFilter extends GenericFilter {
     private boolean anyOriginAllowed;
 
     /**
-     * A {@link Collection} of methods consisting of zero or more methods that
-     * are supported by the resource.
+     * A {@link Collection} of methods consisting of zero or more methods that are supported by the resource.
      */
     private final Collection<String> allowedHttpMethods = new HashSet<>();
 
     /**
-     * A {@link Collection} of headers consisting of zero or more header field
-     * names that are supported by the resource.
+     * A {@link Collection} of headers consisting of zero or more header field names that are supported by the resource.
      */
     private final Collection<String> allowedHttpHeaders = new HashSet<>();
 
     /**
-     * A {@link Collection} of exposed headers consisting of zero or more header
-     * field names of headers other than the simple response headers that the
-     * resource might use and can be exposed.
+     * A {@link Collection} of exposed headers consisting of zero or more header field names of headers other than the
+     * simple response headers that the resource might use and can be exposed.
      */
     private final Collection<String> exposedHeaders = new HashSet<>();
 
     /**
-     * A supports credentials flag that indicates whether the resource supports
-     * user credentials in the request. It is true when the resource does and
-     * false otherwise.
+     * A supports credentials flag that indicates whether the resource supports user credentials in the request. It is
+     * true when the resource does and false otherwise.
      */
     private boolean supportsCredentials;
 
     /**
-     * Indicates (in seconds) how long the results of a pre-flight request can
-     * be cached in a pre-flight result cache.
+     * Indicates (in seconds) how long the results of a pre-flight request can be cached in a pre-flight result cache.
      */
     private long preflightMaxAge;
 
@@ -140,11 +125,9 @@ public class CorsFilter extends GenericFilter {
 
 
     @Override
-    public void doFilter(final ServletRequest servletRequest,
-            final ServletResponse servletResponse, final FilterChain filterChain)
-            throws IOException, ServletException {
-        if (!(servletRequest instanceof HttpServletRequest) ||
-                !(servletResponse instanceof HttpServletResponse)) {
+    public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
+            final FilterChain filterChain) throws IOException, ServletException {
+        if (!(servletRequest instanceof HttpServletRequest) || !(servletResponse instanceof HttpServletResponse)) {
             throw new ServletException(sm.getString("corsFilter.onlyHttp"));
         }
 
@@ -160,53 +143,47 @@ public class CorsFilter extends GenericFilter {
             CorsFilter.decorateCORSProperties(request, requestType);
         }
         switch (requestType) {
-        case SIMPLE:
-            // Handles a Simple CORS request.
-        case ACTUAL:
-            // Handles an Actual CORS request.
-            this.handleSimpleCORS(request, response, filterChain);
-            break;
-        case PRE_FLIGHT:
-            // Handles a Pre-flight CORS request.
-            this.handlePreflightCORS(request, response, filterChain);
-            break;
-        case NOT_CORS:
-            // Handles a Normal request that is not a cross-origin request.
-            this.handleNonCORS(request, response, filterChain);
-            break;
-        default:
-            // Handles a CORS request that violates specification.
-            this.handleInvalidCORS(request, response, filterChain);
-            break;
+            case SIMPLE:
+                // Handles a Simple CORS request.
+            case ACTUAL:
+                // Handles an Actual CORS request.
+                this.handleSimpleCORS(request, response, filterChain);
+                break;
+            case PRE_FLIGHT:
+                // Handles a Pre-flight CORS request.
+                this.handlePreflightCORS(request, response, filterChain);
+                break;
+            case NOT_CORS:
+                // Handles a Normal request that is not a cross-origin request.
+                this.handleNonCORS(request, response, filterChain);
+                break;
+            default:
+                // Handles a CORS request that violates specification.
+                this.handleInvalidCORS(request, response, filterChain);
+                break;
         }
     }
 
 
     @Override
     public void init() throws ServletException {
-        parseAndStore(
-                getInitParameter(PARAM_CORS_ALLOWED_ORIGINS,     DEFAULT_ALLOWED_ORIGINS),
-                getInitParameter(PARAM_CORS_ALLOWED_METHODS,     DEFAULT_ALLOWED_HTTP_METHODS),
-                getInitParameter(PARAM_CORS_ALLOWED_HEADERS,     DEFAULT_ALLOWED_HTTP_HEADERS),
-                getInitParameter(PARAM_CORS_EXPOSED_HEADERS,     DEFAULT_EXPOSED_HEADERS),
+        parseAndStore(getInitParameter(PARAM_CORS_ALLOWED_ORIGINS, DEFAULT_ALLOWED_ORIGINS),
+                getInitParameter(PARAM_CORS_ALLOWED_METHODS, DEFAULT_ALLOWED_HTTP_METHODS),
+                getInitParameter(PARAM_CORS_ALLOWED_HEADERS, DEFAULT_ALLOWED_HTTP_HEADERS),
+                getInitParameter(PARAM_CORS_EXPOSED_HEADERS, DEFAULT_EXPOSED_HEADERS),
                 getInitParameter(PARAM_CORS_SUPPORT_CREDENTIALS, DEFAULT_SUPPORTS_CREDENTIALS),
-                getInitParameter(PARAM_CORS_PREFLIGHT_MAXAGE,    DEFAULT_PREFLIGHT_MAXAGE),
-                getInitParameter(PARAM_CORS_REQUEST_DECORATE,    DEFAULT_DECORATE_REQUEST)
-        );
+                getInitParameter(PARAM_CORS_PREFLIGHT_MAXAGE, DEFAULT_PREFLIGHT_MAXAGE),
+                getInitParameter(PARAM_CORS_REQUEST_DECORATE, DEFAULT_DECORATE_REQUEST));
     }
 
 
     /**
-     * This method returns the parameter's value if it exists, or defaultValue
-     * if not.
-     *
-     * @param name          The parameter's name
+     * This method returns the parameter's value if it exists, or defaultValue if not.
      *
-     * @param defaultValue  The default value to return if the parameter does
-     *                      not exist
+     * @param name         The parameter's name
+     * @param defaultValue The default value to return if the parameter does not exist
      *
-     * @return The parameter's value or the default value if the parameter does
-     *         not exist
+     * @return The parameter's value or the default value if the parameter does not exist
      */
     private String getInitParameter(String name, String defaultValue) {
 
@@ -222,25 +199,23 @@ public class CorsFilter extends GenericFilter {
     /**
      * Handles a CORS request of type {@link CORSRequestType}.SIMPLE.
      *
-     * @param request The {@link HttpServletRequest} object.
-     * @param response The {@link HttpServletResponse} object.
+     * @param request     The {@link HttpServletRequest} object.
+     * @param response    The {@link HttpServletResponse} object.
      * @param filterChain The {@link FilterChain} object.
-     * @throws IOException an IO error occurred
+     *
+     * @throws IOException      an IO error occurred
      * @throws ServletException Servlet error propagation
-     * @see <a href="http://www.w3.org/TR/cors/#resource-requests">Simple
-     *      Cross-Origin Request, Actual Request, and Redirects</a>
+     *
+     * @see <a href="http://www.w3.org/TR/cors/#resource-requests">Simple Cross-Origin Request, Actual Request, and
+     *          Redirects</a>
      */
-    protected void handleSimpleCORS(final HttpServletRequest request,
-            final HttpServletResponse response, final FilterChain filterChain)
-            throws IOException, ServletException {
+    protected void handleSimpleCORS(final HttpServletRequest request, final HttpServletResponse response,
+            final FilterChain filterChain) throws IOException, ServletException {
 
         CorsFilter.CORSRequestType requestType = checkRequestType(request);
-        if (!(requestType == CorsFilter.CORSRequestType.SIMPLE ||
-                requestType == CorsFilter.CORSRequestType.ACTUAL)) {
-            throw new IllegalArgumentException(
-                    sm.getString("corsFilter.wrongType2",
-                            CorsFilter.CORSRequestType.SIMPLE,
-                            CorsFilter.CORSRequestType.ACTUAL));
+        if (!(requestType == CorsFilter.CORSRequestType.SIMPLE || requestType == CorsFilter.CORSRequestType.ACTUAL)) {
+            throw new IllegalArgumentException(sm.getString("corsFilter.wrongType2", CorsFilter.CORSRequestType.SIMPLE,
+                    CorsFilter.CORSRequestType.ACTUAL));
         }
 
         final String origin = request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN);
@@ -267,15 +242,15 @@ public class CorsFilter extends GenericFilter {
     /**
      * Handles CORS pre-flight request.
      *
-     * @param request The {@link HttpServletRequest} object.
-     * @param response The {@link HttpServletResponse} object.
+     * @param request     The {@link HttpServletRequest} object.
+     * @param response    The {@link HttpServletResponse} object.
      * @param filterChain The {@link FilterChain} object.
-     * @throws IOException an IO error occurred
+     *
+     * @throws IOException      an IO error occurred
      * @throws ServletException Servlet error propagation
      */
-    protected void handlePreflightCORS(final HttpServletRequest request,
-            final HttpServletResponse response, final FilterChain filterChain)
-            throws IOException, ServletException {
+    protected void handlePreflightCORS(final HttpServletRequest request, final HttpServletResponse response,
+            final FilterChain filterChain) throws IOException, ServletException {
 
         CORSRequestType requestType = checkRequestType(request);
         if (requestType != CORSRequestType.PRE_FLIGHT) {
@@ -292,8 +267,7 @@ public class CorsFilter extends GenericFilter {
         }
 
         // Section 6.2.3
-        String accessControlRequestMethod = request.getHeader(
-                CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
+        String accessControlRequestMethod = request.getHeader(CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
         if (accessControlRequestMethod == null) {
             handleInvalidCORS(request, response, filterChain);
             return;
@@ -302,11 +276,10 @@ public class CorsFilter extends GenericFilter {
         }
 
         // Section 6.2.4
-        String accessControlRequestHeadersHeader = request.getHeader(
-                CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);
+        String accessControlRequestHeadersHeader = request
+                .getHeader(CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);
         List<String> accessControlRequestHeaders = new ArrayList<>();
-        if (accessControlRequestHeadersHeader != null &&
-                !accessControlRequestHeadersHeader.trim().isEmpty()) {
+        if (accessControlRequestHeadersHeader != null && !accessControlRequestHeadersHeader.trim().isEmpty()) {
             String[] headers = accessControlRequestHeadersHeader.trim().split(",");
             for (String header : headers) {
                 accessControlRequestHeaders.add(header.trim().toLowerCase(Locale.ENGLISH));
@@ -336,19 +309,18 @@ public class CorsFilter extends GenericFilter {
 
 
     /**
-     * Handles a request, that's not a CORS request, but is a valid request i.e.
-     * it is not a cross-origin request. This implementation, just forwards the
-     * request down the filter chain.
+     * Handles a request, that's not a CORS request, but is a valid request i.e. it is not a cross-origin request. This
+     * implementation, just forwards the request down the filter chain.
      *
-     * @param request The {@link HttpServletRequest} object.
-     * @param response The {@link HttpServletResponse} object.
+     * @param request     The {@link HttpServletRequest} object.
+     * @param response    The {@link HttpServletResponse} object.
      * @param filterChain The {@link FilterChain} object.
-     * @throws IOException an IO error occurred
+     *
+     * @throws IOException      an IO error occurred
      * @throws ServletException Servlet error propagation
      */
-    private void handleNonCORS(final HttpServletRequest request,
-            final HttpServletResponse response, final FilterChain filterChain)
-            throws IOException, ServletException {
+    private void handleNonCORS(final HttpServletRequest request, final HttpServletResponse response,
+            final FilterChain filterChain) throws IOException, ServletException {
 
         addStandardHeaders(request, response);
 
@@ -360,16 +332,15 @@ public class CorsFilter extends GenericFilter {
     /**
      * Handles a CORS request that violates specification.
      *
-     * @param request The {@link HttpServletRequest} object.
-     * @param response The {@link HttpServletResponse} object.
+     * @param request     The {@link HttpServletRequest} object.
+     * @param response    The {@link HttpServletResponse} object.
      * @param filterChain The {@link FilterChain} object.
      */
-    private void handleInvalidCORS(final HttpServletRequest request,
-            final HttpServletResponse response, final FilterChain filterChain) {
+    private void handleInvalidCORS(final HttpServletRequest request, final HttpServletResponse response,
+            final FilterChain filterChain) {
         String origin = request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN);
         String method = request.getMethod();
-        String accessControlRequestHeaders = request.getHeader(
-                REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);
+        String accessControlRequestHeaders = request.getHeader(REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);
 
         response.setContentType("text/plain");
         response.setStatus(HttpServletResponse.SC_FORBIDDEN);
@@ -391,11 +362,9 @@ public class CorsFilter extends GenericFilter {
 
 
     /*
-     * Sets a standard set of headers to reduce response variation which in turn
-     * is intended to aid caching.
+     * Sets a standard set of headers to reduce response variation which in turn is intended to aid caching.
      */
-    private void addStandardHeaders(final HttpServletRequest request,
-            final HttpServletResponse response) {
+    private void addStandardHeaders(final HttpServletRequest request, final HttpServletResponse response) {
 
         final String method = request.getMethod();
         final String origin = request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN);
@@ -439,18 +408,15 @@ public class CorsFilter extends GenericFilter {
         Collection<String> exposedHeaders = getExposedHeaders();
         if ((exposedHeaders != null) && (exposedHeaders.size() > 0)) {
             String exposedHeadersString = join(exposedHeaders, ",");
-            response.addHeader(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS,
-                    exposedHeadersString);
+            response.addHeader(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS, exposedHeadersString);
         }
 
         if ("OPTIONS".equals(method)) {
             // For an OPTIONS request, the response will vary based on the
             // value or absence of the following headers. Hence they need be be
             // included in the Vary header.
-            ResponseUtil.addVaryFieldName(
-                    response, CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
-            ResponseUtil.addVaryFieldName(
-                    response, CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);
+            ResponseUtil.addVaryFieldName(response, CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
+            ResponseUtil.addVaryFieldName(response, CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);
 
             // CORS PRE_FLIGHT (OPTIONS) requests set the following headers although
             // non-CORS OPTIONS requests do not need to. The headers are always set
@@ -460,17 +426,14 @@ public class CorsFilter extends GenericFilter {
             // is overridden.
             long preflightMaxAge = getPreflightMaxAge();
             if (preflightMaxAge > 0) {
-                response.addHeader(
-                        CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_MAX_AGE,
-                        String.valueOf(preflightMaxAge));
+                response.addHeader(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_MAX_AGE, String.valueOf(preflightMaxAge));
             }
 
             // Local copy to avoid concurrency issues if getAllowedHttpMethods()
             // is overridden.
             Collection<String> allowedHttpMethods = getAllowedHttpMethods();
-            if  ((allowedHttpMethods != null) && (!allowedHttpMethods.isEmpty())) {
-                response.addHeader(
-                        CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_METHODS,
+            if ((allowedHttpMethods != null) && (!allowedHttpMethods.isEmpty())) {
+                response.addHeader(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_METHODS,
                         join(allowedHttpMethods, ","));
             }
 
@@ -478,8 +441,7 @@ public class CorsFilter extends GenericFilter {
             // is overridden.
             Collection<String> allowedHttpHeaders = getAllowedHttpHeaders();
             if ((allowedHttpHeaders != null) && (!allowedHttpHeaders.isEmpty())) {
-                response.addHeader(
-                        CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_HEADERS,
+                response.addHeader(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_HEADERS,
                         join(allowedHttpHeaders, ","));
             }
         }
@@ -489,22 +451,19 @@ public class CorsFilter extends GenericFilter {
     /**
      * Decorates the {@link HttpServletRequest}, with CORS attributes.
      * <ul>
-     * <li><b>cors.isCorsRequest:</b> Flag to determine if request is a CORS
-     * request. Set to <code>true</code> if CORS request; <code>false</code>
-     * otherwise.</li>
+     * <li><b>cors.isCorsRequest:</b> Flag to determine if request is a CORS request. Set to <code>true</code> if CORS
+     * request; <code>false</code> otherwise.</li>
      * <li><b>cors.request.origin:</b> The Origin URL.</li>
-     * <li><b>cors.request.type:</b> Type of request. Values:
-     * <code>simple</code> or <code>preflight</code> or <code>not_cors</code> or
-     * <code>invalid_cors</code></li>
-     * <li><b>cors.request.headers:</b> Request headers sent as
-     * 'Access-Control-Request-Headers' header, for pre-flight request.</li>
+     * <li><b>cors.request.type:</b> Type of request. Values: <code>simple</code> or <code>preflight</code> or
+     * <code>not_cors</code> or <code>invalid_cors</code></li>
+     * <li><b>cors.request.headers:</b> Request headers sent as 'Access-Control-Request-Headers' header, for pre-flight
+     * request.</li>
      * </ul>
      *
-     * @param request The {@link HttpServletRequest} object.
+     * @param request         The {@link HttpServletRequest} object.
      * @param corsRequestType The {@link CORSRequestType} object.
      */
-    protected static void decorateCORSProperties(
-            final HttpServletRequest request,
+    protected static void decorateCORSProperties(final HttpServletRequest request,
             final CORSRequestType corsRequestType) {
         if (request == null) {
             throw new IllegalArgumentException(sm.getString("corsFilter.nullRequest"));
@@ -515,56 +474,45 @@ public class CorsFilter extends GenericFilter {
         }
 
         switch (corsRequestType) {
-        case SIMPLE:
-        case ACTUAL:
-            request.setAttribute(
-                    CorsFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST, Boolean.TRUE);
-            request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_ORIGIN,
-                    request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN));
-            request.setAttribute(
-                    CorsFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE,
-                    corsRequestType.name().toLowerCase(Locale.ENGLISH));
-            break;
-        case PRE_FLIGHT:
-            request.setAttribute(
-                    CorsFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST,
-                    Boolean.TRUE);
-            request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_ORIGIN,
-                    request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN));
-            request.setAttribute(
-                    CorsFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE,
-                    corsRequestType.name().toLowerCase(Locale.ENGLISH));
-            String headers = request.getHeader(
-                    REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);
-            if (headers == null) {
-                headers = "";
-            }
-            request.setAttribute(
-                    CorsFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_HEADERS, headers);
-            break;
-        case NOT_CORS:
-            request.setAttribute(
-                    CorsFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST,
-                    Boolean.FALSE);
-            break;
-        default:
-            // Don't set any attributes
-            break;
+            case SIMPLE:
+            case ACTUAL:
+                request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST, Boolean.TRUE);
+                request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_ORIGIN,
+                        request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN));
+                request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE,
+                        corsRequestType.name().toLowerCase(Locale.ENGLISH));
+                break;
+            case PRE_FLIGHT:
+                request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST, Boolean.TRUE);
+                request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_ORIGIN,
+                        request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN));
+                request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE,
+                        corsRequestType.name().toLowerCase(Locale.ENGLISH));
+                String headers = request.getHeader(REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);
+                if (headers == null) {
+                    headers = "";
+                }
+                request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_HEADERS, headers);
+                break;
+            case NOT_CORS:
+                request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST, Boolean.FALSE);
+                break;
+            default:
+                // Don't set any attributes
+                break;
         }
     }
 
 
     /**
-     * Joins elements of {@link Set} into a string, where each element is
-     * separated by the provided separator.
+     * Joins elements of {@link Set} into a string, where each element is separated by the provided separator.
      *
-     * @param elements The {@link Set} containing elements to join together.
+     * @param elements      The {@link Set} containing elements to join together.
      * @param joinSeparator The character to be used for separating elements.
-     * @return The joined {@link String}; <code>null</code> if elements
-     *         {@link Set} is null.
+     *
+     * @return The joined {@link String}; <code>null</code> if elements {@link Set} is null.
      */
-    protected static String join(final Collection<String> elements,
-            final String joinSeparator) {
+    protected static String join(final Collection<String> elements, final String joinSeparator) {
         String separator = ",";
         if (elements == null) {
             return null;
@@ -594,13 +542,13 @@ public class CorsFilter extends GenericFilter {
      * Determines the request type.
      *
      * @param request The HTTP Servlet request
+     *
      * @return the CORS type
      */
     protected CORSRequestType checkRequestType(final HttpServletRequest request) {
         CORSRequestType requestType = CORSRequestType.INVALID_CORS;
         if (request == null) {
-            throw new IllegalArgumentException(
-                    sm.getString("corsFilter.nullRequest"));
+            throw new IllegalArgumentException(sm.getString("corsFilter.nullRequest"));
         }
         String originHeader = request.getHeader(REQUEST_HEADER_ORIGIN);
         // Section 6.1.1 and Section 6.2.1
@@ -615,11 +563,9 @@ public class CorsFilter extends GenericFilter {
                 String method = request.getMethod();
                 if (method != null) {
                     if ("OPTIONS".equals(method)) {
-                        String accessControlRequestMethodHeader =
-                                request.getHeader(
-                                        REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
-                        if (accessControlRequestMethodHeader != null &&
-                                !accessControlRequestMethodHeader.isEmpty()) {
+                        String accessControlRequestMethodHeader = request
+                                .getHeader(REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
+                        if (accessControlRequestMethodHeader != null && !accessControlRequestMethodHeader.isEmpty()) {
                             requestType = CORSRequestType.PRE_FLIGHT;
                         } else if (accessControlRequestMethodHeader != null &&
                                 accessControlRequestMethodHeader.isEmpty()) {
@@ -632,8 +578,7 @@ public class CorsFilter extends GenericFilter {
                     } else if ("POST".equals(method)) {
                         String mediaType = getMediaType(request.getContentType());
                         if (mediaType != null) {
-                            if (SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES
-                                    .contains(mediaType)) {
+                            if (SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES.contains(mediaType)) {
                                 requestType = CORSRequestType.SIMPLE;
                             } else {
                                 requestType = CORSRequestType.ACTUAL;
@@ -653,8 +598,7 @@ public class CorsFilter extends GenericFilter {
 
 
     /**
-     * Return the lower case, trimmed value of the media type from the content
-     * type.
+     * Return the lower case, trimmed value of the media type from the content type.
      */
     private String getMediaType(String contentType) {
         if (contentType == null) {
@@ -672,10 +616,9 @@ public class CorsFilter extends GenericFilter {
     /**
      * Checks if the Origin is allowed to make a CORS request.
      *
-     * @param origin
-     *            The Origin.
-     * @return <code>true</code> if origin is allowed; <code>false</code>
-     *         otherwise.
+     * @param origin The Origin.
+     *
+     * @return <code>true</code> if origin is allowed; <code>false</code> otherwise.
      */
     private boolean isOriginAllowed(final String origin) {
         if (isAnyOriginAllowed()) {
@@ -689,30 +632,21 @@ public class CorsFilter extends GenericFilter {
 
 
     /**
-     * Parses each param-value and populates configuration variables. If a param
-     * is provided, it overrides the default.
+     * Parses each param-value and populates configuration variables. If a param is provided, it overrides the default.
+     *
+     * @param allowedOrigins      A {@link String} of comma separated origins.
+     * @param allowedHttpMethods  A {@link String} of comma separated HTTP methods.
+     * @param allowedHttpHeaders  A {@link String} of comma separated HTTP headers.
+     * @param exposedHeaders      A {@link String} of comma separated headers that needs to be exposed.
+     * @param supportsCredentials "true" if support credentials needs to be enabled.
+     * @param preflightMaxAge     The amount of seconds the user agent is allowed to cache the result of the pre-flight
+     *                                request.
      *
-     * @param allowedOrigins
-     *            A {@link String} of comma separated origins.
-     * @param allowedHttpMethods
-     *            A {@link String} of comma separated HTTP methods.
-     * @param allowedHttpHeaders
-     *            A {@link String} of comma separated HTTP headers.
-     * @param exposedHeaders
-     *            A {@link String} of comma separated headers that needs to be
-     *            exposed.
-     * @param supportsCredentials
-     *            "true" if support credentials needs to be enabled.
-     * @param preflightMaxAge
-     *            The amount of seconds the user agent is allowed to cache the
-     *            result of the pre-flight request.
      * @throws ServletException If the configuration is invalid
      */
-    private void parseAndStore(final String allowedOrigins,
-            final String allowedHttpMethods, final String allowedHttpHeaders,
-            final String exposedHeaders, final String supportsCredentials,
-            final String preflightMaxAge, final String decorateRequest)
-                    throws ServletException {
+    private void parseAndStore(final String allowedOrigins, final String allowedHttpMethods,
+            final String allowedHttpHeaders, final String exposedHeaders, final String supportsCredentials,
+            final String preflightMaxAge, final String decorateRequest) throws ServletException {
 
         if (allowedOrigins.trim().equals("*")) {
             this.anyOriginAllowed = true;
@@ -754,8 +688,7 @@ public class CorsFilter extends GenericFilter {
                 this.preflightMaxAge = 0L;
             }
         } catch (NumberFormatException e) {
-            throw new ServletException(
-                    sm.getString("corsFilter.invalidPreflightMaxAge"), e);
+            throw new ServletException(sm.getString("corsFilter.invalidPreflightMaxAge"), e);
         }
 
         // For any value other than 'true' this will be false.
@@ -765,8 +698,8 @@ public class CorsFilter extends GenericFilter {
     /**
      * Takes a comma separated list and returns a Set&lt;String>.
      *
-     * @param data
-     *            A comma separated list of strings.
+     * @param data A comma separated list of strings.
+     *
      * @return Set$lt;String>
      */
     private Set<String> parseStringToSet(final String data) {
@@ -798,11 +731,12 @@ public class CorsFilter extends GenericFilter {
      * </ul>
      *
      * @param origin The origin URI
+     *
      * @return <code>true</code> if the origin was valid
+     *
      * @see <a href="http://tools.ietf.org/html/rfc952">RFC952</a>
      *
-     * @deprecated This will be removed in Tomcat 10
-     *             Use {@link RequestUtil#isValidOrigin(String)}
+     * @deprecated This will be removed in Tomcat 10 Use {@link RequestUtil#isValidOrigin(String)}
      */
     @Deprecated
     protected static boolean isValidOrigin(String origin) {
@@ -833,8 +767,7 @@ public class CorsFilter extends GenericFilter {
     /**
      * Determines is supports credentials is enabled.
      *
-     * @return <code>true</code> if the use of credentials is supported
-     *         otherwise <code>false</code>
+     * @return <code>true</code> if the use of credentials is supported otherwise <code>false</code>
      */
     public boolean isSupportsCredentials() {
         return supportsCredentials;
@@ -852,8 +785,7 @@ public class CorsFilter extends GenericFilter {
 
 
     /**
-     * Returns the {@link Set} of allowed origins that are allowed to make
-     * requests.
+     * Returns the {@link Set} of allowed origins that are allowed to make requests.
      *
      * @return {@link Set}
      */
@@ -885,8 +817,7 @@ public class CorsFilter extends GenericFilter {
     /**
      * Should CORS specific attributes be added to the request.
      *
-     * @return {@code true} if the request should be decorated, otherwise
-     *         {@code false}
+     * @return {@code true} if the request should be decorated, otherwise {@code false}
      */
     public boolean isDecorateRequest() {
         return decorateRequest;
@@ -894,9 +825,8 @@ public class CorsFilter extends GenericFilter {
 
 
     /*
-     * Log objects are not Serializable but this Filter is because it extends
-     * GenericFilter. Tomcat won't serialize a Filter but in case something else
-     * does...
+     * Log objects are not Serializable but this Filter is because it extends GenericFilter. Tomcat won't serialize a
+     * Filter but in case something else does...
      */
     private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
         ois.defaultReadObject();
@@ -907,57 +837,46 @@ public class CorsFilter extends GenericFilter {
     // -------------------------------------------------- CORS Response Headers
 
     /**
-     * The Access-Control-Allow-Origin header indicates whether a resource can
-     * be shared based by returning the value of the Origin request header in
-     * the response.
+     * The Access-Control-Allow-Origin header indicates whether a resource can be shared based by returning the value of
+     * the Origin request header in the response.
      */
-    public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN =
-            "Access-Control-Allow-Origin";
+    public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
 
     /**
-     * The Access-Control-Allow-Credentials header indicates whether the
-     * response to request can be exposed when the omit credentials flag is
-     * unset. When part of the response to a preflight request it indicates that
-     * the actual request can include user credentials.
+     * The Access-Control-Allow-Credentials header indicates whether the response to request can be exposed when the
+     * omit credentials flag is unset. When part of the response to a preflight request it indicates that the actual
+     * request can include user credentials.
      */
-    public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS =
-            "Access-Control-Allow-Credentials";
+    public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
 
     /**
-     * The Access-Control-Expose-Headers header indicates which headers are safe
-     * to expose to the API of a CORS API specification
+     * The Access-Control-Expose-Headers header indicates which headers are safe to expose to the API of a CORS API
+     * specification
      */
-    public static final String RESPONSE_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS =
-            "Access-Control-Expose-Headers";
+    public static final String RESPONSE_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers";
 
     /**
-     * The Access-Control-Max-Age header indicates how long the results of a
-     * preflight request can be cached in a preflight result cache.
+     * The Access-Control-Max-Age header indicates how long the results of a preflight request can be cached in a
+     * preflight result cache.
      */
-    public static final String RESPONSE_HEADER_ACCESS_CONTROL_MAX_AGE =
-            "Access-Control-Max-Age";
+    public static final String RESPONSE_HEADER_ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age";
 
     /**
-     * The Access-Control-Allow-Methods header indicates, as part of the
-     * response to a preflight request, which methods can be used during the
-     * actual request.
+     * The Access-Control-Allow-Methods header indicates, as part of the response to a preflight request, which methods
+     * can be used during the actual request.
      */
-    public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_METHODS =
-            "Access-Control-Allow-Methods";
+    public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
 
     /**
-     * The Access-Control-Allow-Headers header indicates, as part of the
-     * response to a preflight request, which header field names can be used
-     * during the actual request.
+     * The Access-Control-Allow-Headers header indicates, as part of the response to a preflight request, which header
+     * field names can be used during the actual request.
      */
-    public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_HEADERS =
-            "Access-Control-Allow-Headers";
+    public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
 
     // -------------------------------------------------- CORS Request Headers
 
     /**
-     * The Vary header indicates allows disabling proxy caching by indicating
-     * the the response depends on the origin.
+     * The Vary header indicates allows disabling proxy caching by indicating the the response depends on the origin.
      *
      * @deprecated Unused. Will be removed in Tomcat 10
      */
@@ -965,24 +884,21 @@ public class CorsFilter extends GenericFilter {
     public static final String REQUEST_HEADER_VARY = "Vary";
 
     /**
-     * The Origin header indicates where the cross-origin request or preflight
-     * request originates from.
+     * The Origin header indicates where the cross-origin request or preflight request originates from.
      */
     public static final String REQUEST_HEADER_ORIGIN = "Origin";
 
     /**
-     * The Access-Control-Request-Method header indicates which method will be
-     * used in the actual request as part of the preflight request.
+     * The Access-Control-Request-Method header indicates which method will be used in the actual request as part of the
+     * preflight request.
      */
-    public static final String REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD =
-            "Access-Control-Request-Method";
+    public static final String REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method";
 
     /**
-     * The Access-Control-Request-Headers header indicates which headers will be
-     * used in the actual request as part of the preflight request.
+     * The Access-Control-Request-Headers header indicates which headers will be used in the actual request as part of
+     * the preflight request.
      */
-    public static final String REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS =
-            "Access-Control-Request-Headers";
+    public static final String REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers";
 
     // ----------------------------------------------------- Request attributes
     /**
@@ -993,32 +909,27 @@ public class CorsFilter extends GenericFilter {
     /**
      * Attribute that contains the origin of the request.
      */
-    public static final String HTTP_REQUEST_ATTRIBUTE_ORIGIN =
-            HTTP_REQUEST_ATTRIBUTE_PREFIX + "request.origin";
+    public static final String HTTP_REQUEST_ATTRIBUTE_ORIGIN = HTTP_REQUEST_ATTRIBUTE_PREFIX + "request.origin";
 
     /**
      * Boolean value, suggesting if the request is a CORS request or not.
      */
-    public static final String HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST =
-            HTTP_REQUEST_ATTRIBUTE_PREFIX + "isCorsRequest";
+    public static final String HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST = HTTP_REQUEST_ATTRIBUTE_PREFIX + "isCorsRequest";
 
     /**
      * Type of CORS request, of type {@link CORSRequestType}.
      */
-    public static final String HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE =
-            HTTP_REQUEST_ATTRIBUTE_PREFIX + "request.type";
+    public static final String HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE = HTTP_REQUEST_ATTRIBUTE_PREFIX + "request.type";
 
     /**
-     * Request headers sent as 'Access-Control-Request-Headers' header, for
-     * pre-flight request.
+     * Request headers sent as 'Access-Control-Request-Headers' header, for pre-flight request.
      */
-    public static final String HTTP_REQUEST_ATTRIBUTE_REQUEST_HEADERS =
-            HTTP_REQUEST_ATTRIBUTE_PREFIX + "request.headers";
+    public static final String HTTP_REQUEST_ATTRIBUTE_REQUEST_HEADERS = HTTP_REQUEST_ATTRIBUTE_PREFIX +
+            "request.headers";
 
     // -------------------------------------------------------------- Constants
     /**
-     * Enumerates varies types of CORS requests. Also, provides utility methods
-     * to determine the request type.
+     * Enumerates varies types of CORS requests. Also, provides utility methods to determine the request type.
      */
     protected enum CORSRequestType {
         /**
@@ -1030,8 +941,7 @@ public class CorsFilter extends GenericFilter {
          */
         ACTUAL,
         /**
-         * A pre-flight CORS request, to get meta information, before a
-         * non-simple HTTP request is sent.
+         * A pre-flight CORS request, to get meta information, before a non-simple HTTP request is sent.
          */
         PRE_FLIGHT,
         /**
@@ -1039,23 +949,19 @@ public class CorsFilter extends GenericFilter {
          */
         NOT_CORS,
         /**
-         * An invalid CORS request, i.e. it qualifies to be a CORS request, but
-         * fails to be a valid one.
+         * An invalid CORS request, i.e. it qualifies to be a CORS request, but fails to be a valid one.
          */
         INVALID_CORS
     }
 
     /**
-     * {@link Collection} of media type values for the Content-Type header that
-     * will be treated as 'simple'. Note media-type values are compared ignoring
-     * parameters and in a case-insensitive manner.
+     * {@link Collection} of media type values for the Content-Type header that will be treated as 'simple'. Note
+     * media-type values are compared ignoring parameters and in a case-insensitive manner.
      *
-     * @see  <a href="http://www.w3.org/TR/cors/#terminology"
-     *       >http://www.w3.org/TR/cors/#terminology</a>
+     * @see <a href="http://www.w3.org/TR/cors/#terminology" >http://www.w3.org/TR/cors/#terminology</a>
      */
-    public static final Collection<String> SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES =
-            Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
-                    "application/x-www-form-urlencoded", "multipart/form-data", "text/plain")));
+    public static final Collection<String> SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES = Collections.unmodifiableSet(
+            new HashSet<>(Arrays.asList("application/x-www-form-urlencoded", "multipart/form-data", "text/plain")));
 
     // ------------------------------------------------ Configuration Defaults
     /**
@@ -1066,8 +972,7 @@ public class CorsFilter extends GenericFilter {
     /**
      * By default, following methods are supported: GET, POST, HEAD and OPTIONS.
      */
-    public static final String DEFAULT_ALLOWED_HTTP_METHODS =
-            "GET,POST,HEAD,OPTIONS";
+    public static final String DEFAULT_ALLOWED_HTTP_METHODS = "GET,POST,HEAD,OPTIONS";
 
     /**
      * By default, time duration to cache pre-flight response is 30 mins.
@@ -1080,12 +985,10 @@ public class CorsFilter extends GenericFilter {
     public static final String DEFAULT_SUPPORTS_CREDENTIALS = "false";
 
     /**
-     * By default, following headers are supported:
-     * Origin,Accept,X-Requested-With, Content-Type,
+     * By default, following headers are supported: Origin,Accept,X-Requested-With, Content-Type,
      * Access-Control-Request-Method, and Access-Control-Request-Headers.
      */
-    public static final String DEFAULT_ALLOWED_HTTP_HEADERS =
-            "Origin,Accept,X-Requested-With,Content-Type," +
+    public static final String DEFAULT_ALLOWED_HTTP_HEADERS = "Origin,Accept,X-Requested-With,Content-Type," +
             "Access-Control-Request-Method,Access-Control-Request-Headers";
 
     /**
@@ -1102,44 +1005,35 @@ public class CorsFilter extends GenericFilter {
     /**
      * Key to retrieve allowed origins from {@link javax.servlet.FilterConfig}.
      */
-    public static final String PARAM_CORS_ALLOWED_ORIGINS =
-            "cors.allowed.origins";
+    public static final String PARAM_CORS_ALLOWED_ORIGINS = "cors.allowed.origins";
 
     /**
-     * Key to retrieve support credentials from
-     * {@link javax.servlet.FilterConfig}.
+     * Key to retrieve support credentials from {@link javax.servlet.FilterConfig}.
      */
-    public static final String PARAM_CORS_SUPPORT_CREDENTIALS =
-            "cors.support.credentials";
+    public static final String PARAM_CORS_SUPPORT_CREDENTIALS = "cors.support.credentials";
 
     /**
      * Key to retrieve exposed headers from {@link javax.servlet.FilterConfig}.
      */
-    public static final String PARAM_CORS_EXPOSED_HEADERS =
-            "cors.exposed.headers";
+    public static final String PARAM_CORS_EXPOSED_HEADERS = "cors.exposed.headers";
 
     /**
      * Key to retrieve allowed headers from {@link javax.servlet.FilterConfig}.
      */
-    public static final String PARAM_CORS_ALLOWED_HEADERS =
-            "cors.allowed.headers";
+    public static final String PARAM_CORS_ALLOWED_HEADERS = "cors.allowed.headers";
 
     /**
      * Key to retrieve allowed methods from {@link javax.servlet.FilterConfig}.
      */
-    public static final String PARAM_CORS_ALLOWED_METHODS =
-            "cors.allowed.methods";
+    public static final String PARAM_CORS_ALLOWED_METHODS = "cors.allowed.methods";
 
     /**
-     * Key to retrieve preflight max age from
-     * {@link javax.servlet.FilterConfig}.
+     * Key to retrieve preflight max age from {@link javax.servlet.FilterConfig}.
      */
-    public static final String PARAM_CORS_PREFLIGHT_MAXAGE =
-            "cors.preflight.maxage";
+    public static final String PARAM_CORS_PREFLIGHT_MAXAGE = "cors.preflight.maxage";
 
     /**
      * Key to determine if request should be decorated.
      */
-    public static final String PARAM_CORS_REQUEST_DECORATE =
-            "cors.request.decorate";
+    public static final String PARAM_CORS_REQUEST_DECORATE = "cors.request.decorate";
 }
diff --git a/java/org/apache/catalina/filters/CsrfPreventionFilter.java b/java/org/apache/catalina/filters/CsrfPreventionFilter.java
index 4ffb7e2277..5568c4cc6d 100644
--- a/java/org/apache/catalina/filters/CsrfPreventionFilter.java
+++ b/java/org/apache/catalina/filters/CsrfPreventionFilter.java
@@ -37,13 +37,11 @@ import org.apache.juli.logging.Log;
 import org.apache.juli.logging.LogFactory;
 
 /**
- * Provides basic CSRF protection for a web application. The filter assumes
- * that:
+ * Provides basic CSRF protection for a web application. The filter assumes that:
  * <ul>
  * <li>The filter is mapped to /*</li>
- * <li>{@link HttpServletResponse#encodeRedirectURL(String)} and
- * {@link HttpServletResponse#encodeURL(String)} are used to encode all URLs
- * returned to the client
+ * <li>{@link HttpServletResponse#encodeRedirectURL(String)} and {@link HttpServletResponse#encodeURL(String)} are used
+ * to encode all URLs returned to the client
  * </ul>
  */
 public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
@@ -56,14 +54,11 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
     private String nonceRequestParameterName = Constants.CSRF_NONCE_REQUEST_PARAM;
 
     /**
-     * Entry points are URLs that will not be tested for the presence of a valid
-     * nonce. They are used to provide a way to navigate back to a protected
-     * application after navigating away from it. Entry points will be limited
-     * to HTTP GET requests and should not trigger any security sensitive
-     * actions.
+     * Entry points are URLs that will not be tested for the presence of a valid nonce. They are used to provide a way
+     * to navigate back to a protected application after navigating away from it. Entry points will be limited to HTTP
+     * GET requests and should not trigger any security sensitive actions.
      *
-     * @param entryPoints   Comma separated list of URLs to be configured as
-     *                      entry points.
+     * @param entryPoints Comma separated list of URLs to be configured as entry points.
      */
     public void setEntryPoints(String entryPoints) {
         String values[] = entryPoints.split(",");
@@ -73,13 +68,11 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
     }
 
     /**
-     * Sets the number of previously issued nonces that will be cached on a LRU
-     * basis to support parallel requests, limited use of the refresh and back
-     * in the browser and similar behaviors that may result in the submission
-     * of a previous nonce rather than the current one. If not set, the default
-     * value of 5 will be used.
+     * Sets the number of previously issued nonces that will be cached on a LRU basis to support parallel requests,
+     * limited use of the refresh and back in the browser and similar behaviors that may result in the submission of a
+     * previous nonce rather than the current one. If not set, the default value of 5 will be used.
      *
-     * @param nonceCacheSize    The number of nonces to cache
+     * @param nonceCacheSize The number of nonces to cache
      */
     public void setNonceCacheSize(int nonceCacheSize) {
         this.nonceCacheSize = nonceCacheSize;
@@ -88,8 +81,7 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
     /**
      * Sets the request parameter name to use for CSRF nonces.
      *
-     * @param parameterName The request parameter name to use
-     *        for CSRF nonces.
+     * @param parameterName The request parameter name to use for CSRF nonces.
      */
     public void setNonceRequestParameterName(String parameterName) {
         this.nonceRequestParameterName = parameterName;
@@ -101,19 +93,17 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
         super.init(filterConfig);
 
         // Put the expected request parameter name into the application scope
-        filterConfig.getServletContext().setAttribute(
-                Constants.CSRF_NONCE_REQUEST_PARAM_NAME_KEY,
+        filterConfig.getServletContext().setAttribute(Constants.CSRF_NONCE_REQUEST_PARAM_NAME_KEY,
                 nonceRequestParameterName);
     }
 
     @Override
-    public void doFilter(ServletRequest request, ServletResponse response,
-            FilterChain chain) throws IOException, ServletException {
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+            throws IOException, ServletException {
 
         ServletResponse wResponse = null;
 
-        if (request instanceof HttpServletRequest &&
-                response instanceof HttpServletResponse) {
+        if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
 
             HttpServletRequest req = (HttpServletRequest) request;
             HttpServletResponse res = (HttpServletResponse) response;
@@ -128,10 +118,9 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
 
                 if (previousNonce == null) {
                     if (log.isDebugEnabled()) {
-                        log.debug("Rejecting request for " + getRequestedPath(req)
-                                  + ", session "
-                                  + (null == session ? "(none)" : session.getId())
-                                  + " with no CSRF nonce found in request");
+                        log.debug("Rejecting request for " + getRequestedPath(req) + ", session " +
+                                (null == session ? "(none)" : session.getId()) +
+                                " with no CSRF nonce found in request");
                     }
 
                     res.sendError(getDenyStatus());
@@ -141,28 +130,25 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
                 nonceCache = getNonceCache(req, session);
                 if (nonceCache == null) {
                     if (log.isDebugEnabled()) {
-                        log.debug("Rejecting request for " + getRequestedPath(req)
-                                  + ", session "
-                                  + (null == session ? "(none)" : session.getId())
-                                  + " due to empty / missing nonce cache");
+                        log.debug("Rejecting request for " + getRequestedPath(req) + ", session " +
+                                (null == session ? "(none)" : session.getId()) + " due to empty / missing nonce cache");
                     }
 
                     res.sendError(getDenyStatus());
                     return;
                 } else if (!nonceCache.contains(previousNonce)) {
                     if (log.isDebugEnabled()) {
-                        log.debug("Rejecting request for " + getRequestedPath(req)
-                                  + ", session "
-                                  + (null == session ? "(none)" : session.getId())
-                                  + " due to invalid nonce " + previousNonce);
+                        log.debug("Rejecting request for " + getRequestedPath(req) + ", session " +
+                                (null == session ? "(none)" : session.getId()) + " due to invalid nonce " +
+                                previousNonce);
                     }
 
                     res.sendError(getDenyStatus());
                     return;
                 }
                 if (log.isTraceEnabled()) {
-                    log.trace("Allowing request to " + getRequestedPath(req)
-                               + " with valid CSRF nonce " + previousNonce);
+                    log.trace(
+                            "Allowing request to " + getRequestedPath(req) + " with valid CSRF nonce " + previousNonce);
                 }
             }
 
@@ -173,12 +159,13 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
                 }
                 if (nonceCache == null) {
                     if (log.isDebugEnabled()) {
-                        log.debug("Creating new CSRF nonce cache with size=" + nonceCacheSize + " for session " + (null == session ? "(will create)" : session.getId()));
+                        log.debug("Creating new CSRF nonce cache with size=" + nonceCacheSize + " for session " +
+                                (null == session ? "(will create)" : session.getId()));
                     }
 
                     if (session == null) {
                         if (log.isDebugEnabled()) {
-                             log.debug("Creating new session to store CSRF nonce cache");
+                            log.debug("Creating new session to store CSRF nonce cache");
                         }
 
                         session = req.getSession(true);
@@ -224,15 +211,12 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
 
 
     /**
-     * Determines whether a nonce should be created. This method is provided
-     * primarily for the benefit of sub-classes that wish to customise this
-     * behaviour.
+     * Determines whether a nonce should be created. This method is provided primarily for the benefit of sub-classes
+     * that wish to customise this behaviour.
      *
-     * @param request   The request that triggered the need to potentially
-     *                      create the nonce.
+     * @param request The request that triggered the need to potentially create the nonce.
      *
-     * @return {@code true} if a nonce should be created, otherwise
-     *              {@code false}
+     * @return {@code true} if a nonce should be created, otherwise {@code false}
      */
     protected boolean skipNonceGeneration(HttpServletRequest request) {
         return false;
@@ -240,13 +224,12 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
 
 
     /**
-     * Create a new {@link NonceCache} and store in the {@link HttpSession}.
-     * This method is provided primarily for the benefit of sub-classes that
-     * wish to customise this behaviour.
+     * Create a new {@link NonceCache} and store in the {@link HttpSession}. This method is provided primarily for the
+     * benefit of sub-classes that wish to customise this behaviour.
      *
-     * @param request   The request that triggered the need to create the nonce
-     *                      cache. Unused by the default implementation.
-     * @param session   The session associated with the request.
+     * @param request The request that triggered the need to create the nonce cache. Unused by the default
+     *                    implementation.
+     * @param session The session associated with the request.
      *
      * @return A newly created {@link NonceCache}
      */
@@ -261,29 +244,26 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
 
 
     /**
-     * Obtain the {@link NonceCache} associated with the request and/or session.
-     * This method is provided primarily for the benefit of sub-classes that
-     * wish to customise this behaviour.
+     * Obtain the {@link NonceCache} associated with the request and/or session. This method is provided primarily for
+     * the benefit of sub-classes that wish to customise this behaviour.
      *
-     * @param request   The request that triggered the need to obtain the nonce
-     *                      cache. Unused by the default implementation.
-     * @param session   The session associated with the request.
+     * @param request The request that triggered the need to obtain the nonce cache. Unused by the default
+     *                    implementation.
+     * @param session The session associated with the request.
      *
-     * @return The {@link NonceCache} currently associated with the request
-     *         and/or session
+     * @return The {@link NonceCache} currently associated with the request and/or session
      */
     protected NonceCache<String> getNonceCache(HttpServletRequest request, HttpSession session) {
         if (session == null) {
             return null;
         }
         @SuppressWarnings("unchecked")
-        NonceCache<String> nonceCache =
-                (NonceCache<String>) session.getAttribute(Constants.CSRF_NONCE_SESSION_ATTR_NAME);
+        NonceCache<String> nonceCache = (NonceCache<String>) session
+                .getAttribute(Constants.CSRF_NONCE_SESSION_ATTR_NAME);
         return nonceCache;
     }
 
-    protected static class CsrfResponseWrapper
-            extends HttpServletResponseWrapper {
+    protected static class CsrfResponseWrapper extends HttpServletResponseWrapper {
 
         private final String nonceRequestParameterName;
         private final String nonce;
@@ -341,7 +321,7 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
                 path = path.substring(0, question);
             }
             StringBuilder sb = new StringBuilder(path);
-            if (query.length() >0) {
+            if (query.length() > 0) {
                 sb.append(query);
                 sb.append('&');
             } else {
@@ -369,13 +349,14 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
 
         // Although the internal implementation uses a Map, this cache
         // implementation is only concerned with the keys.
-        private final Map<T,T> cache;
+        private final Map<T, T> cache;
 
         public LruCache(final int cacheSize) {
-            cache = new LinkedHashMap<T,T>() {
+            cache = new LinkedHashMap<T, T>() {
                 private static final long serialVersionUID = 1L;
+
                 @Override
-                protected boolean removeEldestEntry(Map.Entry<T,T> eldest) {
+                protected boolean removeEldestEntry(Map.Entry<T, T> eldest) {
                     if (size() > cacheSize) {
                         return true;
                     }
diff --git a/java/org/apache/catalina/filters/CsrfPreventionFilterBase.java b/java/org/apache/catalina/filters/CsrfPreventionFilterBase.java
index ba35ec42a5..f4aebc8d32 100644
--- a/java/org/apache/catalina/filters/CsrfPreventionFilterBase.java
+++ b/java/org/apache/catalina/filters/CsrfPreventionFilterBase.java
@@ -52,22 +52,19 @@ public abstract class CsrfPreventionFilterBase extends FilterBase {
     }
 
     /**
-     * Set response status code that is used to reject denied request. If none
-     * set, the default value of 403 will be used.
+     * Set response status code that is used to reject denied request. If none set, the default value of 403 will be
+     * used.
      *
-     * @param denyStatus
-     *            HTTP status code
+     * @param denyStatus HTTP status code
      */
     public void setDenyStatus(int denyStatus) {
         this.denyStatus = denyStatus;
     }
 
     /**
-     * Specify the class to use to generate the nonces. Must be in instance of
-     * {@link Random}.
+     * Specify the class to use to generate the nonces. Must be in instance of {@link Random}.
      *
-     * @param randomClass
-     *            The name of the class to use
+     * @param randomClass The name of the class to use
      */
     public void setRandomClass(String randomClass) {
         this.randomClass = randomClass;
@@ -82,8 +79,8 @@ public abstract class CsrfPreventionFilterBase extends FilterBase {
             Class<?> clazz = Class.forName(randomClass);
             randomSource = (Random) clazz.getConstructor().newInstance();
         } catch (ReflectiveOperationException e) {
-            ServletException se = new ServletException(sm.getString(
-                    "csrfPrevention.invalidRandomClass", randomClass), e);
+            ServletException se = new ServletException(sm.getString("csrfPrevention.invalidRandomClass", randomClass),
+                    e);
             throw se;
         }
     }
@@ -95,12 +92,10 @@ public abstract class CsrfPreventionFilterBase extends FilterBase {
 
 
     /**
-     * Generate a once time token (nonce) for authenticating subsequent
-     * requests. The nonce generation is a simplified version of
-     * ManagerBase.generateSessionId().
+     * Generate a once time token (nonce) for authenticating subsequent requests. The nonce generation is a simplified
+     * version of ManagerBase.generateSessionId().
      *
-     * @param request   The request. Unused in this method but present for the
-     *                  the benefit of sub-classes.
+     * @param request The request. Unused in this method but present for the the benefit of sub-classes.
      *
      * @return the generated nonce
      */
@@ -109,14 +104,13 @@ public abstract class CsrfPreventionFilterBase extends FilterBase {
     }
 
     /**
-     * Generate a once time token (nonce) for authenticating subsequent
-     * requests. The nonce generation is a simplified version of
-     * ManagerBase.generateSessionId().
+     * Generate a once time token (nonce) for authenticating subsequent requests. The nonce generation is a simplified
+     * version of ManagerBase.generateSessionId().
      *
      * @return the generated nonce
      *
-     * @deprecated Use {@link #generateNonce(HttpServletRequest)} instead. This
-     *             method will be removed in Apache Tomcat 10.1.x onwards.
+     * @deprecated Use {@link #generateNonce(HttpServletRequest)} instead. This method will be removed in Apache Tomcat
+     *                 10.1.x onwards.
      */
     @Deprecated
     protected String generateNonce() {
diff --git a/java/org/apache/catalina/filters/ExpiresFilter.java b/java/org/apache/catalina/filters/ExpiresFilter.java
index 60651b7728..90023f4728 100644
--- a/java/org/apache/catalina/filters/ExpiresFilter.java
+++ b/java/org/apache/catalina/filters/ExpiresFilter.java
@@ -47,41 +47,34 @@ import org.apache.juli.logging.LogFactory;
 
 /**
  * <p>
- * ExpiresFilter is a Java Servlet API port of <a
- * href="https://httpd.apache.org/docs/2.2/mod/mod_expires.html">Apache
- * mod_expires</a> to add '{@code Expires}' and
- * '{@code Cache-Control: max-age=}' headers to HTTP response according to its
- * '{@code Content-Type}'.
+ * ExpiresFilter is a Java Servlet API port of <a href="https://httpd.apache.org/docs/2.2/mod/mod_expires.html">Apache
+ * mod_expires</a> to add '{@code Expires}' and '{@code Cache-Control: max-age=}' headers to HTTP response according to
+ * its '{@code Content-Type}'.
  * </p>
- *
  * <p>
- * Following documentation is inspired by <a
- * href="https://httpd.apache.org/docs/2.2/mod/mod_expires.html">mod_expires</a>
+ * Following documentation is inspired by
+ * <a href="https://httpd.apache.org/docs/2.2/mod/mod_expires.html">mod_expires</a>
  * </p>
  * <h2>Summary</h2>
  * <p>
- * This filter controls the setting of the {@code Expires} HTTP header and the
- * {@code max-age} directive of the {@code Cache-Control} HTTP header in
- * server responses. The expiration date can set to be relative to either the
- * time the source file was last modified, or to the time of the client access.
+ * This filter controls the setting of the {@code Expires} HTTP header and the {@code max-age} directive of the
+ * {@code Cache-Control} HTTP header in server responses. The expiration date can set to be relative to either the time
+ * the source file was last modified, or to the time of the client access.
  * </p>
  * <p>
- * These HTTP headers are an instruction to the client about the document&#x27;s
- * validity and persistence. If cached, the document may be fetched from the
- * cache rather than from the source until this time has passed. After that, the
- * cache copy is considered &quot;expired&quot; and invalid, and a new copy must
- * be obtained from the source.
+ * These HTTP headers are an instruction to the client about the document&#x27;s validity and persistence. If cached,
+ * the document may be fetched from the cache rather than from the source until this time has passed. After that, the
+ * cache copy is considered &quot;expired&quot; and invalid, and a new copy must be obtained from the source.
  * </p>
  * <p>
  * To modify {@code Cache-Control} directives other than {@code max-age} (see
- * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9" >RFC
- * 2616 section 14.9</a>), you can use other servlet filters or <a
- * href="https://httpd.apache.org/docs/2.2/mod/mod_headers.html" >Apache Httpd
+ * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9" >RFC 2616 section 14.9</a>), you can use
+ * other servlet filters or <a href="https://httpd.apache.org/docs/2.2/mod/mod_headers.html" >Apache Httpd
  * mod_headers</a> module.
  * </p>
- * <h2>Filter Configuration</h2><h3>Basic configuration to add
- * '{@code Expires}' and '{@code Cache-Control: max-age=}'
- * headers to images, CSS and JavaScript</h3>
+ * <h2>Filter Configuration</h2>
+ * <h3>Basic configuration to add '{@code Expires}' and '{@code Cache-Control: max-age=}' headers to images, CSS and
+ * JavaScript</h3>
  *
  * <pre>
  * {@code
@@ -115,21 +108,17 @@ import org.apache.juli.logging.LogFactory;
  * </pre>
  *
  * <h3>Configuration Parameters</h3>
- *
  * <h4>{@code ExpiresByType <content-type>}</h4>
  * <p>
- * This directive defines the value of the {@code Expires} header and the
- * {@code max-age} directive of the {@code Cache-Control} header generated for
- * documents of the specified type (<i>e.g.</i>, {@code text/html}). The second
- * argument sets the number of seconds that will be added to a base time to
- * construct the expiration date. The {@code Cache-Control: max-age} is
- * calculated by subtracting the request time from the expiration date and
- * expressing the result in seconds.
+ * This directive defines the value of the {@code Expires} header and the {@code max-age} directive of the
+ * {@code Cache-Control} header generated for documents of the specified type (<i>e.g.</i>, {@code text/html}). The
+ * second argument sets the number of seconds that will be added to a base time to construct the expiration date. The
+ * {@code Cache-Control: max-age} is calculated by subtracting the request time from the expiration date and expressing
+ * the result in seconds.
  * </p>
  * <p>
- * The base time is either the last modification time of the file, or the time
- * of the client&#x27;s access to the document. Which should be used is
- * specified by the {@code <code>} field; {@code M} means that the
+ * The base time is either the last modification time of the file, or the time of the client&#x27;s access to the
+ * document. Which should be used is specified by the {@code <code>} field; {@code M} means that the
  * file&#x27;s last modification time should be used as the base time, and
  * {@code A} means the client&#x27;s access time should be used. The duration
  * is expressed in seconds. {@code A2592000} stands for
@@ -397,7 +386,6 @@ import org.apache.juli.logging.LogFactory;
  * <p>
  * Sample of initialization log message :
  * </p>
- *
  * <code>
  * Mar 26, 2010 2:01:41 PM org.apache.catalina.filters.ExpiresFilter init
  * FINE: Filter initialized with configuration ExpiresFilter[
@@ -409,19 +397,15 @@ import org.apache.juli.logging.LogFactory;
  *       application/javascript=ExpiresConfiguration[startingPoint=ACCESS_TIME, duration=[10 MINUTE]]}]
  * </code>
  * <p>
- * Sample of per-request log message where {@code ExpiresFilter} adds an
- * expiration date
+ * Sample of per-request log message where {@code ExpiresFilter} adds an expiration date
  * </p>
- *
  * <code>
  * Mar 26, 2010 2:09:47 PM org.apache.catalina.filters.ExpiresFilter onBeforeWriteResponseBody
  * FINE: Request "/tomcat.gif" with response status "200" content-type "image/gif", set expiration date 3/26/10 2:19 PM
  * </code>
  * <p>
- * Sample of per-request log message where {@code ExpiresFilter} does not add
- * an expiration date
+ * Sample of per-request log message where {@code ExpiresFilter} does not add an expiration date
  * </p>
- *
  * <code>
  * Mar 26, 2010 2:10:27 PM org.apache.catalina.filters.ExpiresFilter onBeforeWriteResponseBody
  * FINE: Request "/docs/config/manager.html" with response status "200" content-type "text/html", no expiration configured
@@ -462,9 +446,9 @@ public class ExpiresFilter extends FilterBase {
      * Duration unit
      */
     protected enum DurationUnit {
-        DAY(Calendar.DAY_OF_YEAR), HOUR(Calendar.HOUR), MINUTE(Calendar.MINUTE), MONTH(
-                Calendar.MONTH), SECOND(Calendar.SECOND), WEEK(
-                Calendar.WEEK_OF_YEAR), YEAR(Calendar.YEAR);
+        DAY(Calendar.DAY_OF_YEAR), HOUR(Calendar.HOUR), MINUTE(Calendar.MINUTE), MONTH(Calendar.MONTH),
+        SECOND(Calendar.SECOND), WEEK(Calendar.WEEK_OF_YEAR), YEAR(Calendar.YEAR);
+
         private final int calendarField;
 
         private DurationUnit(int calendarField) {
@@ -496,8 +480,7 @@ public class ExpiresFilter extends FilterBase {
          */
         private final StartingPoint startingPoint;
 
-        public ExpiresConfiguration(StartingPoint startingPoint,
-                List<Duration> durations) {
+        public ExpiresConfiguration(StartingPoint startingPoint, List<Duration> durations) {
             super();
             this.startingPoint = startingPoint;
             this.durations = durations;
@@ -513,15 +496,13 @@ public class ExpiresFilter extends FilterBase {
 
         @Override
         public String toString() {
-            return "ExpiresConfiguration[startingPoint=" + startingPoint +
-                    ", duration=" + durations + "]";
+            return "ExpiresConfiguration[startingPoint=" + startingPoint + ", duration=" + durations + "]";
         }
     }
 
     /**
-     * Expiration configuration starting point. Either the time the
-     * HTML-page/servlet-response was served ({@link StartingPoint#ACCESS_TIME})
-     * or the last time the HTML-page/servlet-response was modified (
+     * Expiration configuration starting point. Either the time the HTML-page/servlet-response was served
+     * ({@link StartingPoint#ACCESS_TIME}) or the last time the HTML-page/servlet-response was modified (
      * {@link StartingPoint#LAST_MODIFICATION_TIME}).
      */
     protected enum StartingPoint {
@@ -530,27 +511,23 @@ public class ExpiresFilter extends FilterBase {
 
     /**
      * <p>
-     * Wrapping extension of the {@link HttpServletResponse} to yrap the
-     * "Start Write Response Body" event.
+     * Wrapping extension of the {@link HttpServletResponse} to yrap the "Start Write Response Body" event.
      * </p>
      * <p>
-     * For performance optimization : this extended response holds the
-     * {@link #lastModifiedHeader} and {@link #cacheControlHeader} values access
-     * to the slow {@link #getHeader(String)} and to spare the {@code string}
+     * For performance optimization : this extended response holds the {@link #lastModifiedHeader} and
+     * {@link #cacheControlHeader} values access to the slow {@link #getHeader(String)} and to spare the {@code string}
      * to {@code date} to {@code long} conversion.
      * </p>
      */
     public class XHttpServletResponse extends HttpServletResponseWrapper {
 
         /**
-         * Value of the {@code Cache-Control} http response header if it has
-         * been set.
+         * Value of the {@code Cache-Control} http response header if it has been set.
          */
         private String cacheControlHeader;
 
         /**
-         * Value of the {@code Last-Modified} http response header if it has
-         * been set.
+         * Value of the {@code Last-Modified} http response header if it has been set.
          */
         private long lastModifiedHeader;
 
@@ -563,14 +540,12 @@ public class ExpiresFilter extends FilterBase {
         private ServletOutputStream servletOutputStream;
 
         /**
-         * Indicates whether calls to write methods ({@code write(...)},
-         * {@code print(...)}, etc) of the response body have been called or
-         * not.
+         * Indicates whether calls to write methods ({@code write(...)}, {@code print(...)}, etc) of the response body
+         * have been called or not.
          */
         private boolean writeResponseBodyStarted;
 
-        public XHttpServletResponse(HttpServletRequest request,
-                HttpServletResponse response) {
+        public XHttpServletResponse(HttpServletRequest request, HttpServletResponse response) {
             super(response);
             this.request = request;
         }
@@ -587,8 +562,7 @@ public class ExpiresFilter extends FilterBase {
         @Override
         public void addHeader(String name, String value) {
             super.addHeader(name, value);
-            if (HEADER_CACHE_CONTROL.equalsIgnoreCase(name) &&
-                    cacheControlHeader == null) {
+            if (HEADER_CACHE_CONTROL.equalsIgnoreCase(name) && cacheControlHeader == null) {
                 cacheControlHeader = value;
             }
         }
@@ -604,8 +578,7 @@ public class ExpiresFilter extends FilterBase {
         @Override
         public ServletOutputStream getOutputStream() throws IOException {
             if (servletOutputStream == null) {
-                servletOutputStream = new XServletOutputStream(
-                        super.getOutputStream(), request, this);
+                servletOutputStream = new XServletOutputStream(super.getOutputStream(), request, this);
             }
             return servletOutputStream;
         }
@@ -657,8 +630,7 @@ public class ExpiresFilter extends FilterBase {
     }
 
     /**
-     * Wrapping extension of {@link PrintWriter} to trap the
-     * "Start Write Response Body" event.
+     * Wrapping extension of {@link PrintWriter} to trap the "Start Write Response Body" event.
      */
     public class XPrintWriter extends PrintWriter {
         private final PrintWriter out;
@@ -667,8 +639,7 @@ public class ExpiresFilter extends FilterBase {
 
         private final XHttpServletResponse response;
 
-        public XPrintWriter(PrintWriter out, HttpServletRequest request,
-                XHttpServletResponse response) {
+        public XPrintWriter(PrintWriter out, HttpServletRequest request, XHttpServletResponse response) {
             super(out);
             this.out = out;
             this.request = request;
@@ -871,8 +842,7 @@ public class ExpiresFilter extends FilterBase {
     }
 
     /**
-     * Wrapping extension of {@link ServletOutputStream} to trap the
-     * "Start Write Response Body" event.
+     * Wrapping extension of {@link ServletOutputStream} to trap the "Start Write Response Body" event.
      */
     public class XServletOutputStream extends ServletOutputStream {
 
@@ -882,8 +852,8 @@ public class ExpiresFilter extends FilterBase {
 
         private final ServletOutputStream servletOutputStream;
 
-        public XServletOutputStream(ServletOutputStream servletOutputStream,
-                HttpServletRequest request, XHttpServletResponse response) {
+        public XServletOutputStream(ServletOutputStream servletOutputStream, HttpServletRequest request,
+                XHttpServletResponse response) {
             super();
             this.servletOutputStream = servletOutputStream;
             this.response = response;
@@ -1035,8 +1005,7 @@ public class ExpiresFilter extends FilterBase {
     }
 
     /**
-     * {@link Pattern} for a comma delimited string that support whitespace
-     * characters
+     * {@link Pattern} for a comma delimited string that support whitespace characters
      */
     private static final Pattern commaSeparatedValuesPattern = Pattern.compile("\\s*,\\s*");
 
@@ -1059,12 +1028,11 @@ public class ExpiresFilter extends FilterBase {
     /**
      * Convert a comma delimited list of numbers into an {@code int[]}.
      *
-     * @param commaDelimitedInts
-     *            can be {@code null}
+     * @param commaDelimitedInts can be {@code null}
+     *
      * @return never {@code null} array
      */
-    protected static int[] commaDelimitedListToIntArray(
-            String commaDelimitedInts) {
+    protected static int[] commaDelimitedListToIntArray(String commaDelimitedInts) {
         String[] intsAsStrings = commaDelimitedListToStringArray(commaDelimitedInts);
         int[] ints = new int[intsAsStrings.length];
         for (int i = 0; i < intsAsStrings.length; i++) {
@@ -1072,8 +1040,8 @@ public class ExpiresFilter extends FilterBase {
             try {
                 ints[i] = Integer.parseInt(intAsString);
             } catch (NumberFormatException e) {
-                throw new RuntimeException(sm.getString("expiresFilter.numberError",
-                        Integer.valueOf(i), commaDelimitedInts));
+                throw new RuntimeException(
+                        sm.getString("expiresFilter.numberError", Integer.valueOf(i), commaDelimitedInts));
             }
         }
         return ints;
@@ -1083,18 +1051,18 @@ public class ExpiresFilter extends FilterBase {
      * Convert a given comma delimited list of strings into an array of String
      *
      * @param commaDelimitedStrings the string to be split
+     *
      * @return array of patterns (non {@code null})
      */
-    protected static String[] commaDelimitedListToStringArray(
-            String commaDelimitedStrings) {
+    protected static String[] commaDelimitedListToStringArray(String commaDelimitedStrings) {
         return (commaDelimitedStrings == null || commaDelimitedStrings.length() == 0) ? new String[0]
                 : commaSeparatedValuesPattern.split(commaDelimitedStrings);
     }
 
     /**
-     * @return {@code true} if the given {@code str} contains the given
-     * {@code searchStr}.
-     * @param str String that will be searched
+     * @return {@code true} if the given {@code str} contains the given {@code searchStr}.
+     *
+     * @param str       String that will be searched
      * @param searchStr The substring to search
      */
     protected static boolean contains(String str, String searchStr) {
@@ -1106,7 +1074,9 @@ public class ExpiresFilter extends FilterBase {
 
     /**
      * Convert an array of ints into a comma delimited string
+     *
      * @param ints The int array
+     *
      * @return a comma separated string
      */
     protected static String intsToCommaDelimitedString(int[] ints) {
@@ -1127,8 +1097,8 @@ public class ExpiresFilter extends FilterBase {
 
     /**
      * @param str The String to check
-     * @return {@code true} if the given {@code str} is
-     * {@code null} or has a zero characters length.
+     *
+     * @return {@code true} if the given {@code str} is {@code null} or has a zero characters length.
      */
     protected static boolean isEmpty(String str) {
         return str == null || str.length() == 0;
@@ -1136,21 +1106,18 @@ public class ExpiresFilter extends FilterBase {
 
     /**
      * @param str The String to check
-     * @return {@code true} if the given {@code str} has at least one
-     * character (can be a whitespace).
+     *
+     * @return {@code true} if the given {@code str} has at least one character (can be a whitespace).
      */
     protected static boolean isNotEmpty(String str) {
         return !isEmpty(str);
     }
 
     /**
-     * @return {@code true} if the given {@code string} starts with the
-     * given {@code prefix} ignoring case.
+     * @return {@code true} if the given {@code string} starts with the given {@code prefix} ignoring case.
      *
-     * @param string
-     *            can be {@code null}
-     * @param prefix
-     *            can be {@code null}
+     * @param string can be {@code null}
+     * @param prefix can be {@code null}
      */
     protected static boolean startsWithIgnoreCase(String string, String prefix) {
         if (string == null || prefix == null) {
@@ -1164,15 +1131,12 @@ public class ExpiresFilter extends FilterBase {
     }
 
     /**
-     * @return the subset of the given {@code str} that is before the first
-     * occurrence of the given {@code separator}. Return {@code null}
-     * if the given {@code str} or the given {@code separator} is
-     * null. Return and empty string if the {@code separator} is empty.
+     * @return the subset of the given {@code str} that is before the first occurrence of the given {@code separator}.
+     *             Return {@code null} if the given {@code str} or the given {@code separator} is null. Return and empty
+     *             string if the {@code separator} is empty.
      *
-     * @param str
-     *            can be {@code null}
-     * @param separator
-     *            can be {@code null}
+     * @param str       can be {@code null}
+     * @param separator can be {@code null}
      */
     protected static String substringBefore(String str, String separator) {
         if (str == null || str.isEmpty() || separator == null) {
@@ -1196,8 +1160,7 @@ public class ExpiresFilter extends FilterBase {
     private ExpiresConfiguration defaultExpiresConfiguration;
 
     /**
-     * list of response status code for which the {@link ExpiresFilter} will not
-     * generate expiration headers.
+     * list of response status code for which the {@link ExpiresFilter} will not generate expiration headers.
      */
     private int[] excludedResponseStatusCodes = new int[] { HttpServletResponse.SC_NOT_MODIFIED };
 
@@ -1207,23 +1170,19 @@ public class ExpiresFilter extends FilterBase {
     private Map<String, ExpiresConfiguration> expiresConfigurationByContentType = new LinkedHashMap<>();
 
     @Override
-    public void doFilter(ServletRequest request, ServletResponse response,
-            FilterChain chain) throws IOException, ServletException {
-        if (request instanceof HttpServletRequest &&
-                response instanceof HttpServletResponse) {
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+            throws IOException, ServletException {
+        if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
             HttpServletRequest httpRequest = (HttpServletRequest) request;
             HttpServletResponse httpResponse = (HttpServletResponse) response;
 
             if (response.isCommitted()) {
                 if (log.isDebugEnabled()) {
-                    log.debug(sm.getString(
-                            "expiresFilter.responseAlreadyCommitted",
-                            httpRequest.getRequestURL()));
+                    log.debug(sm.getString("expiresFilter.responseAlreadyCommitted", httpRequest.getRequestURL()));
                 }
                 chain.doFilter(request, response);
             } else {
-                XHttpServletResponse xResponse = new XHttpServletResponse(
-                        httpRequest, httpResponse);
+                XHttpServletResponse xResponse = new XHttpServletResponse(httpRequest, httpResponse);
                 chain.doFilter(request, xResponse);
                 if (!xResponse.isWriteResponseBodyStarted()) {
                     // Empty response, manually trigger
@@ -1250,19 +1209,19 @@ public class ExpiresFilter extends FilterBase {
 
 
     /**
-     * Returns the expiration date of the given {@link XHttpServletResponse} or
-     * {@code null} if no expiration date has been configured for the
-     * declared content type.
+     * Returns the expiration date of the given {@link XHttpServletResponse} or {@code null} if no expiration date has
+     * been configured for the declared content type.
      * <p>
      * {@code protected} for extension.
      *
      * @param response The wrapped HTTP response
      *
      * @return the expiration date
+     *
      * @see HttpServletResponse#getContentType()
      *
-     * @deprecated  Will be removed in Tomcat 10.
-     *              Use {@link #getExpirationDate(HttpServletRequest, XHttpServletResponse)}
+     * @deprecated Will be removed in Tomcat 10. Use
+     *                 {@link #getExpirationDate(HttpServletRequest, XHttpServletResponse)}
      */
     @Deprecated
     protected Date getExpirationDate(XHttpServletResponse response) {
@@ -1271,9 +1230,8 @@ public class ExpiresFilter extends FilterBase {
 
 
     /**
-     * Returns the expiration date of the given {@link XHttpServletResponse} or
-     * {@code null} if no expiration date has been configured for the
-     * declared content type.
+     * Returns the expiration date of the given {@link XHttpServletResponse} or {@code null} if no expiration date has
+     * been configured for the declared content type.
      * <p>
      * {@code protected} for extension.
      *
@@ -1281,6 +1239,7 @@ public class ExpiresFilter extends FilterBase {
      * @param response The wrapped HTTP response
      *
      * @return the expiration date
+     *
      * @see HttpServletResponse#getContentType()
      */
     protected Date getExpirationDate(HttpServletRequest request, XHttpServletResponse response) {
@@ -1309,9 +1268,8 @@ public class ExpiresFilter extends FilterBase {
         if (configuration != null) {
             Date result = getExpirationDate(configuration, response);
             if (log.isDebugEnabled()) {
-                log.debug(sm.getString(
-                        "expiresFilter.useMatchingConfiguration",
-                        configuration, contentType, contentType, result));
+                log.debug(sm.getString("expiresFilter.useMatchingConfiguration", configuration, contentType,
+                        contentType, result));
             }
             return result;
         }
@@ -1324,10 +1282,8 @@ public class ExpiresFilter extends FilterBase {
             if (configuration != null) {
                 Date result = getExpirationDate(configuration, response);
                 if (log.isDebugEnabled()) {
-                    log.debug(sm.getString(
-                            "expiresFilter.useMatchingConfiguration",
-                            configuration, contentTypeWithoutCharset,
-                            contentType, result));
+                    log.debug(sm.getString("expiresFilter.useMatchingConfiguration", configuration,
+                            contentTypeWithoutCharset, contentType, result));
                 }
                 return result;
             }
@@ -1340,74 +1296,69 @@ public class ExpiresFilter extends FilterBase {
             if (configuration != null) {
                 Date result = getExpirationDate(configuration, response);
                 if (log.isDebugEnabled()) {
-                    log.debug(sm.getString(
-                            "expiresFilter.useMatchingConfiguration",
-                            configuration, majorType, contentType, result));
+                    log.debug(sm.getString("expiresFilter.useMatchingConfiguration", configuration, majorType,
+                            contentType, result));
                 }
                 return result;
             }
         }
 
         if (defaultExpiresConfiguration != null) {
-            Date result = getExpirationDate(defaultExpiresConfiguration,
-                    response);
+            Date result = getExpirationDate(defaultExpiresConfiguration, response);
             if (log.isDebugEnabled()) {
-                log.debug(sm.getString("expiresFilter.useDefaultConfiguration",
-                        defaultExpiresConfiguration, contentType, result));
+                log.debug(sm.getString("expiresFilter.useDefaultConfiguration", defaultExpiresConfiguration,
+                        contentType, result));
             }
             return result;
         }
 
         if (log.isDebugEnabled()) {
-            log.debug(sm.getString(
-                    "expiresFilter.noExpirationConfiguredForContentType",
-                    contentType));
+            log.debug(sm.getString("expiresFilter.noExpirationConfiguredForContentType", contentType));
         }
         return null;
     }
 
     /**
      * <p>
-     * Returns the expiration date of the given {@link ExpiresConfiguration},
-     * {@link HttpServletRequest} and {@link XHttpServletResponse}.
+     * Returns the expiration date of the given {@link ExpiresConfiguration}, {@link HttpServletRequest} and
+     * {@link XHttpServletResponse}.
      * </p>
      * <p>
      * {@code protected} for extension.
      * </p>
+     *
      * @param configuration The parsed expires
-     * @param response The Servlet response
+     * @param response      The Servlet response
+     *
      * @return the expiration date
      */
-    protected Date getExpirationDate(ExpiresConfiguration configuration,
-            XHttpServletResponse response) {
+    protected Date getExpirationDate(ExpiresConfiguration configuration, XHttpServletResponse response) {
         Calendar calendar;
         switch (configuration.getStartingPoint()) {
-        case ACCESS_TIME:
-            calendar = Calendar.getInstance();
-            break;
-        case LAST_MODIFICATION_TIME:
-            if (response.isLastModifiedHeaderSet()) {
-                try {
-                    long lastModified = response.getLastModifiedHeader();
-                    calendar = Calendar.getInstance();
-                    calendar.setTimeInMillis(lastModified);
-                } catch (NumberFormatException e) {
-                    // default to now
+            case ACCESS_TIME:
+                calendar = Calendar.getInstance();
+                break;
+            case LAST_MODIFICATION_TIME:
+                if (response.isLastModifiedHeaderSet()) {
+                    try {
+                        long lastModified = response.getLastModifiedHeader();
+                        calendar = Calendar.getInstance();
+                        calendar.setTimeInMillis(lastModified);
+                    } catch (NumberFormatException e) {
+                        // default to now
+                        calendar = Calendar.getInstance();
+                    }
+                } else {
+                    // Last-Modified header not found, use now
                     calendar = Calendar.getInstance();
                 }
-            } else {
-                // Last-Modified header not found, use now
-                calendar = Calendar.getInstance();
-            }
-            break;
-        default:
-            throw new IllegalStateException(sm.getString(
-                    "expiresFilter.unsupportedStartingPoint",
-                    configuration.getStartingPoint()));
+                break;
+            default:
+                throw new IllegalStateException(
+                        sm.getString("expiresFilter.unsupportedStartingPoint", configuration.getStartingPoint()));
         }
         for (Duration duration : configuration.getDurations()) {
-            calendar.add(duration.getUnit().getCalendardField(),
-                    duration.getAmount());
+            calendar.add(duration.getUnit().getCalendardField(), duration.getAmount());
         }
 
         return calendar.getTime();
@@ -1430,51 +1381,44 @@ public class ExpiresFilter extends FilterBase {
 
             try {
                 if (name.startsWith(PARAMETER_EXPIRES_BY_TYPE)) {
-                    String contentType = name.substring(
-                            PARAMETER_EXPIRES_BY_TYPE.length()).trim().toLowerCase(Locale.ENGLISH);
+                    String contentType = name.substring(PARAMETER_EXPIRES_BY_TYPE.length()).trim()
+                            .toLowerCase(Locale.ENGLISH);
                     ExpiresConfiguration expiresConfiguration = parseExpiresConfiguration(value);
-                    this.expiresConfigurationByContentType.put(contentType,
-                            expiresConfiguration);
+                    this.expiresConfigurationByContentType.put(contentType, expiresConfiguration);
                 } else if (name.equalsIgnoreCase(PARAMETER_EXPIRES_DEFAULT)) {
                     ExpiresConfiguration expiresConfiguration = parseExpiresConfiguration(value);
                     this.defaultExpiresConfiguration = expiresConfiguration;
                 } else if (name.equalsIgnoreCase(PARAMETER_EXPIRES_EXCLUDED_RESPONSE_STATUS_CODES)) {
                     this.excludedResponseStatusCodes = commaDelimitedListToIntArray(value);
                 } else {
-                    log.warn(sm.getString(
-                            "expiresFilter.unknownParameterIgnored", name,
-                            value));
+                    log.warn(sm.getString("expiresFilter.unknownParameterIgnored", name, value));
                 }
             } catch (RuntimeException e) {
-                throw new ServletException(sm.getString(
-                        "expiresFilter.exceptionProcessingParameter", name,
-                        value), e);
+                throw new ServletException(sm.getString("expiresFilter.exceptionProcessingParameter", name, value), e);
             }
         }
 
-        log.debug(sm.getString("expiresFilter.filterInitialized",
-                this.toString()));
+        log.debug(sm.getString("expiresFilter.filterInitialized", this.toString()));
     }
 
     /**
      * <p>
      * {@code protected} for extension.
      * </p>
-     * @param request The Servlet request
+     *
+     * @param request  The Servlet request
      * @param response The Servlet response
+     *
      * @return <code>true</code> if an expire header may be added
      */
-    protected boolean isEligibleToExpirationHeaderGeneration(
-            HttpServletRequest request, XHttpServletResponse response) {
+    protected boolean isEligibleToExpirationHeaderGeneration(HttpServletRequest request,
+            XHttpServletResponse response) {
         boolean expirationHeaderHasBeenSet = response.containsHeader(HEADER_EXPIRES) ||
                 contains(response.getCacheControlHeader(), "max-age");
         if (expirationHeaderHasBeenSet) {
             if (log.isDebugEnabled()) {
-                log.debug(sm.getString(
-                        "expiresFilter.expirationHeaderAlreadyDefined",
-                        request.getRequestURI(),
-                        Integer.valueOf(response.getStatus()),
-                        response.getContentType()));
+                log.debug(sm.getString("expiresFilter.expirationHeaderAlreadyDefined", request.getRequestURI(),
+                        Integer.valueOf(response.getStatus()), response.getContentType()));
             }
             return false;
         }
@@ -1482,10 +1426,8 @@ public class ExpiresFilter extends FilterBase {
         for (int skippedStatusCode : this.excludedResponseStatusCodes) {
             if (response.getStatus() == skippedStatusCode) {
                 if (log.isDebugEnabled()) {
-                    log.debug(sm.getString("expiresFilter.skippedStatusCode",
-                            request.getRequestURI(),
-                            Integer.valueOf(response.getStatus()),
-                            response.getContentType()));
+                    log.debug(sm.getString("expiresFilter.skippedStatusCode", request.getRequestURI(),
+                            Integer.valueOf(response.getStatus()), response.getContentType()));
                 }
                 return false;
             }
@@ -1496,26 +1438,23 @@ public class ExpiresFilter extends FilterBase {
 
     /**
      * <p>
-     * If no expiration header has been set by the servlet and an expiration has
-     * been defined in the {@link ExpiresFilter} configuration, sets the
-     * '{@code Expires}' header and the attribute '{@code max-age}' of the
+     * If no expiration header has been set by the servlet and an expiration has been defined in the
+     * {@link ExpiresFilter} configuration, sets the '{@code Expires}' header and the attribute '{@code max-age}' of the
      * '{@code Cache-Control}' header.
      * </p>
      * <p>
      * Must be called on the "Start Write Response Body" event.
      * </p>
      * <p>
-     * Invocations to {@code Logger.debug(...)} are guarded by
-     * {@link Log#isDebugEnabled()} because
-     * {@link HttpServletRequest#getRequestURI()} and
-     * {@link HttpServletResponse#getContentType()} costs {@code String}
+     * Invocations to {@code Logger.debug(...)} are guarded by {@link Log#isDebugEnabled()} because
+     * {@link HttpServletRequest#getRequestURI()} and {@link HttpServletResponse#getContentType()} costs {@code String}
      * objects instantiations (as of Tomcat 7).
      * </p>
-     * @param request The Servlet request
+     *
+     * @param request  The Servlet request
      * @param response The Servlet response
      */
-    public void onBeforeWriteResponseBody(HttpServletRequest request,
-            XHttpServletResponse response) {
+    public void onBeforeWriteResponseBody(HttpServletRequest request, XHttpServletResponse response) {
 
         if (!isEligibleToExpirationHeaderGeneration(request, response)) {
             return;
@@ -1524,21 +1463,16 @@ public class ExpiresFilter extends FilterBase {
         Date expirationDate = getExpirationDate(request, response);
         if (expirationDate == null) {
             if (log.isDebugEnabled()) {
-                log.debug(sm.getString("expiresFilter.noExpirationConfigured",
-                        request.getRequestURI(),
-                        Integer.valueOf(response.getStatus()),
-                        response.getContentType()));
+                log.debug(sm.getString("expiresFilter.noExpirationConfigured", request.getRequestURI(),
+                        Integer.valueOf(response.getStatus()), response.getContentType()));
             }
         } else {
             if (log.isDebugEnabled()) {
-                log.debug(sm.getString("expiresFilter.setExpirationDate",
-                        request.getRequestURI(),
-                        Integer.valueOf(response.getStatus()),
-                        response.getContentType(), expirationDate));
+                log.debug(sm.getString("expiresFilter.setExpirationDate", request.getRequestURI(),
+                        Integer.valueOf(response.getStatus()), response.getContentType(), expirationDate));
             }
 
-            String maxAgeDirective = "max-age=" +
-                    ((expirationDate.getTime() - System.currentTimeMillis()) / 1000);
+            String maxAgeDirective = "max-age=" + ((expirationDate.getTime() - System.currentTimeMillis()) / 1000);
 
             String cacheControlHeader = response.getCacheControlHeader();
             String newCacheControlHeader = (cacheControlHeader == null) ? maxAgeDirective
@@ -1550,11 +1484,11 @@ public class ExpiresFilter extends FilterBase {
     }
 
     /**
-     * Parse configuration lines like
-     * '{@code access plus 1 month 15 days 2 hours}' or
+     * Parse configuration lines like '{@code access plus 1 month 15 days 2 hours}' or
      * '{@code modification 1 day 2 hours 5 seconds}'
      *
      * @param inputLine the input
+     *
      * @return the parsed expires
      */
     protected ExpiresConfiguration parseExpiresConfiguration(String inputLine) {
@@ -1567,38 +1501,30 @@ public class ExpiresFilter extends FilterBase {
         try {
             currentToken = tokenizer.nextToken();
         } catch (NoSuchElementException e) {
-            throw new IllegalStateException(sm.getString(
-                    "expiresFilter.startingPointNotFound", line));
+            throw new IllegalStateException(sm.getString("expiresFilter.startingPointNotFound", line));
         }
 
         StartingPoint startingPoint;
-        if ("access".equalsIgnoreCase(currentToken) ||
-                "now".equalsIgnoreCase(currentToken)) {
+        if ("access".equalsIgnoreCase(currentToken) || "now".equalsIgnoreCase(currentToken)) {
             startingPoint = StartingPoint.ACCESS_TIME;
         } else if ("modification".equalsIgnoreCase(currentToken)) {
             startingPoint = StartingPoint.LAST_MODIFICATION_TIME;
-        } else if (!tokenizer.hasMoreTokens() &&
-                startsWithIgnoreCase(currentToken, "a")) {
+        } else if (!tokenizer.hasMoreTokens() && startsWithIgnoreCase(currentToken, "a")) {
             startingPoint = StartingPoint.ACCESS_TIME;
             // trick : convert duration configuration from old to new style
-            tokenizer = new StringTokenizer(currentToken.substring(1) +
-                    " seconds", " ");
-        } else if (!tokenizer.hasMoreTokens() &&
-                startsWithIgnoreCase(currentToken, "m")) {
+            tokenizer = new StringTokenizer(currentToken.substring(1) + " seconds", " ");
+        } else if (!tokenizer.hasMoreTokens() && startsWithIgnoreCase(currentToken, "m")) {
             startingPoint = StartingPoint.LAST_MODIFICATION_TIME;
             // trick : convert duration configuration from old to new style
-            tokenizer = new StringTokenizer(currentToken.substring(1) +
-                    " seconds", " ");
+            tokenizer = new StringTokenizer(currentToken.substring(1) + " seconds", " ");
         } else {
-            throw new IllegalStateException(sm.getString(
-                    "expiresFilter.startingPointInvalid", currentToken, line));
+            throw new IllegalStateException(sm.getString("expiresFilter.startingPointInvalid", currentToken, line));
         }
 
         try {
             currentToken = tokenizer.nextToken();
         } catch (NoSuchElementException e) {
-            throw new IllegalStateException(sm.getString(
-                    "expiresFilter.noDurationFound", line));
+            throw new IllegalStateException(sm.getString("expiresFilter.noDurationFound", line));
         }
 
         if ("plus".equalsIgnoreCase(currentToken)) {
@@ -1606,8 +1532,7 @@ public class ExpiresFilter extends FilterBase {
             try {
                 currentToken = tokenizer.nextToken();
             } catch (NoSuchElementException e) {
-                throw new IllegalStateException(sm.getString(
-                        "expiresFilter.noDurationFound", line));
+                throw new IllegalStateException(sm.getString("expiresFilter.noDurationFound", line));
             }
         }
 
@@ -1618,46 +1543,33 @@ public class ExpiresFilter extends FilterBase {
             try {
                 amount = Integer.parseInt(currentToken);
             } catch (NumberFormatException e) {
-                throw new IllegalStateException(sm.getString(
-                        "expiresFilter.invalidDurationNumber",
-                        currentToken, line));
+                throw new IllegalStateException(
+                        sm.getString("expiresFilter.invalidDurationNumber", currentToken, line));
             }
 
             try {
                 currentToken = tokenizer.nextToken();
             } catch (NoSuchElementException e) {
                 throw new IllegalStateException(
-                        sm.getString(
-                                "expiresFilter.noDurationUnitAfterAmount",
-                                Integer.valueOf(amount), line));
+                        sm.getString("expiresFilter.noDurationUnitAfterAmount", Integer.valueOf(amount), line));
             }
             DurationUnit durationUnit;
-            if ("year".equalsIgnoreCase(currentToken) ||
-                    "years".equalsIgnoreCase(currentToken)) {
+            if ("year".equalsIgnoreCase(currentToken) || "years".equalsIgnoreCase(currentToken)) {
                 durationUnit = DurationUnit.YEAR;
-            } else if ("month".equalsIgnoreCase(currentToken) ||
-                    "months".equalsIgnoreCase(currentToken)) {
+            } else if ("month".equalsIgnoreCase(currentToken) || "months".equalsIgnoreCase(currentToken)) {
                 durationUnit = DurationUnit.MONTH;
-            } else if ("week".equalsIgnoreCase(currentToken) ||
-                    "weeks".equalsIgnoreCase(currentToken)) {
+            } else if ("week".equalsIgnoreCase(currentToken) || "weeks".equalsIgnoreCase(currentToken)) {
                 durationUnit = DurationUnit.WEEK;
-            } else if ("day".equalsIgnoreCase(currentToken) ||
-                    "days".equalsIgnoreCase(currentToken)) {
+            } else if ("day".equalsIgnoreCase(currentToken) || "days".equalsIgnoreCase(currentToken)) {
                 durationUnit = DurationUnit.DAY;
-            } else if ("hour".equalsIgnoreCase(currentToken) ||
-                    "hours".equalsIgnoreCase(currentToken)) {
+            } else if ("hour".equalsIgnoreCase(currentToken) || "hours".equalsIgnoreCase(currentToken)) {
                 durationUnit = DurationUnit.HOUR;
-            } else if ("minute".equalsIgnoreCase(currentToken) ||
-                    "minutes".equalsIgnoreCase(currentToken)) {
+            } else if ("minute".equalsIgnoreCase(currentToken) || "minutes".equalsIgnoreCase(currentToken)) {
                 durationUnit = DurationUnit.MINUTE;
-            } else if ("second".equalsIgnoreCase(currentToken) ||
-                    "seconds".equalsIgnoreCase(currentToken)) {
+            } else if ("second".equalsIgnoreCase(currentToken) || "seconds".equalsIgnoreCase(currentToken)) {
                 durationUnit = DurationUnit.SECOND;
             } else {
-                throw new IllegalStateException(
-                        sm.getString(
-                                "expiresFilter.invalidDurationUnit",
-                                currentToken, line));
+                throw new IllegalStateException(sm.getString("expiresFilter.invalidDurationUnit", currentToken, line));
             }
 
             Duration duration = new Duration(amount, durationUnit);
@@ -1673,8 +1585,7 @@ public class ExpiresFilter extends FilterBase {
         return new ExpiresConfiguration(startingPoint, durations);
     }
 
-    public void setDefaultExpiresConfiguration(
-            ExpiresConfiguration defaultExpiresConfiguration) {
+    public void setDefaultExpiresConfiguration(ExpiresConfiguration defaultExpiresConfiguration) {
         this.defaultExpiresConfiguration = defaultExpiresConfiguration;
     }
 
@@ -1690,8 +1601,7 @@ public class ExpiresFilter extends FilterBase {
     @Override
     public String toString() {
         return getClass().getSimpleName() + "[excludedResponseStatusCode=[" +
-                intsToCommaDelimitedString(this.excludedResponseStatusCodes) +
-                "], default=" + this.defaultExpiresConfiguration + ", byType=" +
-                this.expiresConfigurationByContentType + "]";
+                intsToCommaDelimitedString(this.excludedResponseStatusCodes) + "], default=" +
+                this.defaultExpiresConfiguration + ", byType=" + this.expiresConfigurationByContentType + "]";
     }
 }
diff --git a/java/org/apache/catalina/filters/FailedRequestFilter.java b/java/org/apache/catalina/filters/FailedRequestFilter.java
index 7a6473736e..5ce47668da 100644
--- a/java/org/apache/catalina/filters/FailedRequestFilter.java
+++ b/java/org/apache/catalina/filters/FailedRequestFilter.java
@@ -30,16 +30,12 @@ import org.apache.juli.logging.LogFactory;
 import org.apache.tomcat.util.http.Parameters.FailReason;
 
 /**
- * Filter that will reject requests if there was a failure during parameter
- * parsing. This filter can be used to ensure that none parameter values
- * submitted by client are lost.
- *
+ * Filter that will reject requests if there was a failure during parameter parsing. This filter can be used to ensure
+ * that none parameter values submitted by client are lost.
  * <p>
- * Note that parameter parsing may consume the body of an HTTP request, so
- * caution is needed if the servlet protected by this filter uses
- * <code>request.getInputStream()</code> or <code>request.getReader()</code>
- * calls. In general the risk of breaking a web application by adding this
- * filter is not so high, because parameter parsing does check content type
+ * Note that parameter parsing may consume the body of an HTTP request, so caution is needed if the servlet protected by
+ * this filter uses <code>request.getInputStream()</code> or <code>request.getReader()</code> calls. In general the risk
+ * of breaking a web application by adding this filter is not so high, because parameter parsing does check content type
  * of the request before consuming the request body.
  */
 public class FailedRequestFilter extends FilterBase {
@@ -54,11 +50,10 @@ public class FailedRequestFilter extends FilterBase {
     }
 
     @Override
-    public void doFilter(ServletRequest request, ServletResponse response,
-            FilterChain chain) throws IOException, ServletException {
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+            throws IOException, ServletException {
         if (!isGoodRequest(request)) {
-            FailReason reason = (FailReason) request.getAttribute(
-                    Globals.PARAMETER_PARSE_FAILED_REASON_ATTR);
+            FailReason reason = (FailReason) request.getAttribute(Globals.PARAMETER_PARSE_FAILED_REASON_ATTR);
 
             int status;
 
@@ -75,8 +70,8 @@ public class FailedRequestFilter extends FilterBase {
                     // and/or URI could be well below any limits set. Use the
                     // default.
                 case UNKNOWN: // Assume the client is at fault
-                // Various things that the client can get wrong that don't have
-                // a specific status code so use the default.
+                    // Various things that the client can get wrong that don't have
+                    // a specific status code so use the default.
                 case INVALID_CONTENT_TYPE:
                 case MULTIPART_CONFIG_INVALID:
                 case NO_NAME:
diff --git a/java/org/apache/catalina/filters/FilterBase.java b/java/org/apache/catalina/filters/FilterBase.java
index 6513136e51..c20abf8b69 100644
--- a/java/org/apache/catalina/filters/FilterBase.java
+++ b/java/org/apache/catalina/filters/FilterBase.java
@@ -27,8 +27,7 @@ import org.apache.tomcat.util.IntrospectionUtils;
 import org.apache.tomcat.util.res.StringManager;
 
 /**
- * Base class for filters that provides generic initialisation and a simple
- * no-op destruction.
+ * Base class for filters that provides generic initialisation and a simple no-op destruction.
  */
 public abstract class FilterBase implements Filter {
 
@@ -38,26 +37,21 @@ public abstract class FilterBase implements Filter {
 
 
     /**
-     * Iterates over the configuration parameters and either logs a warning,
-     * or throws an exception for any parameter that does not have a matching
-     * setter in this filter.
+     * Iterates over the configuration parameters and either logs a warning, or throws an exception for any parameter
+     * that does not have a matching setter in this filter.
      *
-     * @param filterConfig The configuration information associated with the
-     *                     filter instance being initialised
+     * @param filterConfig The configuration information associated with the filter instance being initialised
      *
-     * @throws ServletException if {@link #isConfigProblemFatal()} returns
-     *                          {@code true} and a configured parameter does not
-     *                          have a matching setter
+     * @throws ServletException if {@link #isConfigProblemFatal()} returns {@code true} and a configured parameter does
+     *                              not have a matching setter
      */
     @Override
     public void init(FilterConfig filterConfig) throws ServletException {
         Enumeration<String> paramNames = filterConfig.getInitParameterNames();
         while (paramNames.hasMoreElements()) {
             String paramName = paramNames.nextElement();
-            if (!IntrospectionUtils.setProperty(this, paramName,
-                    filterConfig.getInitParameter(paramName))) {
-                String msg = sm.getString("filterbase.noSuchProperty",
-                        paramName, this.getClass().getName());
+            if (!IntrospectionUtils.setProperty(this, paramName, filterConfig.getInitParameter(paramName))) {
+                String msg = sm.getString("filterbase.noSuchProperty", paramName, this.getClass().getName());
                 if (isConfigProblemFatal()) {
                     throw new ServletException(msg);
                 } else {
@@ -68,12 +62,10 @@ public abstract class FilterBase implements Filter {
     }
 
     /**
-     * Determines if an exception when calling a setter or an unknown
-     * configuration attribute triggers the failure of the this filter which in
-     * turn will prevent the web application from starting.
+     * Determines if an exception when calling a setter or an unknown configuration attribute triggers the failure of
+     * the this filter which in turn will prevent the web application from starting.
      *
-     * @return <code>true</code> if a problem should trigger the failure of this
-     *         filter, else <code>false</code>
+     * @return <code>true</code> if a problem should trigger the failure of this filter, else <code>false</code>
      */
     protected boolean isConfigProblemFatal() {
         return false;
diff --git a/java/org/apache/catalina/filters/HttpHeaderSecurityFilter.java b/java/org/apache/catalina/filters/HttpHeaderSecurityFilter.java
index a41aca532c..338a58bd1a 100644
--- a/java/org/apache/catalina/filters/HttpHeaderSecurityFilter.java
+++ b/java/org/apache/catalina/filters/HttpHeaderSecurityFilter.java
@@ -31,8 +31,8 @@ import org.apache.juli.logging.Log;
 import org.apache.juli.logging.LogFactory;
 
 /**
- * Provides a single configuration point for security measures that required the
- * addition of one or more HTTP headers to the response.
+ * Provides a single configuration point for security measures that required the addition of one or more HTTP headers to
+ * the response.
  */
 public class HttpHeaderSecurityFilter extends FilterBase {
 
@@ -91,8 +91,8 @@ public class HttpHeaderSecurityFilter extends FilterBase {
 
 
     @Override
-    public void doFilter(ServletRequest request, ServletResponse response,
-            FilterChain chain) throws IOException, ServletException {
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+            throws IOException, ServletException {
 
         if (response instanceof HttpServletResponse) {
             HttpServletResponse httpResponse = (HttpServletResponse) response;
@@ -222,8 +222,7 @@ public class HttpHeaderSecurityFilter extends FilterBase {
     }
 
 
-    public void setBlockContentTypeSniffingEnabled(
-            boolean blockContentTypeSniffingEnabled) {
+    public void setBlockContentTypeSniffingEnabled(boolean blockContentTypeSniffingEnabled) {
         this.blockContentTypeSniffingEnabled = blockContentTypeSniffingEnabled;
     }
 
@@ -250,9 +249,7 @@ public class HttpHeaderSecurityFilter extends FilterBase {
 
 
     private enum XFrameOption {
-        DENY("DENY"),
-        SAME_ORIGIN("SAMEORIGIN"),
-        ALLOW_FROM("ALLOW-FROM");
+        DENY("DENY"), SAME_ORIGIN("SAMEORIGIN"), ALLOW_FROM("ALLOW-FROM");
 
 
         private final String headerValue;
diff --git a/java/org/apache/catalina/filters/RemoteAddrFilter.java b/java/org/apache/catalina/filters/RemoteAddrFilter.java
index 1239494dea..29fcedb3e2 100644
--- a/java/org/apache/catalina/filters/RemoteAddrFilter.java
+++ b/java/org/apache/catalina/filters/RemoteAddrFilter.java
@@ -27,11 +27,10 @@ import org.apache.juli.logging.Log;
 import org.apache.juli.logging.LogFactory;
 
 /**
- * Concrete implementation of <code>RequestFilter</code> that filters
- * based on the string representation of the remote client's IP address.
+ * Concrete implementation of <code>RequestFilter</code> that filters based on the string representation of the remote
+ * client's IP address.
  *
  * @author Craig R. McClanahan
- *
  */
 public final class RemoteAddrFilter extends RequestFilter {
 
@@ -41,21 +40,19 @@ public final class RemoteAddrFilter extends RequestFilter {
 
 
     /**
-     * Extract the desired request property, and pass it (along with the
-     * specified request and response objects and associated filter chain) to
-     * the protected <code>process()</code> method to perform the actual
-     * filtering.
+     * Extract the desired request property, and pass it (along with the specified request and response objects and
+     * associated filter chain) to the protected <code>process()</code> method to perform the actual filtering.
      *
      * @param request  The servlet request to be processed
      * @param response The servlet response to be created
      * @param chain    The filter chain for this request
      *
-     * @exception IOException if an input/output error occurs
+     * @exception IOException      if an input/output error occurs
      * @exception ServletException if a servlet error occurs
      */
     @Override
-    public void doFilter(ServletRequest request, ServletResponse response,
-            FilterChain chain) throws IOException, ServletException {
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+            throws IOException, ServletException {
 
         process(request.getRemoteAddr(), request, response, chain);
 
diff --git a/java/org/apache/catalina/filters/RemoteCIDRFilter.java b/java/org/apache/catalina/filters/RemoteCIDRFilter.java
index ed56e7c6e1..fbd4caf764 100644
--- a/java/org/apache/catalina/filters/RemoteCIDRFilter.java
+++ b/java/org/apache/catalina/filters/RemoteCIDRFilter.java
@@ -37,8 +37,8 @@ import org.apache.juli.logging.LogFactory;
 public final class RemoteCIDRFilter extends FilterBase {
 
     /**
-     * text/plain MIME type: this is the MIME type we return when a
-     * {@link ServletResponse} is not an {@link HttpServletResponse}
+     * text/plain MIME type: this is the MIME type we return when a {@link ServletResponse} is not an
+     * {@link HttpServletResponse}
      */
     private static final String PLAIN_TEXT_MIME_TYPE = "text/plain";
 
@@ -61,8 +61,7 @@ public final class RemoteCIDRFilter extends FilterBase {
     /**
      * Return a string representation of the {@link NetMask} list in #allow.
      *
-     * @return the #allow list as a string, without the leading '[' and trailing
-     *         ']'
+     * @return the #allow list as a string, without the leading '[' and trailing ']'
      */
     public String getAllow() {
         return allow.toString().replace("[", "").replace("]", "");
@@ -70,10 +69,10 @@ public final class RemoteCIDRFilter extends FilterBase {
 
 
     /**
-     * Fill the #allow list with the list of netmasks provided as an argument,
-     * if any. Calls #fillFromInput.
+     * Fill the #allow list with the list of netmasks provided as an argument, if any. Calls #fillFromInput.
      *
      * @param input The list of netmasks, as a comma separated string
+     *
      * @throws IllegalArgumentException One or more netmasks are invalid
      */
     public void setAllow(final String input) {
@@ -94,8 +93,7 @@ public final class RemoteCIDRFilter extends FilterBase {
     /**
      * Return a string representation of the {@link NetMask} list in #deny.
      *
-     * @return the #deny list as string, without the leading '[' and trailing
-     *         ']'
+     * @return the #deny list as string, without the leading '[' and trailing ']'
      */
     public String getDeny() {
         return deny.toString().replace("[", "").replace("]", "");
@@ -103,10 +101,10 @@ public final class RemoteCIDRFilter extends FilterBase {
 
 
     /**
-     * Fill the #deny list with the list of netmasks provided as an argument, if
-     * any. Calls #fillFromInput.
+     * Fill the #deny list with the list of netmasks provided as an argument, if any. Calls #fillFromInput.
      *
      * @param input The list of netmasks, as a comma separated string
+     *
      * @throws IllegalArgumentException One or more netmasks are invalid
      */
     public void setDeny(final String input) {
@@ -124,7 +122,6 @@ public final class RemoteCIDRFilter extends FilterBase {
     }
 
 
-
     @Override
     protected boolean isConfigProblemFatal() {
         // Failure to configure a security related component should always be
@@ -161,6 +158,7 @@ public final class RemoteCIDRFilter extends FilterBase {
      * Test if a remote's IP address is allowed to proceed.
      *
      * @param property The remote's IP address, as a string
+     *
      * @return true if allowed
      */
     private boolean isAllowed(final String property) {
@@ -206,11 +204,12 @@ public final class RemoteCIDRFilter extends FilterBase {
 
 
     /**
-     * Fill a {@link NetMask} list from a string input containing a
-     * comma-separated list of (hopefully valid) {@link NetMask}s.
+     * Fill a {@link NetMask} list from a string input containing a comma-separated list of (hopefully valid)
+     * {@link NetMask}s.
      *
-     * @param input The input string
+     * @param input  The input string
      * @param target The list to fill
+     *
      * @return a string list of processing errors (empty when no errors)
      */
     private List<String> fillFromInput(final String input, final List<NetMask> target) {
diff --git a/java/org/apache/catalina/filters/RemoteHostFilter.java b/java/org/apache/catalina/filters/RemoteHostFilter.java
index ec10b53cf5..23c2d1f1af 100644
--- a/java/org/apache/catalina/filters/RemoteHostFilter.java
+++ b/java/org/apache/catalina/filters/RemoteHostFilter.java
@@ -27,11 +27,9 @@ import org.apache.juli.logging.Log;
 import org.apache.juli.logging.LogFactory;
 
 /**
- * Concrete implementation of <code>RequestFilter</code> that filters
- * based on the remote client's host name.
+ * Concrete implementation of <code>RequestFilter</code> that filters based on the remote client's host name.
  *
  * @author Craig R. McClanahan
- *
  */
 public final class RemoteHostFilter extends RequestFilter {
 
@@ -41,21 +39,19 @@ public final class RemoteHostFilter extends RequestFilter {
 
 
     /**
-     * Extract the desired request property, and pass it (along with the
-     * specified request and response objects and associated filter chain) to
-     * the protected <code>process()</code> method to perform the actual
-     * filtering.
+     * Extract the desired request property, and pass it (along with the specified request and response objects and
+     * associated filter chain) to the protected <code>process()</code> method to perform the actual filtering.
      *
      * @param request  The servlet request to be processed
      * @param response The servlet response to be created
      * @param chain    The filter chain for this request
      *
-     * @exception IOException if an input/output error occurs
+     * @exception IOException      if an input/output error occurs
      * @exception ServletException if a servlet error occurs
      */
     @Override
-    public void doFilter(ServletRequest request, ServletResponse response,
-            FilterChain chain) throws IOException, ServletException {
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+            throws IOException, ServletException {
 
         process(request.getRemoteHost(), request, response, chain);
 
diff --git a/java/org/apache/catalina/filters/RemoteIpFilter.java b/java/org/apache/catalina/filters/RemoteIpFilter.java
index 6f13a1795e..3fdb17551b 100644
--- a/java/org/apache/catalina/filters/RemoteIpFilter.java
+++ b/java/org/apache/catalina/filters/RemoteIpFilter.java
@@ -58,25 +58,26 @@ import org.apache.tomcat.util.res.StringManager;
  * Servlet filter to integrate "X-Forwarded-For" and "X-Forwarded-Proto" HTTP headers.
  * </p>
  * <p>
- * Most of the design of this Servlet Filter is a port of <a
- * href="https://httpd.apache.org/docs/trunk/mod/mod_remoteip.html">mod_remoteip</a>, this servlet filter replaces the apparent client remote
- * IP address and hostname for the request with the IP address list presented by a proxy or a load balancer via a request headers (e.g.
- * "X-Forwarded-For").
+ * Most of the design of this Servlet Filter is a port of
+ * <a href="https://httpd.apache.org/docs/trunk/mod/mod_remoteip.html">mod_remoteip</a>, this servlet filter replaces
+ * the apparent client remote IP address and hostname for the request with the IP address list presented by a proxy or a
+ * load balancer via a request headers (e.g. "X-Forwarded-For").
  * </p>
  * <p>
- * Another feature of this servlet filter is to replace the apparent scheme (http/https) and server port with the scheme presented by a
- * proxy or a load balancer via a request header (e.g. "X-Forwarded-Proto").
+ * Another feature of this servlet filter is to replace the apparent scheme (http/https) and server port with the scheme
+ * presented by a proxy or a load balancer via a request header (e.g. "X-Forwarded-Proto").
  * </p>
  * <p>
  * This servlet filter proceeds as follows:
  * </p>
  * <p>
- * If the incoming <code>request.getRemoteAddr()</code> matches the servlet
- * filter's list of internal or trusted proxies:
+ * If the incoming <code>request.getRemoteAddr()</code> matches the servlet filter's list of internal or trusted
+ * proxies:
  * </p>
  * <ul>
- * <li>Loop on the comma delimited list of IPs and hostnames passed by the preceding load balancer or proxy in the given request's Http
- * header named <code>$remoteIpHeader</code> (default value <code>x-forwarded-for</code>). Values are processed in right-to-left order.</li>
+ * <li>Loop on the comma delimited list of IPs and hostnames passed by the preceding load balancer or proxy in the given
+ * request's Http header named <code>$remoteIpHeader</code> (default value <code>x-forwarded-for</code>). Values are
+ * processed in right-to-left order.</li>
  * <li>For each ip/host of the list:
  * <ul>
  * <li>if it matches the internal proxies list, the ip/host is swallowed</li>
@@ -84,12 +85,13 @@ import org.apache.tomcat.util.res.StringManager;
  * <li>otherwise, the ip/host is declared to be the remote ip and looping is stopped.</li>
  * </ul>
  * </li>
- * <li>If the request http header named <code>$protocolHeader</code> (default value <code>X-Forwarded-Proto</code>) consists only of forwards that match
- * <code>protocolHeaderHttpsValue</code> configuration parameter (default <code>https</code>) then <code>request.isSecure = true</code>,
- * <code>request.scheme = https</code> and <code>request.serverPort = 443</code>. Note that 443 can be overwritten with the
- * <code>$httpsServerPort</code> configuration parameter.</li>
- * <li>Mark the request with the attribute {@link Globals#REQUEST_FORWARDED_ATTRIBUTE} and value {@code Boolean.TRUE} to indicate
- * that this request has been forwarded by one or more proxies.</li>
+ * <li>If the request http header named <code>$protocolHeader</code> (default value <code>X-Forwarded-Proto</code>)
+ * consists only of forwards that match <code>protocolHeaderHttpsValue</code> configuration parameter (default
+ * <code>https</code>) then <code>request.isSecure = true</code>, <code>request.scheme = https</code> and
+ * <code>request.serverPort = 443</code>. Note that 443 can be overwritten with the <code>$httpsServerPort</code>
+ * configuration parameter.</li>
+ * <li>Mark the request with the attribute {@link Globals#REQUEST_FORWARDED_ATTRIBUTE} and value {@code Boolean.TRUE} to
+ * indicate that this request has been forwarded by one or more proxies.</li>
  * </ul>
  * <table border="1">
  * <caption>Configuration parameters</caption>
@@ -102,52 +104,47 @@ import org.apache.tomcat.util.res.StringManager;
  * </tr>
  * <tr>
  * <td>remoteIpHeader</td>
- * <td>Name of the Http Header read by this servlet filter that holds the list of traversed IP addresses starting from the requesting client
- * </td>
+ * <td>Name of the Http Header read by this servlet filter that holds the list of traversed IP addresses starting from
+ * the requesting client</td>
  * <td>RemoteIPHeader</td>
  * <td>Compliant http header name</td>
  * <td>x-forwarded-for</td>
  * </tr>
  * <tr>
  * <td>internalProxies</td>
- * <td>Regular expression that matches the IP addresses of internal proxies.
- * If they appear in the <code>remoteIpHeader</code> value, they will be
- * trusted and will not appear
- * in the <code>proxiesHeader</code> value</td>
+ * <td>Regular expression that matches the IP addresses of internal proxies. If they appear in the
+ * <code>remoteIpHeader</code> value, they will be trusted and will not appear in the <code>proxiesHeader</code>
+ * value</td>
  * <td>RemoteIPInternalProxy</td>
- * <td>Regular expression (in the syntax supported by
- * {@link java.util.regex.Pattern java.util.regex})</td>
+ * <td>Regular expression (in the syntax supported by {@link java.util.regex.Pattern java.util.regex})</td>
  * <td>10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|
- *     169\.254\.\d{1,3}\.\d{1,3}|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|
- *     172\.1[6-9]{1}\.\d{1,3}\.\d{1,3}|172\.2[0-9]{1}\.\d{1,3}\.\d{1,3}|
- *     172\.3[0-1]{1}\.\d{1,3}\.\d{1,3}|
- *     0:0:0:0:0:0:0:1|::1
- *     <br>
+ * 169\.254\.\d{1,3}\.\d{1,3}|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|
+ * 172\.1[6-9]{1}\.\d{1,3}\.\d{1,3}|172\.2[0-9]{1}\.\d{1,3}\.\d{1,3}| 172\.3[0-1]{1}\.\d{1,3}\.\d{1,3}|
+ * 0:0:0:0:0:0:0:1|::1 <br>
  * By default, 10/8, 192.168/16, 169.254/16, 127/8, 172.16/12, and 0:0:0:0:0:0:0:1 are allowed.</td>
  * </tr>
  * <tr>
  * <td>proxiesHeader</td>
- * <td>Name of the http header created by this servlet filter to hold the list of proxies that have been processed in the incoming
- * <code>remoteIpHeader</code></td>
+ * <td>Name of the http header created by this servlet filter to hold the list of proxies that have been processed in
+ * the incoming <code>remoteIpHeader</code></td>
  * <td>RemoteIPProxiesHeader</td>
  * <td>Compliant http header name</td>
  * <td>x-forwarded-by</td>
  * </tr>
  * <tr>
  * <td>trustedProxies</td>
- * <td>Regular expression that matches the IP addresses of trusted proxies.
- * If they appear in the <code>remoteIpHeader</code> value, they will be
- * trusted and will appear in the <code>proxiesHeader</code> value</td>
+ * <td>Regular expression that matches the IP addresses of trusted proxies. If they appear in the
+ * <code>remoteIpHeader</code> value, they will be trusted and will appear in the <code>proxiesHeader</code> value</td>
  * <td>RemoteIPTrustedProxy</td>
- * <td>Regular expression (in the syntax supported by
- * {@link java.util.regex.Pattern java.util.regex})</td>
+ * <td>Regular expression (in the syntax supported by {@link java.util.regex.Pattern java.util.regex})</td>
  * <td>&nbsp;</td>
  * </tr>
  * <tr>
  * <td>protocolHeader</td>
  * <td>Name of the http header read by this servlet filter that holds the flag that this request</td>
  * <td>N/A</td>
- * <td>Compliant http header name like <code>X-Forwarded-Proto</code>, <code>X-Forwarded-Ssl</code> or <code>Front-End-Https</code></td>
+ * <td>Compliant http header name like <code>X-Forwarded-Proto</code>, <code>X-Forwarded-Ssl</code> or
+ * <code>Front-End-Https</code></td>
  * <td><code>X-Forwarded-Proto</code></td>
  * </tr>
  * <tr>
@@ -159,14 +156,16 @@ import org.apache.tomcat.util.res.StringManager;
  * </tr>
  * <tr>
  * <td>httpServerPort</td>
- * <td>Value returned by {@link ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates <code>http</code> protocol</td>
+ * <td>Value returned by {@link ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates
+ * <code>http</code> protocol</td>
  * <td>N/A</td>
  * <td>integer</td>
  * <td>80</td>
  * </tr>
  * <tr>
  * <td>httpsServerPort</td>
- * <td>Value returned by {@link ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates <code>https</code> protocol</td>
+ * <td>Value returned by {@link ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates
+ * <code>https</code> protocol</td>
  * <td>N/A</td>
  * <td>integer</td>
  * <td>443</td>
@@ -180,11 +179,11 @@ import org.apache.tomcat.util.res.StringManager;
  * </tr>
  * </table>
  * <p>
- * <strong>Regular expression vs. IP address blocks:</strong> <code>mod_remoteip</code> allows to use address blocks (e.g.
- * <code>192.168/16</code>) to configure <code>RemoteIPInternalProxy</code> and <code>RemoteIPTrustedProxy</code> ; as the JVM doesn't have a
- * library similar to <a
- * href="https://apr.apache.org/docs/apr/1.3/group__apr__network__io.html#gb74d21b8898b7c40bf7fd07ad3eb993d">apr_ipsubnet_test</a>, we rely on
- * regular expressions.
+ * <strong>Regular expression vs. IP address blocks:</strong> <code>mod_remoteip</code> allows to use address blocks
+ * (e.g. <code>192.168/16</code>) to configure <code>RemoteIPInternalProxy</code> and <code>RemoteIPTrustedProxy</code>
+ * ; as the JVM doesn't have a library similar to <a href=
+ * "https://apr.apache.org/docs/apr/1.3/group__apr__network__io.html#gb74d21b8898b7c40bf7fd07ad3eb993d">apr_ipsubnet_test</a>,
+ * we rely on regular expressions.
  * </p>
  * <hr>
  * <p>
@@ -323,8 +322,9 @@ import org.apache.tomcat.util.res.StringManager;
  * </tr>
  * </table>
  * <p>
- * Note : <code>proxy1</code> and <code>proxy2</code> are both trusted proxies that come in <code>x-forwarded-for</code> header, they both
- * are migrated in <code>x-forwarded-by</code> header. <code>x-forwarded-by</code> is null because all the proxies are trusted or internal.
+ * Note : <code>proxy1</code> and <code>proxy2</code> are both trusted proxies that come in <code>x-forwarded-for</code>
+ * header, they both are migrated in <code>x-forwarded-by</code> header. <code>x-forwarded-by</code> is null because all
+ * the proxies are trusted or internal.
  * </p>
  * <hr>
  * <p>
@@ -384,9 +384,10 @@ import org.apache.tomcat.util.res.StringManager;
  * </tr>
  * </table>
  * <p>
- * Note : <code>proxy1</code> and <code>proxy2</code> are both trusted proxies that come in <code>x-forwarded-for</code> header, they both
- * are migrated in <code>x-forwarded-by</code> header. As <code>192.168.0.10</code> is an internal proxy, it does not appear in
- * <code>x-forwarded-by</code>. <code>x-forwarded-by</code> is null because all the proxies are trusted or internal.
+ * Note : <code>proxy1</code> and <code>proxy2</code> are both trusted proxies that come in <code>x-forwarded-for</code>
+ * header, they both are migrated in <code>x-forwarded-by</code> header. As <code>192.168.0.10</code> is an internal
+ * proxy, it does not appear in <code>x-forwarded-by</code>. <code>x-forwarded-by</code> is null because all the proxies
+ * are trusted or internal.
  * </p>
  * <hr>
  * <p>
@@ -448,8 +449,8 @@ import org.apache.tomcat.util.res.StringManager;
  * <p>
  * Note : <code>x-forwarded-by</code> holds the trusted proxy <code>proxy1</code>. <code>x-forwarded-by</code> holds
  * <code>140.211.11.130</code> because <code>untrusted-proxy</code> is not trusted and thus, we cannot trust that
- * <code>untrusted-proxy</code> is the actual remote ip. <code>request.remoteAddr</code> is <code>untrusted-proxy</code> that is an IP
- * verified by <code>proxy1</code>.
+ * <code>untrusted-proxy</code> is the actual remote ip. <code>request.remoteAddr</code> is <code>untrusted-proxy</code>
+ * that is an IP verified by <code>proxy1</code>.
  * </p>
  * <hr>
  */
@@ -699,17 +700,19 @@ public class RemoteIpFilter extends GenericFilter {
      * Convert a given comma delimited list of regular expressions into an array of String
      *
      * @param commaDelimitedStrings The string to split
+     *
      * @return array of patterns (non <code>null</code>)
      */
     protected static String[] commaDelimitedListToStringArray(String commaDelimitedStrings) {
-        return (commaDelimitedStrings == null || commaDelimitedStrings.length() == 0) ? new String[0] : commaSeparatedValuesPattern
-            .split(commaDelimitedStrings);
+        return (commaDelimitedStrings == null || commaDelimitedStrings.length() == 0) ? new String[0]
+                : commaSeparatedValuesPattern.split(commaDelimitedStrings);
     }
 
     /**
      * Convert a list of strings in a comma delimited string.
      *
      * @param stringList List of strings
+     *
      * @return concatenated string
      *
      * @deprecated Unused. Will be removed in Tomcat 11 onwards
@@ -745,15 +748,11 @@ public class RemoteIpFilter extends GenericFilter {
     /**
      * @see #setInternalProxies(String)
      */
-    private Pattern internalProxies = Pattern.compile(
-            "10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|" +
-            "192\\.168\\.\\d{1,3}\\.\\d{1,3}|" +
-            "169\\.254\\.\\d{1,3}\\.\\d{1,3}|" +
-            "127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|" +
-            "172\\.1[6-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" +
-            "172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" +
-            "172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}|" +
-            "0:0:0:0:0:0:0:1|::1");
+    private Pattern internalProxies = Pattern
+            .compile("10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|" + "192\\.168\\.\\d{1,3}\\.\\d{1,3}|" +
+                    "169\\.254\\.\\d{1,3}\\.\\d{1,3}|" + "127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|" +
+                    "172\\.1[6-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" + "172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|" +
+                    "172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}|" + "0:0:0:0:0:0:0:1|::1");
 
     /**
      * @see #setProtocolHeader(String)
@@ -792,13 +791,12 @@ public class RemoteIpFilter extends GenericFilter {
 
     private boolean enableLookups;
 
-    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
+    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
+            throws IOException, ServletException {
 
-        boolean isInternal = internalProxies != null &&
-                internalProxies.matcher(request.getRemoteAddr()).matches();
+        boolean isInternal = internalProxies != null && internalProxies.matcher(request.getRemoteAddr()).matches();
 
-        if (isInternal || (trustedProxies != null &&
-                trustedProxies.matcher(request.getRemoteAddr()).matches())) {
+        if (isInternal || (trustedProxies != null && trustedProxies.matcher(request.getRemoteAddr()).matches())) {
             String remoteIp = null;
             Deque<String> proxiesHeaderValue = new ArrayDeque<>();
             StringBuilder concatRemoteIpHeaderValue = new StringBuilder();
@@ -820,10 +818,9 @@ public class RemoteIpFilter extends GenericFilter {
             for (idx = remoteIpHeaderValue.length - 1; idx >= 0; idx--) {
                 String currentRemoteIp = remoteIpHeaderValue[idx];
                 remoteIp = currentRemoteIp;
-                if (internalProxies !=null && internalProxies.matcher(currentRemoteIp).matches()) {
+                if (internalProxies != null && internalProxies.matcher(currentRemoteIp).matches()) {
                     // do nothing, internalProxies IPs are not appended to the
-                } else if (trustedProxies != null &&
-                        trustedProxies.matcher(currentRemoteIp).matches()) {
+                } else if (trustedProxies != null && trustedProxies.matcher(currentRemoteIp).matches()) {
                     proxiesHeaderValue.addFirst(currentRemoteIp);
                 } else {
                     idx--; // decrement idx because break statement doesn't do it
@@ -911,34 +908,28 @@ public class RemoteIpFilter extends GenericFilter {
             request.setAttribute(Globals.REQUEST_FORWARDED_ATTRIBUTE, Boolean.TRUE);
 
             if (log.isDebugEnabled()) {
-                log.debug("Incoming request " + request.getRequestURI() + " with originalRemoteAddr [" + request.getRemoteAddr() +
-                        "], originalRemoteHost=[" + request.getRemoteHost() + "], originalSecure=[" + request.isSecure() +
-                        "], originalScheme=[" + request.getScheme() + "], originalServerName=[" + request.getServerName() +
-                        "], originalServerPort=[" + request.getServerPort() +
-                        "] will be seen as newRemoteAddr=[" + xRequest.getRemoteAddr() +
+                log.debug("Incoming request " + request.getRequestURI() + " with originalRemoteAddr [" +
+                        request.getRemoteAddr() + "], originalRemoteHost=[" + request.getRemoteHost() +
+                        "], originalSecure=[" + request.isSecure() + "], originalScheme=[" + request.getScheme() +
+                        "], originalServerName=[" + request.getServerName() + "], originalServerPort=[" +
+                        request.getServerPort() + "] will be seen as newRemoteAddr=[" + xRequest.getRemoteAddr() +
                         "], newRemoteHost=[" + xRequest.getRemoteHost() + "], newSecure=[" + xRequest.isSecure() +
                         "], newScheme=[" + xRequest.getScheme() + "], newServerName=[" + xRequest.getServerName() +
                         "], newServerPort=[" + xRequest.getServerPort() + "]");
             }
             if (requestAttributesEnabled) {
-                request.setAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE,
-                        xRequest.getRemoteAddr());
-                request.setAttribute(Globals.REMOTE_ADDR_ATTRIBUTE,
-                        xRequest.getRemoteAddr());
-                request.setAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE,
-                        xRequest.getRemoteHost());
-                request.setAttribute(AccessLog.PROTOCOL_ATTRIBUTE,
-                        xRequest.getProtocol());
-                request.setAttribute(AccessLog.SERVER_NAME_ATTRIBUTE,
-                        xRequest.getServerName());
-                request.setAttribute(AccessLog.SERVER_PORT_ATTRIBUTE,
-                        Integer.valueOf(xRequest.getServerPort()));
+                request.setAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE, xRequest.getRemoteAddr());
+                request.setAttribute(Globals.REMOTE_ADDR_ATTRIBUTE, xRequest.getRemoteAddr());
+                request.setAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE, xRequest.getRemoteHost());
+                request.setAttribute(AccessLog.PROTOCOL_ATTRIBUTE, xRequest.getProtocol());
+                request.setAttribute(AccessLog.SERVER_NAME_ATTRIBUTE, xRequest.getServerName());
+                request.setAttribute(AccessLog.SERVER_PORT_ATTRIBUTE, Integer.valueOf(xRequest.getServerPort()));
             }
             chain.doFilter(xRequest, response);
         } else {
             if (log.isDebugEnabled()) {
-                log.debug("Skip RemoteIpFilter for request " + request.getRequestURI() + " with originalRemoteAddr '"
-                        + request.getRemoteAddr() + "'");
+                log.debug("Skip RemoteIpFilter for request " + request.getRequestURI() + " with originalRemoteAddr '" +
+                        request.getRemoteAddr() + "'");
             }
             chain.doFilter(request, response);
         }
@@ -946,8 +937,7 @@ public class RemoteIpFilter extends GenericFilter {
     }
 
     /*
-     * Considers the value to be secure if it exclusively holds forwards for
-     * {@link #protocolHeaderHttpsValue}.
+     * Considers the value to be secure if it exclusively holds forwards for {@link #protocolHeaderHttpsValue}.
      */
     private boolean isForwardedProtoHeaderValueSecure(String protocolHeaderValue) {
         if (!protocolHeaderValue.contains(",")) {
@@ -973,8 +963,8 @@ public class RemoteIpFilter extends GenericFilter {
                 try {
                     port = Integer.parseInt(portHeaderValue);
                 } catch (NumberFormatException nfe) {
-                    log.debug("Invalid port value [" + portHeaderValue +
-                            "] provided in header [" + getPortHeader() + "]");
+                    log.debug("Invalid port value [" + portHeaderValue + "] provided in header [" + getPortHeader() +
+                            "]");
                 }
             }
         }
@@ -985,13 +975,14 @@ public class RemoteIpFilter extends GenericFilter {
     }
 
     /**
-     * Wrap the incoming <code>request</code> in a {@link XForwardedRequest} if the http header <code>x-forwarded-for</code> is not empty.
-     * {@inheritDoc}
+     * Wrap the incoming <code>request</code> in a {@link XForwardedRequest} if the http header
+     * <code>x-forwarded-for</code> is not empty. {@inheritDoc}
      */
     @Override
-    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+            throws IOException, ServletException {
         if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
-            doFilter((HttpServletRequest)request, (HttpServletResponse)response, chain);
+            doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
         } else {
             chain.doFilter(request, response);
         }
@@ -1035,8 +1026,8 @@ public class RemoteIpFilter extends GenericFilter {
 
     /**
      * @see #setRequestAttributesEnabled(boolean)
-     * @return <code>true</code> if the attributes will be logged, otherwise
-     *         <code>false</code>
+     *
+     * @return <code>true</code> if the attributes will be logged, otherwise <code>false</code>
      */
     public boolean getRequestAttributesEnabled() {
         return requestAttributesEnabled;
@@ -1096,7 +1087,8 @@ public class RemoteIpFilter extends GenericFilter {
             try {
                 setHttpServerPort(Integer.parseInt(getInitParameter(HTTP_SERVER_PORT_PARAMETER)));
             } catch (NumberFormatException e) {
-                throw new NumberFormatException(sm.getString("remoteIpFilter.invalidNumber", HTTP_SERVER_PORT_PARAMETER, e.getLocalizedMessage()));
+                throw new NumberFormatException(sm.getString("remoteIpFilter.invalidNumber", HTTP_SERVER_PORT_PARAMETER,
+                        e.getLocalizedMessage()));
             }
         }
 
@@ -1104,7 +1096,8 @@ public class RemoteIpFilter extends GenericFilter {
             try {
                 setHttpsServerPort(Integer.parseInt(getInitParameter(HTTPS_SERVER_PORT_PARAMETER)));
             } catch (NumberFormatException e) {
-                throw new NumberFormatException(sm.getString("remoteIpFilter.invalidNumber", HTTPS_SERVER_PORT_PARAMETER, e.getLocalizedMessage()));
+                throw new NumberFormatException(sm.getString("remoteIpFilter.invalidNumber",
+                        HTTPS_SERVER_PORT_PARAMETER, e.getLocalizedMessage()));
             }
         }
 
@@ -1115,14 +1108,14 @@ public class RemoteIpFilter extends GenericFilter {
 
     /**
      * <p>
-     * If <code>true</code>, the return values for both {@link
-     * ServletRequest#getLocalName()} and {@link ServletRequest#getServerName()}
-     * will be modified by this Filter rather than just
+     * If <code>true</code>, the return values for both {@link ServletRequest#getLocalName()} and
+     * {@link ServletRequest#getServerName()} will be modified by this Filter rather than just
      * {@link ServletRequest#getServerName()}.
      * </p>
      * <p>
      * Default value : <code>false</code>
      * </p>
+     *
      * @param changeLocalName The new flag value
      */
     public void setChangeLocalName(boolean changeLocalName) {
@@ -1131,14 +1124,14 @@ public class RemoteIpFilter extends GenericFilter {
 
     /**
      * <p>
-     * If <code>true</code>, the return values for both {@link
-     * ServletRequest#getLocalPort()} and {@link ServletRequest#getServerPort()}
-     * will be modified by this Filter rather than just
+     * If <code>true</code>, the return values for both {@link ServletRequest#getLocalPort()} and
+     * {@link ServletRequest#getServerPort()} will be modified by this Filter rather than just
      * {@link ServletRequest#getServerPort()}.
      * </p>
      * <p>
      * Default value : <code>false</code>
      * </p>
+     *
      * @param changeLocalPort The new flag value
      */
     public void setChangeLocalPort(boolean changeLocalPort) {
@@ -1147,12 +1140,13 @@ public class RemoteIpFilter extends GenericFilter {
 
     /**
      * <p>
-     * Server Port value if the {@link #protocolHeader} indicates HTTP (i.e. {@link #protocolHeader} is not null and
-     * has a value different of {@link #protocolHeaderHttpsValue}).
+     * Server Port value if the {@link #protocolHeader} indicates HTTP (i.e. {@link #protocolHeader} is not null and has
+     * a value different of {@link #protocolHeaderHttpsValue}).
      * </p>
      * <p>
      * Default value : 80
      * </p>
+     *
      * @param httpServerPort The server port to use
      */
     public void setHttpServerPort(int httpServerPort) {
@@ -1166,6 +1160,7 @@ public class RemoteIpFilter extends GenericFilter {
      * <p>
      * Default value : 443
      * </p>
+     *
      * @param httpsServerPort The server port to use
      */
     public void setHttpsServerPort(int httpsServerPort) {
@@ -1177,8 +1172,10 @@ public class RemoteIpFilter extends GenericFilter {
      * Regular expression that defines the internal proxies.
      * </p>
      * <p>
-     * Default value : 10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|169\.254.\d{1,3}.\d{1,3}|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|0:0:0:0:0:0:0:1
+     * Default value :
+     * 10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|169\.254.\d{1,3}.\d{1,3}|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|0:0:0:0:0:0:0:1
      * </p>
+     *
      * @param internalProxies The regexp
      */
     public void setInternalProxies(String internalProxies) {
@@ -1191,12 +1188,12 @@ public class RemoteIpFilter extends GenericFilter {
 
     /**
      * <p>
-     * Header that holds the incoming host, usually named
-     * <code>X-Forwarded-Host</code>.
+     * Header that holds the incoming host, usually named <code>X-Forwarded-Host</code>.
      * </p>
      * <p>
      * Default value : <code>null</code>
      * </p>
+     *
      * @param hostHeader The header name
      */
     public void setHostHeader(String hostHeader) {
@@ -1205,13 +1202,13 @@ public class RemoteIpFilter extends GenericFilter {
 
     /**
      * <p>
-     * Header that holds the incoming port, usually named
-     * <code>X-Forwarded-Port</code>. If <code>null</code>,
+     * Header that holds the incoming port, usually named <code>X-Forwarded-Port</code>. If <code>null</code>,
      * {@link #httpServerPort} or {@link #httpsServerPort} will be used.
      * </p>
      * <p>
      * Default value : <code>null</code>
      * </p>
+     *
      * @param portHeader The header name
      */
     public void setPortHeader(String portHeader) {
@@ -1220,12 +1217,13 @@ public class RemoteIpFilter extends GenericFilter {
 
     /**
      * <p>
-     * Header that holds the incoming protocol, usually named <code>X-Forwarded-Proto</code>. If <code>null</code>, request.scheme and
-     * request.secure will not be modified.
+     * Header that holds the incoming protocol, usually named <code>X-Forwarded-Proto</code>. If <code>null</code>,
+     * request.scheme and request.secure will not be modified.
      * </p>
      * <p>
      * Default value : <code>X-Forwarded-Proto</code>
      * </p>
+     *
      * @param protocolHeader The header name
      */
     public void setProtocolHeader(String protocolHeader) {
@@ -1239,6 +1237,7 @@ public class RemoteIpFilter extends GenericFilter {
      * <p>
      * Default value : <code>https</code>
      * </p>
+     *
      * @param protocolHeaderHttpsValue The header value
      */
     public void setProtocolHeaderHttpsValue(String protocolHeaderHttpsValue) {
@@ -1247,9 +1246,10 @@ public class RemoteIpFilter extends GenericFilter {
 
     /**
      * <p>
-     * The proxiesHeader directive specifies a header into which mod_remoteip will collect a list of all of the intermediate client IP
-     * addresses trusted to resolve the actual remote IP. Note that intermediate RemoteIPTrustedProxy addresses are recorded in this header,
-     * while any intermediate RemoteIPInternalProxy addresses are discarded.
+     * The proxiesHeader directive specifies a header into which mod_remoteip will collect a list of all of the
+     * intermediate client IP addresses trusted to resolve the actual remote IP. Note that intermediate
+     * RemoteIPTrustedProxy addresses are recorded in this header, while any intermediate RemoteIPInternalProxy
+     * addresses are discarded.
      * </p>
      * <p>
      * Name of the http header that holds the list of trusted proxies that has been traversed by the http request.
@@ -1260,6 +1260,7 @@ public class RemoteIpFilter extends GenericFilter {
      * <p>
      * Default value : <code>X-Forwarded-By</code>
      * </p>
+     *
      * @param proxiesHeader The header name
      */
     public void setProxiesHeader(String proxiesHeader) {
@@ -1276,6 +1277,7 @@ public class RemoteIpFilter extends GenericFilter {
      * <p>
      * Default value : <code>X-Forwarded-For</code>
      * </p>
+     *
      * @param remoteIpHeader The header name
      */
     public void setRemoteIpHeader(String remoteIpHeader) {
@@ -1283,12 +1285,9 @@ public class RemoteIpFilter extends GenericFilter {
     }
 
     /**
-     * Should this filter set request attributes for IP address, Hostname,
-     * protocol and port used for the request? This are typically used in
-     * conjunction with an {@link AccessLog} which will otherwise log the
-     * original values. Default is <code>true</code>.
-     *
-     * The attributes set are:
+     * Should this filter set request attributes for IP address, Hostname, protocol and port used for the request? This
+     * are typically used in conjunction with an {@link AccessLog} which will otherwise log the original values. Default
+     * is <code>true</code>. The attributes set are:
      * <ul>
      * <li>org.apache.catalina.AccessLog.RemoteAddr</li>
      * <li>org.apache.catalina.AccessLog.RemoteHost</li>
@@ -1297,9 +1296,8 @@ public class RemoteIpFilter extends GenericFilter {
      * <li>org.apache.tomcat.remoteAddr</li>
      * </ul>
      *
-     * @param requestAttributesEnabled  <code>true</code> causes the attributes
-     *                                  to be set, <code>false</code> disables
-     *                                  the setting of the attributes.
+     * @param requestAttributesEnabled <code>true</code> causes the attributes to be set, <code>false</code> disables
+     *                                     the setting of the attributes.
      */
     public void setRequestAttributesEnabled(boolean requestAttributesEnabled) {
         this.requestAttributesEnabled = requestAttributesEnabled;
@@ -1307,12 +1305,12 @@ public class RemoteIpFilter extends GenericFilter {
 
     /**
      * <p>
-     * Regular expression defining proxies that are trusted when they appear in
-     * the {@link #remoteIpHeader} header.
+     * Regular expression defining proxies that are trusted when they appear in the {@link #remoteIpHeader} header.
      * </p>
      * <p>
      * Default value : empty list, no external proxy is trusted.
      * </p>
+     *
      * @param trustedProxies The trusted proxies regexp
      */
     public void setTrustedProxies(String trustedProxies) {
@@ -1328,9 +1326,8 @@ public class RemoteIpFilter extends GenericFilter {
     }
 
     /*
-     * Log objects are not Serializable but this Filter is because it extends
-     * GenericFilter. Tomcat won't serialize a Filter but in case something else
-     * does...
+     * Log objects are not Serializable but this Filter is because it extends GenericFilter. Tomcat won't serialize a
+     * Filter but in case something else does...
      */
     private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
         ois.defaultReadObject();
diff --git a/java/org/apache/catalina/filters/RequestDumperFilter.java b/java/org/apache/catalina/filters/RequestDumperFilter.java
index b8e9796dd9..2a306d23bd 100644
--- a/java/org/apache/catalina/filters/RequestDumperFilter.java
+++ b/java/org/apache/catalina/filters/RequestDumperFilter.java
@@ -36,15 +36,16 @@ import org.apache.juli.logging.LogFactory;
 
 
 /**
- * <p>Implementation of a Filter that logs interesting contents from the
- * specified Request (before processing) and the corresponding Response
- * (after processing).  It is especially useful in debugging problems
- * related to headers and cookies.</p>
- *
- * <p>When using this Filter, it is strongly recommended that the
- * <code>org.apache.catalina.filter.RequestDumperFilter</code> logger is
- * directed to a dedicated file and that the
- * <code>org.apache.juli.VerbatimFormatter</code> is used.</p>
+ * <p>
+ * Implementation of a Filter that logs interesting contents from the specified Request (before processing) and the
+ * corresponding Response (after processing). It is especially useful in debugging problems related to headers and
+ * cookies.
+ * </p>
+ * <p>
+ * When using this Filter, it is strongly recommended that the
+ * <code>org.apache.catalina.filter.RequestDumperFilter</code> logger is directed to a dedicated file and that the
+ * <code>org.apache.juli.VerbatimFormatter</code> is used.
+ * </p>
  *
  * @author Craig R. McClanahan
  */
@@ -52,10 +53,8 @@ public class RequestDumperFilter extends GenericFilter {
 
     private static final long serialVersionUID = 1L;
 
-    private static final String NON_HTTP_REQ_MSG =
-        "Not available. Non-http request.";
-    private static final String NON_HTTP_RES_MSG =
-        "Not available. Non-http response.";
+    private static final String NON_HTTP_REQ_MSG = "Not available. Non-http request.";
+    private static final String NON_HTTP_RES_MSG = "Not available. Non-http response.";
 
     private static final ThreadLocal<Timestamp> timestamp = ThreadLocal.withInitial(Timestamp::new);
 
@@ -65,20 +64,19 @@ public class RequestDumperFilter extends GenericFilter {
 
 
     /**
-     * Log the interesting request parameters, invoke the next Filter in the
-     * sequence, and log the interesting response parameters.
+     * Log the interesting request parameters, invoke the next Filter in the sequence, and log the interesting response
+     * parameters.
      *
      * @param request  The servlet request to be processed
      * @param response The servlet response to be created
      * @param chain    The filter chain being processed
      *
-     * @exception IOException if an input/output error occurs
+     * @exception IOException      if an input/output error occurs
      * @exception ServletException if a servlet error occurs
      */
     @Override
-    public void doFilter(ServletRequest request, ServletResponse response,
-            FilterChain chain)
-        throws IOException, ServletException {
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+            throws IOException, ServletException {
 
         HttpServletRequest hRequest = null;
         HttpServletResponse hResponse = null;
@@ -102,8 +100,7 @@ public class RequestDumperFilter extends GenericFilter {
         }
 
         doLog(" characterEncoding", request.getCharacterEncoding());
-        doLog("     contentLength",
-                Long.toString(request.getContentLengthLong()));
+        doLog("     contentLength", Long.toString(request.getContentLengthLong()));
         doLog("       contentType", request.getContentType());
 
         if (hRequest == null) {
@@ -115,8 +112,7 @@ public class RequestDumperFilter extends GenericFilter {
             Cookie cookies[] = hRequest.getCookies();
             if (cookies != null) {
                 for (Cookie cookie : cookies) {
-                    doLog("            cookie", cookie.getName() +
-                            "=" + cookie.getValue());
+                    doLog("            cookie", cookie.getName() + "=" + cookie.getValue());
                 }
             }
             Enumeration<String> hnames = hRequest.getHeaderNames();
@@ -180,8 +176,7 @@ public class RequestDumperFilter extends GenericFilter {
 
         doLog("            scheme", request.getScheme());
         doLog("        serverName", request.getServerName());
-        doLog("        serverPort",
-                Integer.toString(request.getServerPort()));
+        doLog("        serverPort", Integer.toString(request.getServerPort()));
 
         if (hRequest == null) {
             doLog("       servletPath", NON_HTTP_REQ_MSG);
@@ -189,17 +184,14 @@ public class RequestDumperFilter extends GenericFilter {
             doLog("       servletPath", hRequest.getServletPath());
         }
 
-        doLog("          isSecure",
-                Boolean.valueOf(request.isSecure()).toString());
-        doLog("------------------",
-                "--------------------------------------------");
+        doLog("          isSecure", Boolean.valueOf(request.isSecure()).toString());
+        doLog("------------------", "--------------------------------------------");
 
         // Perform the request
         chain.doFilter(request, response);
 
         // Log post-service information
-        doLog("------------------",
-                "--------------------------------------------");
+        doLog("------------------", "--------------------------------------------");
         if (hRequest == null) {
             doLog("          authType", NON_HTTP_REQ_MSG);
         } else {
@@ -229,13 +221,11 @@ public class RequestDumperFilter extends GenericFilter {
         if (hResponse == null) {
             doLog("            status", NON_HTTP_RES_MSG);
         } else {
-            doLog("            status",
-                    Integer.toString(hResponse.getStatus()));
+            doLog("            status", Integer.toString(hResponse.getStatus()));
         }
 
         doLog("END TIME          ", getTimestamp());
-        doLog("==================",
-                "============================================");
+        doLog("==================", "============================================");
     }
 
     private void doLog(String attribute, String value) {
@@ -261,9 +251,8 @@ public class RequestDumperFilter extends GenericFilter {
 
 
     /*
-     * Log objects are not Serializable but this Filter is because it extends
-     * GenericFilter. Tomcat won't serialize a Filter but in case something else
-     * does...
+     * Log objects are not Serializable but this Filter is because it extends GenericFilter. Tomcat won't serialize a
+     * Filter but in case something else does...
      */
     private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
         ois.defaultReadObject();
@@ -273,9 +262,9 @@ public class RequestDumperFilter extends GenericFilter {
 
     private static final class Timestamp {
         private final Date date = new Date(0);
-        private final SimpleDateFormat format =
-            new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
+        private final SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
         private String dateString = format.format(date);
+
         private void update() {
             dateString = format.format(date);
         }
diff --git a/java/org/apache/catalina/filters/RequestFilter.java b/java/org/apache/catalina/filters/RequestFilter.java
index a20a7683c6..ac222455be 100644
--- a/java/org/apache/catalina/filters/RequestFilter.java
+++ b/java/org/apache/catalina/filters/RequestFilter.java
@@ -28,27 +28,21 @@ import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 /**
- * Implementation of a Filter that performs filtering based on comparing the
- * appropriate request property (selected based on which subclass you choose
- * to configure into your Container's pipeline) against the regular expressions
+ * Implementation of a Filter that performs filtering based on comparing the appropriate request property (selected
+ * based on which subclass you choose to configure into your Container's pipeline) against the regular expressions
  * configured for this Filter.
  * <p>
- * This filter is configured by setting the <code>allow</code> and/or
- * <code>deny</code> properties to a regular expressions (in the syntax
- * supported by {@link Pattern}) to which the appropriate request property will
- * be compared.  Evaluation proceeds as follows:
+ * This filter is configured by setting the <code>allow</code> and/or <code>deny</code> properties to a regular
+ * expressions (in the syntax supported by {@link Pattern}) to which the appropriate request property will be compared.
+ * Evaluation proceeds as follows:
  * <ul>
- * <li>The subclass extracts the request property to be filtered, and
- *     calls the common <code>process()</code> method.
- * <li>If there is a deny expression configured, the property will be compared
- *     to the expression. If a match is found, this request will be rejected
- *     with a "Forbidden" HTTP response.</li>
- * <li>If there is a allow expression configured, the property will be compared
- *     to the expression. If a match is found, this request will be allowed to
- *     pass through to the next filter in the current pipeline.</li>
- * <li>If a deny expression was specified but no allow expression, allow this
- *     request to pass through (because none of the deny expressions matched
- *     it).
+ * <li>The subclass extracts the request property to be filtered, and calls the common <code>process()</code> method.
+ * <li>If there is a deny expression configured, the property will be compared to the expression. If a match is found,
+ * this request will be rejected with a "Forbidden" HTTP response.</li>
+ * <li>If there is a allow expression configured, the property will be compared to the expression. If a match is found,
+ * this request will be allowed to pass through to the next filter in the current pipeline.</li>
+ * <li>If a deny expression was specified but no allow expression, allow this request to pass through (because none of
+ * the deny expressions matched it).
  * <li>The request will be rejected with a "Forbidden" HTTP response.</li>
  * </ul>
  */
@@ -68,8 +62,8 @@ public abstract class RequestFilter extends FilterBase {
     protected Pattern deny = null;
 
     /**
-     * The HTTP response status code that is used when rejecting denied
-     * request. It is 403 by default, but may be changed to be 404.
+     * The HTTP response status code that is used when rejecting denied request. It is 403 by default, but may be
+     * changed to be 404.
      */
     protected int denyStatus = HttpServletResponse.SC_FORBIDDEN;
 
@@ -83,8 +77,8 @@ public abstract class RequestFilter extends FilterBase {
 
 
     /**
-     * @return the regular expression used to test for allowed requests for this
-     * Filter, if any; otherwise, return <code>null</code>.
+     * @return the regular expression used to test for allowed requests for this Filter, if any; otherwise, return
+     *             <code>null</code>.
      */
     public String getAllow() {
         if (allow == null) {
@@ -95,8 +89,7 @@ public abstract class RequestFilter extends FilterBase {
 
 
     /**
-     * Set the regular expression used to test for allowed requests for this
-     * Filter, if any.
+     * Set the regular expression used to test for allowed requests for this Filter, if any.
      *
      * @param allow The new allow expression
      */
@@ -110,8 +103,8 @@ public abstract class RequestFilter extends FilterBase {
 
 
     /**
-     * @return the regular expression used to test for denied requests for this
-     * Filter, if any; otherwise, return <code>null</code>.
+     * @return the regular expression used to test for denied requests for this Filter, if any; otherwise, return
+     *             <code>null</code>.
      */
     public String getDeny() {
         if (deny == null) {
@@ -122,8 +115,7 @@ public abstract class RequestFilter extends FilterBase {
 
 
     /**
-     * Set the regular expression used to test for denied requests for this
-     * Filter, if any.
+     * Set the regular expression used to test for denied requests for this Filter, if any.
      *
      * @param deny The new deny expression
      */
@@ -158,22 +150,20 @@ public abstract class RequestFilter extends FilterBase {
 
 
     /**
-     * Extract the desired request property, and pass it (along with the
-     * specified request and response objects) to the protected
-     * <code>process()</code> method to perform the actual filtering.
-     * This method must be implemented by a concrete subclass.
+     * Extract the desired request property, and pass it (along with the specified request and response objects) to the
+     * protected <code>process()</code> method to perform the actual filtering. This method must be implemented by a
+     * concrete subclass.
      *
-     * @param request The servlet request to be processed
+     * @param request  The servlet request to be processed
      * @param response The servlet response to be created
-     * @param chain The filter chain
+     * @param chain    The filter chain
      *
-     * @exception IOException if an input/output error occurs
+     * @exception IOException      if an input/output error occurs
      * @exception ServletException if a servlet error occurs
      */
     @Override
-    public abstract void doFilter(ServletRequest request,
-            ServletResponse response, FilterChain chain) throws IOException,
-            ServletException;
+    public abstract void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+            throws IOException, ServletException;
 
 
     // ------------------------------------------------------ Protected Methods
@@ -186,19 +176,17 @@ public abstract class RequestFilter extends FilterBase {
 
 
     /**
-     * Perform the filtering that has been configured for this Filter, matching
-     * against the specified request property.
+     * Perform the filtering that has been configured for this Filter, matching against the specified request property.
      *
      * @param property The request property on which to filter
-     * @param request The servlet request to be processed
+     * @param request  The servlet request to be processed
      * @param response The servlet response to be processed
-     * @param chain The filter chain
+     * @param chain    The filter chain
      *
-     * @exception IOException if an input/output error occurs
+     * @exception IOException      if an input/output error occurs
      * @exception ServletException if a servlet error occurs
      */
-    protected void process(String property, ServletRequest request,
-            ServletResponse response, FilterChain chain)
+    protected void process(String property, ServletRequest request, ServletResponse response, FilterChain chain)
             throws IOException, ServletException {
 
         if (isAllowed(property)) {
@@ -206,8 +194,8 @@ public abstract class RequestFilter extends FilterBase {
         } else {
             if (response instanceof HttpServletResponse) {
                 if (getLogger().isDebugEnabled()) {
-                    getLogger().debug(sm.getString("requestFilter.deny",
-                            ((HttpServletRequest) request).getRequestURI(), property));
+                    getLogger().debug(sm.getString("requestFilter.deny", ((HttpServletRequest) request).getRequestURI(),
+                            property));
                 }
                 ((HttpServletResponse) response).sendError(denyStatus);
             } else {
@@ -220,9 +208,9 @@ public abstract class RequestFilter extends FilterBase {
     /**
      * Process the allow and deny rules for the provided property.
      *
-     * @param property  The property to test against the allow and deny lists
-     * @return          <code>true</code> if this request should be allowed,
-     *                  <code>false</code> otherwise
+     * @param property The property to test against the allow and deny lists
+     *
+     * @return <code>true</code> if this request should be allowed, <code>false</code> otherwise
      */
     private boolean isAllowed(String property) {
         if (deny != null && deny.matcher(property).matches()) {
@@ -243,8 +231,7 @@ public abstract class RequestFilter extends FilterBase {
         return false;
     }
 
-    private void sendErrorWhenNotHttp(ServletResponse response)
-            throws IOException {
+    private void sendErrorWhenNotHttp(ServletResponse response) throws IOException {
         response.setContentType(PLAIN_TEXT_MIME_TYPE);
         response.getWriter().write(sm.getString("http.403"));
         response.getWriter().flush();
diff --git a/java/org/apache/catalina/filters/RestCsrfPreventionFilter.java b/java/org/apache/catalina/filters/RestCsrfPreventionFilter.java
index 58f76f1467..46dadb62a4 100644
--- a/java/org/apache/catalina/filters/RestCsrfPreventionFilter.java
+++ b/java/org/apache/catalina/filters/RestCsrfPreventionFilter.java
@@ -34,9 +34,8 @@ import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 
 /**
- * Provides basic CSRF protection for REST APIs. The filter assumes that the
- * clients have adapted the transfer of the nonce through the 'X-CSRF-Token'
- * header.
+ * Provides basic CSRF protection for REST APIs. The filter assumes that the clients have adapted the transfer of the
+ * nonce through the 'X-CSRF-Token' header.
  *
  * <pre>
  * Positive scenario:
@@ -95,8 +94,7 @@ public class RestCsrfPreventionFilter extends CsrfPreventionFilterBase {
         super.init(filterConfig);
 
         // Put the expected request header name into the application scope
-        filterConfig.getServletContext().setAttribute(
-                Constants.CSRF_REST_NONCE_HEADER_NAME_KEY,
+        filterConfig.getServletContext().setAttribute(Constants.CSRF_REST_NONCE_HEADER_NAME_KEY,
                 Constants.CSRF_REST_NONCE_HEADER_NAME);
     }
 
@@ -112,12 +110,12 @@ public class RestCsrfPreventionFilter extends CsrfPreventionFilterBase {
 
             RestCsrfPreventionStrategy strategy;
             switch (mType) {
-            case NON_MODIFYING_METHOD:
-                strategy = new FetchRequest();
-                break;
-            default:
-                strategy = new StateChangingRequest();
-                break;
+                case NON_MODIFYING_METHOD:
+                    strategy = new FetchRequest();
+                    break;
+                default:
+                    strategy = new StateChangingRequest();
+                    break;
             }
 
             if (!strategy.apply((HttpServletRequest) request, (HttpServletResponse) response)) {
@@ -130,8 +128,8 @@ public class RestCsrfPreventionFilter extends CsrfPreventionFilterBase {
     private static interface RestCsrfPreventionStrategy {
         static final NonceSupplier<HttpServletRequest, String> nonceFromRequestHeader = HttpServletRequest::getHeader;
         static final NonceSupplier<HttpServletRequest, String[]> nonceFromRequestParams = ServletRequest::getParameterValues;
-        static final NonceSupplier<HttpSession, String> nonceFromSession = (s, k) -> Objects
-                .isNull(s) ? null : (String) s.getAttribute(k);
+        static final NonceSupplier<HttpSession, String> nonceFromSession = (s, k) -> Objects.isNull(s) ? null
+                : (String) s.getAttribute(k);
 
         static final NonceConsumer<HttpServletResponse> nonceToResponse = HttpServletResponse::setHeader;
         static final NonceConsumer<HttpSession> nonceToSession = HttpSession::setAttribute;
@@ -142,8 +140,7 @@ public class RestCsrfPreventionFilter extends CsrfPreventionFilterBase {
     private class StateChangingRequest implements RestCsrfPreventionStrategy {
 
         @Override
-        public boolean apply(HttpServletRequest request, HttpServletResponse response)
-                throws IOException {
+        public boolean apply(HttpServletRequest request, HttpServletResponse response) throws IOException {
 
             String nonceRequest = extractNonceFromRequest(request);
             HttpSession session = request.getSession(false);
@@ -159,23 +156,21 @@ public class RestCsrfPreventionFilter extends CsrfPreventionFilterBase {
 
             if (getLogger().isDebugEnabled()) {
                 getLogger().debug(sm.getString("restCsrfPreventionFilter.invalidNonce.debug", request.getMethod(),
-                        request.getRequestURI(), Boolean.valueOf(request.getRequestedSessionId() != null),
-                        session, Boolean.valueOf(nonceRequest != null), Boolean.valueOf(nonceSession != null)));
+                        request.getRequestURI(), Boolean.valueOf(request.getRequestedSessionId() != null), session,
+                        Boolean.valueOf(nonceRequest != null), Boolean.valueOf(nonceSession != null)));
             }
             return false;
         }
 
         private boolean isValidStateChangingRequest(String reqNonce, String sessionNonce) {
-            return Objects.nonNull(reqNonce) && Objects.nonNull(sessionNonce)
-                    && Objects.equals(reqNonce, sessionNonce);
+            return Objects.nonNull(reqNonce) && Objects.nonNull(sessionNonce) && Objects.equals(reqNonce, sessionNonce);
         }
 
         private String extractNonceFromRequest(HttpServletRequest request) {
-            String nonceFromRequest = nonceFromRequestHeader.getNonce(request,
-                    Constants.CSRF_REST_NONCE_HEADER_NAME);
-            if ((Objects.isNull(nonceFromRequest) || Objects.equals("", nonceFromRequest))
-                    && !getPathsAcceptingParams().isEmpty()
-                    && getPathsAcceptingParams().contains(getRequestedPath(request))) {
+            String nonceFromRequest = nonceFromRequestHeader.getNonce(request, Constants.CSRF_REST_NONCE_HEADER_NAME);
+            if ((Objects.isNull(nonceFromRequest) || Objects.equals("", nonceFromRequest)) &&
+                    !getPathsAcceptingParams().isEmpty() &&
+                    getPathsAcceptingParams().contains(getRequestedPath(request))) {
                 nonceFromRequest = extractNonceFromRequestParams(request);
             }
             return nonceFromRequest;
@@ -205,8 +200,7 @@ public class RestCsrfPreventionFilter extends CsrfPreventionFilterBase {
 
         @Override
         public boolean apply(HttpServletRequest request, HttpServletResponse response) {
-            if (fetchRequest.test(
-                    nonceFromRequestHeader.getNonce(request, Constants.CSRF_REST_NONCE_HEADER_NAME))) {
+            if (fetchRequest.test(nonceFromRequestHeader.getNonce(request, Constants.CSRF_REST_NONCE_HEADER_NAME))) {
                 String nonceFromSessionStr = nonceFromSession.getNonce(request.getSession(false),
                         Constants.CSRF_REST_NONCE_SESSION_ATTR_NAME);
                 if (nonceFromSessionStr == null) {
@@ -214,11 +208,10 @@ public class RestCsrfPreventionFilter extends CsrfPreventionFilterBase {
                     nonceToSession.setNonce(Objects.requireNonNull(request.getSession(true)),
                             Constants.CSRF_REST_NONCE_SESSION_ATTR_NAME, nonceFromSessionStr);
                 }
-                nonceToResponse.setNonce(response, Constants.CSRF_REST_NONCE_HEADER_NAME,
-                        nonceFromSessionStr);
+                nonceToResponse.setNonce(response, Constants.CSRF_REST_NONCE_HEADER_NAME, nonceFromSessionStr);
                 if (getLogger().isDebugEnabled()) {
-                    getLogger().debug(sm.getString("restCsrfPreventionFilter.fetch.debug",
-                            request.getMethod(), request.getRequestURI()));
+                    getLogger().debug(sm.getString("restCsrfPreventionFilter.fetch.debug", request.getMethod(),
+                            request.getRequestURI()));
                 }
             }
             return true;
@@ -237,21 +230,17 @@ public class RestCsrfPreventionFilter extends CsrfPreventionFilterBase {
     }
 
     /**
-     * A comma separated list of URLs that can accept nonces via request
-     * parameter 'X-CSRF-Token'. For use cases when a nonce information cannot
-     * be provided via header, one can provide it via request parameters. If
-     * there is a X-CSRF-Token header, it will be taken with preference over any
-     * parameter with the same name in the request. Request parameters cannot be
-     * used to fetch new nonce, only header.
+     * A comma separated list of URLs that can accept nonces via request parameter 'X-CSRF-Token'. For use cases when a
+     * nonce information cannot be provided via header, one can provide it via request parameters. If there is a
+     * X-CSRF-Token header, it will be taken with preference over any parameter with the same name in the request.
+     * Request parameters cannot be used to fetch new nonce, only header.
      *
-     * @param pathsList
-     *            Comma separated list of URLs to be configured as paths
-     *            accepting request parameters with nonce information.
+     * @param pathsList Comma separated list of URLs to be configured as paths accepting request parameters with nonce
+     *                      information.
      */
     public void setPathsAcceptingParams(String pathsList) {
         if (Objects.nonNull(pathsList)) {
-            Arrays.asList(pathsList.split(pathsDelimiter)).forEach(
-                    e -> pathsAcceptingParams.add(e.trim()));
+            Arrays.asList(pathsList.split(pathsDelimiter)).forEach(e -> pathsAcceptingParams.add(e.trim()));
         }
     }
 
diff --git a/java/org/apache/catalina/filters/SessionInitializerFilter.java b/java/org/apache/catalina/filters/SessionInitializerFilter.java
index dafc28845f..55c80e0106 100644
--- a/java/org/apache/catalina/filters/SessionInitializerFilter.java
+++ b/java/org/apache/catalina/filters/SessionInitializerFilter.java
@@ -27,33 +27,30 @@ import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpSession;
 
 /**
- * A {@link javax.servlet.Filter} that initializes the {@link HttpSession} for
- * the {@link HttpServletRequest} by calling its getSession() method.
+ * A {@link javax.servlet.Filter} that initializes the {@link HttpSession} for the {@link HttpServletRequest} by calling
+ * its getSession() method.
  * <p>
- * This is required for some operations with WebSocket requests, where it is
- * too late to initialize the HttpSession object, and the current Java WebSocket
- * specification does not provide a way to do so.
+ * This is required for some operations with WebSocket requests, where it is too late to initialize the HttpSession
+ * object, and the current Java WebSocket specification does not provide a way to do so.
  */
 public class SessionInitializerFilter implements Filter {
 
     /**
-     * Calls {@link HttpServletRequest}'s getSession() to initialize the
-     * HttpSession and continues processing the chain.
+     * Calls {@link HttpServletRequest}'s getSession() to initialize the HttpSession and continues processing the chain.
      *
      * @param request  The request to process
      * @param response The response associated with the request
-     * @param chain    Provides access to the next filter in the chain for this
-     *                 filter to pass the request and response to for further
-     *                 processing
-     * @throws IOException      if an I/O error occurs during this filter's
-     *                          processing of the request
+     * @param chain    Provides access to the next filter in the chain for this filter to pass the request and response
+     *                     to for further processing
+     *
+     * @throws IOException      if an I/O error occurs during this filter's processing of the request
      * @throws ServletException if the processing fails for any other reason
      */
     @Override
     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
             throws IOException, ServletException {
 
-        ((HttpServletRequest)request).getSession();
+        ((HttpServletRequest) request).getSession();
 
         chain.doFilter(request, response);
     }
diff --git a/java/org/apache/catalina/filters/SetCharacterEncodingFilter.java b/java/org/apache/catalina/filters/SetCharacterEncodingFilter.java
index d1d9f1d98d..31dc9adbe6 100644
--- a/java/org/apache/catalina/filters/SetCharacterEncodingFilter.java
+++ b/java/org/apache/catalina/filters/SetCharacterEncodingFilter.java
@@ -28,29 +28,26 @@ import org.apache.juli.logging.LogFactory;
 
 
 /**
- * <p>Example filter that sets the character encoding to be used in parsing the
- * incoming request, either unconditionally or only if the client did not
- * specify a character encoding.  Configuration of this filter is based on
- * the following initialization parameters:</p>
+ * <p>
+ * Example filter that sets the character encoding to be used in parsing the incoming request, either unconditionally or
+ * only if the client did not specify a character encoding. Configuration of this filter is based on the following
+ * initialization parameters:
+ * </p>
  * <ul>
- * <li><strong>encoding</strong> - The character encoding to be configured
- *     for this request, either conditionally or unconditionally based on
- *     the <code>ignore</code> initialization parameter.  This parameter
- *     is required, so there is no default.</li>
- * <li><strong>ignore</strong> - If set to "true", any character encoding
- *     specified by the client is ignored, and the value returned by the
- *     <code>selectEncoding()</code> method is set.  If set to "false,
- *     <code>selectEncoding()</code> is called <strong>only</strong> if the
- *     client has not already specified an encoding.  By default, this
- *     parameter is set to "false".</li>
+ * <li><strong>encoding</strong> - The character encoding to be configured for this request, either conditionally or
+ * unconditionally based on the <code>ignore</code> initialization parameter. This parameter is required, so there is no
+ * default.</li>
+ * <li><strong>ignore</strong> - If set to "true", any character encoding specified by the client is ignored, and the
+ * value returned by the <code>selectEncoding()</code> method is set. If set to "false, <code>selectEncoding()</code> is
+ * called <strong>only</strong> if the client has not already specified an encoding. By default, this parameter is set
+ * to "false".</li>
  * </ul>
- *
- * <p>Although this filter can be used unchanged, it is also easy to
- * subclass it and make the <code>selectEncoding()</code> method more
- * intelligent about what encoding to choose, based on characteristics of
- * the incoming request (such as the values of the <code>Accept-Language</code>
- * and <code>User-Agent</code> headers, or a value stashed in the current
- * user's session.</p>
+ * <p>
+ * Although this filter can be used unchanged, it is also easy to subclass it and make the <code>selectEncoding()</code>
+ * method more intelligent about what encoding to choose, based on characteristics of the incoming request (such as the
+ * values of the <code>Accept-Language</code> and <code>User-Agent</code> headers, or a value stashed in the current
+ * user's session.
+ * </p>
  */
 public class SetCharacterEncodingFilter extends FilterBase {
 
@@ -62,40 +59,49 @@ public class SetCharacterEncodingFilter extends FilterBase {
     // ----------------------------------------------------- Instance Variables
 
     /**
-     * The default character encoding to set for requests that pass through
-     * this filter.
+     * The default character encoding to set for requests that pass through this filter.
      */
     private String encoding = null;
-    public void setEncoding(String encoding) { this.encoding = encoding; }
-    public String getEncoding() { return encoding; }
+
+    public void setEncoding(String encoding) {
+        this.encoding = encoding;
+    }
+
+    public String getEncoding() {
+        return encoding;
+    }
 
 
     /**
      * Should a character encoding specified by the client be ignored?
      */
     private boolean ignore = false;
-    public void setIgnore(boolean ignore) { this.ignore = ignore; }
-    public boolean isIgnore() { return ignore; }
+
+    public void setIgnore(boolean ignore) {
+        this.ignore = ignore;
+    }
+
+    public boolean isIgnore() {
+        return ignore;
+    }
 
 
     // --------------------------------------------------------- Public Methods
 
 
     /**
-     * Select and set (if specified) the character encoding to be used to
-     * interpret request parameters for this request.
+     * Select and set (if specified) the character encoding to be used to interpret request parameters for this request.
      *
-     * @param request The servlet request we are processing
+     * @param request  The servlet request we are processing
      * @param response The servlet response we are creating
-     * @param chain The filter chain we are processing
+     * @param chain    The filter chain we are processing
      *
-     * @exception IOException if an input/output error occurs
+     * @exception IOException      if an input/output error occurs
      * @exception ServletException if a servlet error occurs
      */
     @Override
-    public void doFilter(ServletRequest request, ServletResponse response,
-                         FilterChain chain)
-        throws IOException, ServletException {
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+            throws IOException, ServletException {
 
         // Conditionally select and set the character encoding to be used
         if (ignore || (request.getCharacterEncoding() == null)) {
@@ -119,16 +125,14 @@ public class SetCharacterEncodingFilter extends FilterBase {
 
 
     /**
-     * Select an appropriate character encoding to be used, based on the
-     * characteristics of the current request and/or filter initialization
-     * parameters.  If no character encoding should be set, return
-     * <code>null</code>.
+     * Select an appropriate character encoding to be used, based on the characteristics of the current request and/or
+     * filter initialization parameters. If no character encoding should be set, return <code>null</code>.
      * <p>
-     * The default implementation unconditionally returns the value configured
-     * by the <strong>encoding</strong> initialization parameter for this
-     * filter.
+     * The default implementation unconditionally returns the value configured by the <strong>encoding</strong>
+     * initialization parameter for this filter.
      *
      * @param request The servlet request we are processing
+     *
      * @return the encoding that was configured
      */
     protected String selectEncoding(ServletRequest request) {
diff --git a/java/org/apache/catalina/filters/WebdavFixFilter.java b/java/org/apache/catalina/filters/WebdavFixFilter.java
index 3909f61cfc..1d1b555a58 100644
--- a/java/org/apache/catalina/filters/WebdavFixFilter.java
+++ b/java/org/apache/catalina/filters/WebdavFixFilter.java
@@ -29,33 +29,27 @@ import javax.servlet.http.HttpServletResponse;
 import org.apache.tomcat.util.res.StringManager;
 
 /**
- * Filter that attempts to force MS WebDAV clients connecting on port 80 to use
- * a WebDAV client that actually works. Other workarounds that might help
- * include:
+ * Filter that attempts to force MS WebDAV clients connecting on port 80 to use a WebDAV client that actually works.
+ * Other workarounds that might help include:
  * <ul>
- *   <li>Specifying the port, even if it is port 80, when trying to
- *       connect.</li>
- *   <li>Cancelling the first authentication dialog box and then trying to
- *       reconnect.</li>
+ * <li>Specifying the port, even if it is port 80, when trying to connect.</li>
+ * <li>Cancelling the first authentication dialog box and then trying to reconnect.</li>
  * </ul>
- *
- * Generally each different version of the MS client has a different set of
- * problems.
+ * Generally each different version of the MS client has a different set of problems.
  * <p>
- * TODO: Update this filter to recognise specific MS clients and apply the
- *       appropriate workarounds for that particular client
+ * TODO: Update this filter to recognise specific MS clients and apply the appropriate workarounds for that particular
+ * client
  * <p>
- * As a filter, this is configured in web.xml like any other Filter. You usually
- * want to map this filter to whatever your WebDAV servlet is mapped to.
+ * As a filter, this is configured in web.xml like any other Filter. You usually want to map this filter to whatever
+ * your WebDAV servlet is mapped to.
  * <p>
- * In addition to the issues fixed by this Filter, the following issues have
- * also been observed that cannot be fixed by this filter. Where possible the
- * filter will add an message to the logs.
+ * In addition to the issues fixed by this Filter, the following issues have also been observed that cannot be fixed by
+ * this filter. Where possible the filter will add an message to the logs.
  * <p>
  * XP x64 SP2 (MiniRedir Version 3790)
  * <ul>
- *   <li>Only connects to port 80</li>
- *   <li>Unknown issue means it doesn't work</li>
+ * <li>Only connects to port 80</li>
+ * <li>Unknown issue means it doesn't work</li>
  * </ul>
  */
 public class WebdavFixFilter extends GenericFilter {
@@ -64,25 +58,21 @@ public class WebdavFixFilter extends GenericFilter {
     protected static final StringManager sm = StringManager.getManager(WebdavFixFilter.class);
 
     /* Start string for all versions */
-    private static final String UA_MINIDIR_START =
-        "Microsoft-WebDAV-MiniRedir";
+    private static final String UA_MINIDIR_START = "Microsoft-WebDAV-MiniRedir";
     /* XP 32-bit SP3 */
-    private static final String UA_MINIDIR_5_1_2600 =
-        "Microsoft-WebDAV-MiniRedir/5.1.2600";
+    private static final String UA_MINIDIR_5_1_2600 = "Microsoft-WebDAV-MiniRedir/5.1.2600";
 
     /* XP 64-bit SP2 */
-    private static final String UA_MINIDIR_5_2_3790 =
-        "Microsoft-WebDAV-MiniRedir/5.2.3790";
+    private static final String UA_MINIDIR_5_2_3790 = "Microsoft-WebDAV-MiniRedir/5.2.3790";
 
     /**
-     * Check for the broken MS WebDAV client and if detected issue a re-direct
-     * that hopefully will cause the non-broken client to be used.
+     * Check for the broken MS WebDAV client and if detected issue a re-direct that hopefully will cause the non-broken
+     * client to be used.
      */
     @Override
-    public void doFilter(ServletRequest request, ServletResponse response,
-            FilterChain chain) throws IOException, ServletException {
-        if (!(request instanceof HttpServletRequest) ||
-                !(response instanceof HttpServletResponse)) {
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+            throws IOException, ServletException {
+        if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
             chain.doFilter(request, response);
             return;
         }
@@ -90,8 +80,7 @@ public class WebdavFixFilter extends GenericFilter {
         HttpServletResponse httpResponse = ((HttpServletResponse) response);
         String ua = httpRequest.getHeader("User-Agent");
 
-        if (ua == null || ua.length() == 0 ||
-                !ua.startsWith(UA_MINIDIR_START)) {
+        if (ua == null || ua.length() == 0 || !ua.startsWith(UA_MINIDIR_START)) {
             // No UA or starts with non MS value
             // Hope everything just works...
             chain.doFilter(request, response);
@@ -117,8 +106,7 @@ public class WebdavFixFilter extends GenericFilter {
     }
 
     private String buildRedirect(HttpServletRequest request) {
-        StringBuilder location =
-            new StringBuilder(request.getRequestURL().length());
+        StringBuilder location = new StringBuilder(request.getRequestURL().length());
         location.append(request.getScheme());
         location.append("://");
         location.append(request.getServerName());


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


[tomcat] 06/07: Code cleanup (format). No functional change.

Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 2d6f8fc2c090dab230bbdba505ccd4436049f904
Author: Mark Thomas <ma...@apache.org>
AuthorDate: Tue Jan 24 11:15:23 2023 +0000

    Code cleanup (format). No functional change.
---
 java/org/apache/tomcat/util/res/StringManager.java | 121 +++++++++------------
 1 file changed, 50 insertions(+), 71 deletions(-)

diff --git a/java/org/apache/tomcat/util/res/StringManager.java b/java/org/apache/tomcat/util/res/StringManager.java
index 91b39b48d7..094c93727a 100644
--- a/java/org/apache/tomcat/util/res/StringManager.java
+++ b/java/org/apache/tomcat/util/res/StringManager.java
@@ -26,27 +26,22 @@ import java.util.MissingResourceException;
 import java.util.ResourceBundle;
 
 /**
- * An internationalization / localization helper class which reduces
- * the bother of handling ResourceBundles and takes care of the
- * common cases of message formatting which otherwise require the
- * creation of Object arrays and such.
- *
- * <p>The StringManager operates on a package basis. One StringManager
- * per package can be created and accessed via the getManager method
- * call.
- *
- * <p>The StringManager will look for a ResourceBundle named by
- * the package name given plus the suffix of "LocalStrings". In
- * practice, this means that the localized information will be contained
- * in a LocalStrings.properties file located in the package
- * directory of the class path.
- *
- * <p>Please see the documentation for java.util.ResourceBundle for
- * more information.
+ * An internationalization / localization helper class which reduces the bother of handling ResourceBundles and takes
+ * care of the common cases of message formatting which otherwise require the creation of Object arrays and such.
+ * <p>
+ * The StringManager operates on a package basis. One StringManager per package can be created and accessed via the
+ * getManager method call.
+ * <p>
+ * The StringManager will look for a ResourceBundle named by the package name given plus the suffix of "LocalStrings".
+ * In practice, this means that the localized information will be contained in a LocalStrings.properties file located in
+ * the package directory of the class path.
+ * <p>
+ * Please see the documentation for java.util.ResourceBundle for more information.
  *
  * @author James Duncan Davidson [duncan@eng.sun.com]
  * @author James Todd [gonzo@eng.sun.com]
  * @author Mel Martinez [mmartinez@g1440.com]
+ *
  * @see java.util.ResourceBundle
  */
 public class StringManager {
@@ -61,10 +56,8 @@ public class StringManager {
 
 
     /**
-     * Creates a new StringManager for a given package. This is a
-     * private method and all access to it is arbitrated by the
-     * static getManager method call so that only one StringManager
-     * per package will be created.
+     * Creates a new StringManager for a given package. This is a private method and all access to it is arbitrated by
+     * the static getManager method call so that only one StringManager per package will be created.
      *
      * @param packageName Name of package to create StringManager for.
      */
@@ -109,18 +102,16 @@ public class StringManager {
 
 
     /**
-     * Get a string from the underlying resource bundle or return null if the
-     * String is not found.
+     * Get a string from the underlying resource bundle or return null if the String is not found.
      *
      * @param key to desired resource String
      *
-     * @return resource String matching <i>key</i> from underlying bundle or
-     *         null if not found.
+     * @return resource String matching <i>key</i> from underlying bundle or null if not found.
      *
      * @throws IllegalArgumentException if <i>key</i> is null
      */
     public String getString(String key) {
-        if (key == null){
+        if (key == null) {
             String msg = "key may not have a null value";
             throw new IllegalArgumentException(msg);
         }
@@ -133,17 +124,17 @@ public class StringManager {
                 str = bundle.getString(key);
             }
         } catch (MissingResourceException mre) {
-            //bad: shouldn't mask an exception the following way:
-            //   str = "[cannot find message associated with key '" + key +
-            //         "' due to " + mre + "]";
-            //     because it hides the fact that the String was missing
-            //     from the calling code.
-            //good: could just throw the exception (or wrap it in another)
-            //      but that would probably cause much havoc on existing
-            //      code.
-            //better: consistent with container pattern to
-            //      simply return null.  Calling code can then do
-            //      a null check.
+            // bad: shouldn't mask an exception the following way:
+            // str = "[cannot find message associated with key '" + key +
+            // "' due to " + mre + "]";
+            // because it hides the fact that the String was missing
+            // from the calling code.
+            // good: could just throw the exception (or wrap it in another)
+            // but that would probably cause much havoc on existing
+            // code.
+            // better: consistent with container pattern to
+            // simply return null. Calling code can then do
+            // a null check.
             str = null;
         }
 
@@ -152,14 +143,12 @@ public class StringManager {
 
 
     /**
-     * Get a string from the underlying resource bundle and format
-     * it with the given set of arguments.
+     * Get a string from the underlying resource bundle and format it with the given set of arguments.
      *
      * @param key  The key for the required message
      * @param args The values to insert into the message
      *
-     * @return The request string formatted with the provided arguments or the
-     *         key if the key was not found.
+     * @return The request string formatted with the provided arguments or the key if the key was not found.
      */
     public String getString(final String key, final Object... args) {
         String value = getString(key);
@@ -187,14 +176,13 @@ public class StringManager {
     // STATIC SUPPORT METHODS
     // --------------------------------------------------------------
 
-    private static final Map<String, Map<Locale,StringManager>> managers = new HashMap<>();
+    private static final Map<String, Map<Locale, StringManager>> managers = new HashMap<>();
 
 
     /**
-     * Get the StringManager for a given class. The StringManager will be
-     * returned for the package in which the class is located. If a manager for
-     * that package already exists, it will be reused, else a new
-     * StringManager will be created and returned.
+     * Get the StringManager for a given class. The StringManager will be returned for the package in which the class is
+     * located. If a manager for that package already exists, it will be reused, else a new StringManager will be
+     * created and returned.
      *
      * @param clazz The class for which to retrieve the StringManager
      *
@@ -206,14 +194,12 @@ public class StringManager {
 
 
     /**
-     * Get the StringManager for a particular package. If a manager for
-     * a package already exists, it will be reused, else a new
-     * StringManager will be created and returned.
+     * Get the StringManager for a particular package. If a manager for a package already exists, it will be reused,
+     * else a new StringManager will be created and returned.
      *
      * @param packageName The package name
      *
-     * @return The instance associated with the given package and the default
-     *         Locale
+     * @return The instance associated with the given package and the default Locale
      */
     public static final StringManager getManager(String packageName) {
         return getManager(packageName, Locale.getDefault());
@@ -221,33 +207,29 @@ public class StringManager {
 
 
     /**
-     * Get the StringManager for a particular package and Locale. If a manager
-     * for a package/Locale combination already exists, it will be reused, else
-     * a new StringManager will be created and returned.
+     * Get the StringManager for a particular package and Locale. If a manager for a package/Locale combination already
+     * exists, it will be reused, else a new StringManager will be created and returned.
      *
      * @param packageName The package name
      * @param locale      The Locale
      *
      * @return The instance associated with the given package and Locale
      */
-    public static final synchronized StringManager getManager(
-            String packageName, Locale locale) {
+    public static final synchronized StringManager getManager(String packageName, Locale locale) {
 
-        Map<Locale,StringManager> map = managers.get(packageName);
+        Map<Locale, StringManager> map = managers.get(packageName);
         if (map == null) {
             /*
-             * Don't want the HashMap to be expanded beyond LOCALE_CACHE_SIZE.
-             * Expansion occurs when size() exceeds capacity. Therefore keep
-             * size at or below capacity.
-             * removeEldestEntry() executes after insertion therefore the test
-             * for removal needs to use one less than the maximum desired size
+             * Don't want the HashMap to be expanded beyond LOCALE_CACHE_SIZE. Expansion occurs when size() exceeds
+             * capacity. Therefore keep size at or below capacity. removeEldestEntry() executes after insertion
+             * therefore the test for removal needs to use one less than the maximum desired size
              *
              */
-            map = new LinkedHashMap<Locale,StringManager>(LOCALE_CACHE_SIZE, 1, true) {
+            map = new LinkedHashMap<Locale, StringManager>(LOCALE_CACHE_SIZE, 1, true) {
                 private static final long serialVersionUID = 1L;
+
                 @Override
-                protected boolean removeEldestEntry(
-                        Map.Entry<Locale,StringManager> eldest) {
+                protected boolean removeEldestEntry(Map.Entry<Locale, StringManager> eldest) {
                     if (size() > (LOCALE_CACHE_SIZE - 1)) {
                         return true;
                     }
@@ -267,17 +249,14 @@ public class StringManager {
 
 
     /**
-     * Retrieve the StringManager for a list of Locales. The first StringManager
-     * found will be returned.
+     * Retrieve the StringManager for a list of Locales. The first StringManager found will be returned.
      *
-     * @param packageName      The package for which the StringManager was
-     *                         requested
+     * @param packageName      The package for which the StringManager was requested
      * @param requestedLocales The list of Locales
      *
      * @return the found StringManager or the default StringManager
      */
-    public static StringManager getManager(String packageName,
-            Enumeration<Locale> requestedLocales) {
+    public static StringManager getManager(String packageName, Enumeration<Locale> requestedLocales) {
         while (requestedLocales.hasMoreElements()) {
             Locale locale = requestedLocales.nextElement();
             StringManager result = getManager(packageName, locale);


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


[tomcat] 04/07: Code cleanup (format). No functional change.

Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 74c9ebf14f5af2e5a5f202a2f0fd08f30e7479ea
Author: Mark Thomas <ma...@apache.org>
AuthorDate: Tue Jan 24 11:14:51 2023 +0000

    Code cleanup (format). No functional change.
---
 java/org/apache/catalina/tribes/util/Arrays.java   |  54 +++++-----
 .../catalina/tribes/util/ExceptionUtils.java       |   4 +-
 .../catalina/tribes/util/ExecutorFactory.java      |  43 ++++----
 java/org/apache/catalina/tribes/util/Logs.java     |   1 +
 .../apache/catalina/tribes/util/StringManager.java | 110 +++++++++------------
 .../catalina/tribes/util/TcclThreadFactory.java    |  11 +--
 .../apache/catalina/tribes/util/UUIDGenerator.java |  35 ++++---
 7 files changed, 122 insertions(+), 136 deletions(-)

diff --git a/java/org/apache/catalina/tribes/util/Arrays.java b/java/org/apache/catalina/tribes/util/Arrays.java
index dfe79bd481..9998f6e5d4 100644
--- a/java/org/apache/catalina/tribes/util/Arrays.java
+++ b/java/org/apache/catalina/tribes/util/Arrays.java
@@ -31,38 +31,38 @@ public class Arrays {
     protected static final StringManager sm = StringManager.getManager(Arrays.class);
 
     public static boolean contains(byte[] source, int srcoffset, byte[] key, int keyoffset, int length) {
-        if ( srcoffset < 0 || srcoffset >= source.length) {
+        if (srcoffset < 0 || srcoffset >= source.length) {
             throw new ArrayIndexOutOfBoundsException(sm.getString("arrays.srcoffset.outOfBounds"));
         }
-        if ( keyoffset < 0 || keyoffset >= key.length) {
+        if (keyoffset < 0 || keyoffset >= key.length) {
             throw new ArrayIndexOutOfBoundsException(sm.getString("arrays.keyoffset.outOfBounds"));
         }
-        if ( length > (key.length-keyoffset) ) {
+        if (length > (key.length - keyoffset)) {
             throw new ArrayIndexOutOfBoundsException(sm.getString("arrays.length.outOfBounds"));
         }
-        //we don't have enough data to validate it
-        if ( length > (source.length-srcoffset) ) {
+        // we don't have enough data to validate it
+        if (length > (source.length - srcoffset)) {
             return false;
         }
         boolean match = true;
         int pos = keyoffset;
-        for ( int i=srcoffset; match && i<length; i++ ) {
+        for (int i = srcoffset; match && i < length; i++) {
             match = (source[i] == key[pos++]);
         }
         return match;
     }
 
     public static String toString(byte[] data) {
-        return toString(data,0,data!=null?data.length:0);
+        return toString(data, 0, data != null ? data.length : 0);
     }
 
     public static String toString(byte[] data, int offset, int length) {
-        return toString(data,offset,length,false);
+        return toString(data, offset, length, false);
     }
 
     public static String toString(byte[] data, int offset, int length, boolean unsigned) {
         StringBuilder buf = new StringBuilder("{");
-        if ( data != null && length > 0 ) {
+        if (data != null && length > 0) {
             int i = offset;
             if (unsigned) {
                 buf.append(data[i++] & 0xff);
@@ -81,12 +81,12 @@ public class Arrays {
     }
 
     public static String toString(Object[] data) {
-        return toString(data,0,data!=null?data.length:0);
+        return toString(data, 0, data != null ? data.length : 0);
     }
 
     public static String toString(Object[] data, int offset, int length) {
         StringBuilder buf = new StringBuilder("{");
-        if ( data != null && length > 0 ) {
+        if (data != null && length > 0) {
             buf.append(data[offset++]);
             for (int i = offset; i < length; i++) {
                 buf.append(", ").append(data[i]);
@@ -97,12 +97,12 @@ public class Arrays {
     }
 
     public static String toNameString(Member[] data) {
-        return toNameString(data,0,data!=null?data.length:0);
+        return toNameString(data, 0, data != null ? data.length : 0);
     }
 
     public static String toNameString(Member[] data, int offset, int length) {
         StringBuilder buf = new StringBuilder("{");
-        if ( data != null && length > 0 ) {
+        if (data != null && length > 0) {
             buf.append(data[offset++].getName());
             for (int i = offset; i < length; i++) {
                 buf.append(", ").append(data[i].getName());
@@ -129,13 +129,13 @@ public class Arrays {
     }
 
     public static boolean equals(byte[] o1, byte[] o2) {
-        return java.util.Arrays.equals(o1,o2);
+        return java.util.Arrays.equals(o1, o2);
     }
 
     public static boolean equals(Object[] o1, Object[] o2) {
         boolean result = o1.length == o2.length;
-        if ( result ) {
-            for (int i=0; i<o1.length && result; i++ ) {
+        if (result) {
+            for (int i = 0; i < o1.length && result; i++) {
                 result = o1[i].equals(o2[i]);
             }
         }
@@ -145,7 +145,7 @@ public class Arrays {
     public static boolean sameMembers(Member[] m1, Member[] m2) {
         AbsoluteOrder.absoluteOrder(m1);
         AbsoluteOrder.absoluteOrder(m2);
-        return equals(m1,m2);
+        return equals(m1, m2);
     }
 
     public static Member[] merge(Member[] m1, Member[] m2) {
@@ -183,7 +183,7 @@ public class Arrays {
     }
 
     public static Member[] remove(Member[] all, Member remove) {
-        return extract(all,new Member[] {remove});
+        return extract(all, new Member[] { remove });
     }
 
     public static Member[] extract(Member[] all, Member[] remove) {
@@ -197,8 +197,8 @@ public class Arrays {
 
     public static int indexOf(Member member, Member[] members) {
         int result = -1;
-        for (int i=0; (result==-1) && (i<members.length); i++ ) {
-            if ( member.equals(members[i]) ) {
+        for (int i = 0; (result == -1) && (i < members.length); i++) {
+            if (member.equals(members[i])) {
                 result = i;
             }
         }
@@ -206,9 +206,9 @@ public class Arrays {
     }
 
     public static int nextIndex(Member member, Member[] members) {
-        int idx = indexOf(member,members)+1;
-        if (idx >= members.length ) {
-            idx = ((members.length>0)?0:-1);
+        int idx = indexOf(member, members) + 1;
+        if (idx >= members.length) {
+            idx = ((members.length > 0) ? 0 : -1);
         }
 
         return idx;
@@ -227,15 +227,15 @@ public class Arrays {
     }
 
     public static byte[] fromString(String value) {
-        if ( value == null ) {
+        if (value == null) {
             return null;
         }
-        if ( !value.startsWith("{") ) {
+        if (!value.startsWith("{")) {
             throw new RuntimeException(sm.getString("arrays.malformed.arrays"));
         }
-        StringTokenizer t = new StringTokenizer(value,"{,}",false);
+        StringTokenizer t = new StringTokenizer(value, "{,}", false);
         byte[] result = new byte[t.countTokens()];
-        for (int i=0; i<result.length; i++ ) {
+        for (int i = 0; i < result.length; i++) {
             result[i] = Byte.parseByte(t.nextToken());
         }
         return result;
diff --git a/java/org/apache/catalina/tribes/util/ExceptionUtils.java b/java/org/apache/catalina/tribes/util/ExceptionUtils.java
index 9c74a15e6d..c352e3c39f 100644
--- a/java/org/apache/catalina/tribes/util/ExceptionUtils.java
+++ b/java/org/apache/catalina/tribes/util/ExceptionUtils.java
@@ -22,8 +22,8 @@ package org.apache.catalina.tribes.util;
 public class ExceptionUtils {
 
     /**
-     * Checks whether the supplied Throwable is one that needs to be
-     * rethrown and swallows all others.
+     * Checks whether the supplied Throwable is one that needs to be rethrown and swallows all others.
+     *
      * @param t the Throwable to check
      */
     public static void handleThrowable(Throwable t) {
diff --git a/java/org/apache/catalina/tribes/util/ExecutorFactory.java b/java/org/apache/catalina/tribes/util/ExecutorFactory.java
index b0d1e597fa..f14fd9dd1a 100644
--- a/java/org/apache/catalina/tribes/util/ExecutorFactory.java
+++ b/java/org/apache/catalina/tribes/util/ExecutorFactory.java
@@ -30,37 +30,42 @@ public class ExecutorFactory {
 
     public static ExecutorService newThreadPool(int minThreads, int maxThreads, long maxIdleTime, TimeUnit unit) {
         TaskQueue taskqueue = new TaskQueue();
-        ThreadPoolExecutor service = new TribesThreadPoolExecutor(minThreads, maxThreads, maxIdleTime, unit,taskqueue);
+        ThreadPoolExecutor service = new TribesThreadPoolExecutor(minThreads, maxThreads, maxIdleTime, unit, taskqueue);
         taskqueue.setParent(service);
         return service;
     }
 
-    public static ExecutorService newThreadPool(int minThreads, int maxThreads, long maxIdleTime, TimeUnit unit, ThreadFactory threadFactory) {
+    public static ExecutorService newThreadPool(int minThreads, int maxThreads, long maxIdleTime, TimeUnit unit,
+            ThreadFactory threadFactory) {
         TaskQueue taskqueue = new TaskQueue();
-        ThreadPoolExecutor service = new TribesThreadPoolExecutor(minThreads, maxThreads, maxIdleTime, unit,taskqueue, threadFactory);
+        ThreadPoolExecutor service = new TribesThreadPoolExecutor(minThreads, maxThreads, maxIdleTime, unit, taskqueue,
+                threadFactory);
         taskqueue.setParent(service);
         return service;
     }
 
     // ---------------------------------------------- TribesThreadPoolExecutor Inner Class
     private static class TribesThreadPoolExecutor extends ThreadPoolExecutor {
-        public TribesThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
+        public TribesThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
+                BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
             super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
             prestartAllCoreThreads();
         }
 
-        public TribesThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
-                RejectedExecutionHandler handler) {
+        public TribesThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
+                BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
             super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
             prestartAllCoreThreads();
         }
 
-        public TribesThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
+        public TribesThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
+                BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
             super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
             prestartAllCoreThreads();
         }
 
-        public TribesThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
+        public TribesThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
+                BlockingQueue<Runnable> workQueue) {
             super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
             prestartAllCoreThreads();
         }
@@ -71,7 +76,7 @@ public class ExecutorFactory {
                 super.execute(command);
             } catch (RejectedExecutionException rx) {
                 if (super.getQueue() instanceof TaskQueue) {
-                    TaskQueue queue = (TaskQueue)super.getQueue();
+                    TaskQueue queue = (TaskQueue) super.getQueue();
                     if (!queue.force(command)) {
                         throw new RejectedExecutionException(sm.getString("executorFactory.queue.full"));
                     }
@@ -80,7 +85,7 @@ public class ExecutorFactory {
         }
     }
 
-     // ---------------------------------------------- TaskQueue Inner Class
+    // ---------------------------------------------- TaskQueue Inner Class
     private static class TaskQueue extends LinkedBlockingQueue<Runnable> {
         private static final long serialVersionUID = 1L;
 
@@ -104,24 +109,24 @@ public class ExecutorFactory {
 
         @Override
         public boolean offer(Runnable o) {
-            //we can't do any checks
-            if (parent==null) {
+            // we can't do any checks
+            if (parent == null) {
                 return super.offer(o);
             }
-            //we are maxed out on threads, simply queue the object
+            // we are maxed out on threads, simply queue the object
             if (parent.getPoolSize() == parent.getMaximumPoolSize()) {
                 return super.offer(o);
             }
-            //we have idle threads, just add it to the queue
-            //this is an approximation, so it could use some tuning
-            if (parent.getActiveCount()<(parent.getPoolSize())) {
+            // we have idle threads, just add it to the queue
+            // this is an approximation, so it could use some tuning
+            if (parent.getActiveCount() < (parent.getPoolSize())) {
                 return super.offer(o);
             }
-            //if we have less threads than maximum force creation of a new thread
-            if (parent.getPoolSize()<parent.getMaximumPoolSize()) {
+            // if we have less threads than maximum force creation of a new thread
+            if (parent.getPoolSize() < parent.getMaximumPoolSize()) {
                 return false;
             }
-            //if we reached here, we need to add it to the queue
+            // if we reached here, we need to add it to the queue
             return super.offer(o);
         }
     }
diff --git a/java/org/apache/catalina/tribes/util/Logs.java b/java/org/apache/catalina/tribes/util/Logs.java
index 112e8cf8f5..1c1933b93b 100644
--- a/java/org/apache/catalina/tribes/util/Logs.java
+++ b/java/org/apache/catalina/tribes/util/Logs.java
@@ -18,6 +18,7 @@ package org.apache.catalina.tribes.util;
 
 import org.apache.juli.logging.Log;
 import org.apache.juli.logging.LogFactory;
+
 /**
  * Simple class that holds references to global loggers
  */
diff --git a/java/org/apache/catalina/tribes/util/StringManager.java b/java/org/apache/catalina/tribes/util/StringManager.java
index ed689fdb8c..fc4b8b5b21 100644
--- a/java/org/apache/catalina/tribes/util/StringManager.java
+++ b/java/org/apache/catalina/tribes/util/StringManager.java
@@ -27,27 +27,22 @@ import java.util.ResourceBundle;
 
 
 /**
- * An internationalization / localization helper class which reduces
- * the bother of handling ResourceBundles and takes care of the
- * common cases of message formatting which otherwise require the
- * creation of Object arrays and such.
- *
- * <p>The StringManager operates on a package basis. One StringManager
- * per package can be created and accessed via the getManager method
- * call.
- *
- * <p>The StringManager will look for a ResourceBundle named by
- * the package name given plus the suffix of "LocalStrings". In
- * practice, this means that the localized information will be contained
- * in a LocalStrings.properties file located in the package
- * directory of the classpath.
- *
- * <p>Please see the documentation for java.util.ResourceBundle for
- * more information.
+ * An internationalization / localization helper class which reduces the bother of handling ResourceBundles and takes
+ * care of the common cases of message formatting which otherwise require the creation of Object arrays and such.
+ * <p>
+ * The StringManager operates on a package basis. One StringManager per package can be created and accessed via the
+ * getManager method call.
+ * <p>
+ * The StringManager will look for a ResourceBundle named by the package name given plus the suffix of "LocalStrings".
+ * In practice, this means that the localized information will be contained in a LocalStrings.properties file located in
+ * the package directory of the classpath.
+ * <p>
+ * Please see the documentation for java.util.ResourceBundle for more information.
  *
  * @author James Duncan Davidson [duncan@eng.sun.com]
  * @author James Todd [gonzo@eng.sun.com]
  * @author Mel Martinez [mmartinez@g1440.com]
+ *
  * @see java.util.ResourceBundle
  */
 public class StringManager {
@@ -62,10 +57,8 @@ public class StringManager {
 
 
     /**
-     * Creates a new StringManager for a given package. This is a
-     * private method and all access to it is arbitrated by the
-     * static getManager method call so that only one StringManager
-     * per package will be created.
+     * Creates a new StringManager for a given package. This is a private method and all access to it is arbitrated by
+     * the static getManager method call so that only one StringManager per package will be created.
      *
      * @param packageName Name of package to create StringManager for.
      */
@@ -103,18 +96,16 @@ public class StringManager {
 
 
     /**
-     * Get a string from the underlying resource bundle or return null if the
-     * String is not found.
+     * Get a string from the underlying resource bundle or return null if the String is not found.
      *
      * @param key to desired resource String
      *
-     * @return resource String matching <i>key</i> from underlying bundle or
-     *         null if not found.
+     * @return resource String matching <i>key</i> from underlying bundle or null if not found.
      *
      * @throws IllegalArgumentException if <i>key</i> is null
      */
     public String getString(String key) {
-        if (key == null){
+        if (key == null) {
             String msg = "key may not have a null value";
             throw new IllegalArgumentException(msg);
         }
@@ -127,17 +118,17 @@ public class StringManager {
                 str = bundle.getString(key);
             }
         } catch (MissingResourceException mre) {
-            //bad: shouldn't mask an exception the following way:
-            //   str = "[cannot find message associated with key '" + key +
-            //         "' due to " + mre + "]";
-            //     because it hides the fact that the String was missing
-            //     from the calling code.
-            //good: could just throw the exception (or wrap it in another)
-            //      but that would probably cause much havoc on existing
-            //      code.
-            //better: consistent with container pattern to
-            //      simply return null.  Calling code can then do
-            //      a null check.
+            // bad: shouldn't mask an exception the following way:
+            // str = "[cannot find message associated with key '" + key +
+            // "' due to " + mre + "]";
+            // because it hides the fact that the String was missing
+            // from the calling code.
+            // good: could just throw the exception (or wrap it in another)
+            // but that would probably cause much havoc on existing
+            // code.
+            // better: consistent with container pattern to
+            // simply return null. Calling code can then do
+            // a null check.
             str = null;
         }
 
@@ -146,8 +137,7 @@ public class StringManager {
 
 
     /**
-     * Get a string from the underlying resource bundle and format
-     * it with the given set of arguments.
+     * Get a string from the underlying resource bundle and format it with the given set of arguments.
      *
      * @param key  The key for the required message
      * @param args The values to insert into the message
@@ -180,13 +170,12 @@ public class StringManager {
     // STATIC SUPPORT METHODS
     // --------------------------------------------------------------
 
-    private static final Map<String, Map<Locale,StringManager>> managers = new HashMap<>();
+    private static final Map<String, Map<Locale, StringManager>> managers = new HashMap<>();
 
 
     /**
-     * The StringManager will be returned for the package in which the class is
-     * located. If a manager for that package already exists, it will be reused,
-     * else a new StringManager will be created and returned.
+     * The StringManager will be returned for the package in which the class is located. If a manager for that package
+     * already exists, it will be reused, else a new StringManager will be created and returned.
      *
      * @param clazz The class for which to retrieve the StringManager
      *
@@ -198,8 +187,8 @@ public class StringManager {
 
 
     /**
-     * If a manager for a package already exists, it will be reused, else a new
-     * StringManager will be created and returned.
+     * If a manager for a package already exists, it will be reused, else a new StringManager will be created and
+     * returned.
      *
      * @param packageName The package name
      *
@@ -211,32 +200,29 @@ public class StringManager {
 
 
     /**
-     * If a manager for a package/Locale combination already exists, it will be
-     * reused, else a new StringManager will be created and returned.
+     * If a manager for a package/Locale combination already exists, it will be reused, else a new StringManager will be
+     * created and returned.
      *
      * @param packageName The package name
      * @param locale      The Locale
      *
      * @return The StringManager for a particular package and Locale
      */
-    public static final synchronized StringManager getManager(
-            String packageName, Locale locale) {
+    public static final synchronized StringManager getManager(String packageName, Locale locale) {
 
-        Map<Locale,StringManager> map = managers.get(packageName);
+        Map<Locale, StringManager> map = managers.get(packageName);
         if (map == null) {
             /*
-             * Don't want the HashMap to be expanded beyond LOCALE_CACHE_SIZE.
-             * Expansion occurs when size() exceeds capacity. Therefore keep
-             * size at or below capacity.
-             * removeEldestEntry() executes after insertion therefore the test
-             * for removal needs to use one less than the maximum desired size
+             * Don't want the HashMap to be expanded beyond LOCALE_CACHE_SIZE. Expansion occurs when size() exceeds
+             * capacity. Therefore keep size at or below capacity. removeEldestEntry() executes after insertion
+             * therefore the test for removal needs to use one less than the maximum desired size
              *
              */
-            map = new LinkedHashMap<Locale,StringManager>(LOCALE_CACHE_SIZE, 1, true) {
+            map = new LinkedHashMap<Locale, StringManager>(LOCALE_CACHE_SIZE, 1, true) {
                 private static final long serialVersionUID = 1L;
+
                 @Override
-                protected boolean removeEldestEntry(
-                        Map.Entry<Locale,StringManager> eldest) {
+                protected boolean removeEldestEntry(Map.Entry<Locale, StringManager> eldest) {
                     if (size() > (LOCALE_CACHE_SIZE - 1)) {
                         return true;
                     }
@@ -256,16 +242,14 @@ public class StringManager {
 
 
     /**
-     * Retrieve the StringManager for a list of Locales. The first StringManager
-     * found will be returned.
+     * Retrieve the StringManager for a list of Locales. The first StringManager found will be returned.
      *
-     * @param packageName The package for which the StringManager is required
+     * @param packageName      The package for which the StringManager is required
      * @param requestedLocales the list of Locales
      *
      * @return the found StringManager or the default StringManager
      */
-    public static StringManager getManager(String packageName,
-            Enumeration<Locale> requestedLocales) {
+    public static StringManager getManager(String packageName, Enumeration<Locale> requestedLocales) {
         while (requestedLocales.hasMoreElements()) {
             Locale locale = requestedLocales.nextElement();
             StringManager result = getManager(packageName, locale);
diff --git a/java/org/apache/catalina/tribes/util/TcclThreadFactory.java b/java/org/apache/catalina/tribes/util/TcclThreadFactory.java
index 052d3ea51c..2a493ad2da 100644
--- a/java/org/apache/catalina/tribes/util/TcclThreadFactory.java
+++ b/java/org/apache/catalina/tribes/util/TcclThreadFactory.java
@@ -22,17 +22,14 @@ import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.atomic.AtomicInteger;
 
 /**
- * ThreadFactory implementation that creates threads with the thread context
- * class loader set to the class loader that loaded this factory. It is intended
- * to be used when tasks may be passed to executors when the web application
- * class loader is set as the thread context class loader, such as in async
- * session replication.
+ * ThreadFactory implementation that creates threads with the thread context class loader set to the class loader that
+ * loaded this factory. It is intended to be used when tasks may be passed to executors when the web application class
+ * loader is set as the thread context class loader, such as in async session replication.
  */
 public class TcclThreadFactory implements ThreadFactory {
 
     private static final AtomicInteger poolNumber = new AtomicInteger(1);
-    private static final boolean IS_SECURITY_ENABLED =
-        (System.getSecurityManager() != null);
+    private static final boolean IS_SECURITY_ENABLED = (System.getSecurityManager() != null);
 
     private final ThreadGroup group;
     private final AtomicInteger threadNumber = new AtomicInteger(1);
diff --git a/java/org/apache/catalina/tribes/util/UUIDGenerator.java b/java/org/apache/catalina/tribes/util/UUIDGenerator.java
index d3ef7a31c4..0358fbcdc0 100644
--- a/java/org/apache/catalina/tribes/util/UUIDGenerator.java
+++ b/java/org/apache/catalina/tribes/util/UUIDGenerator.java
@@ -27,8 +27,7 @@ import org.apache.juli.logging.LogFactory;
  */
 public class UUIDGenerator {
     private static final Log log = LogFactory.getLog(UUIDGenerator.class);
-    protected static final StringManager sm =
-        StringManager.getManager("org.apache.catalina.tribes.util");
+    protected static final StringManager sm = StringManager.getManager("org.apache.catalina.tribes.util");
 
     public static final int UUID_LENGTH = 16;
     public static final int UUID_VERSION = 4;
@@ -45,37 +44,37 @@ public class UUIDGenerator {
         secrand.nextInt();
         long time = System.currentTimeMillis() - start;
         if (time > 100) {
-            log.info(sm.getString("uuidGenerator.createRandom",
-                    secrand.getAlgorithm(), Long.valueOf(time)));
+            log.info(sm.getString("uuidGenerator.createRandom", secrand.getAlgorithm(), Long.valueOf(time)));
         }
     }
 
     public static byte[] randomUUID(boolean secure) {
         byte[] result = new byte[UUID_LENGTH];
-        return randomUUID(secure,result,0);
+        return randomUUID(secure, result, 0);
     }
 
     public static byte[] randomUUID(boolean secure, byte[] into, int offset) {
-        if ( (offset+UUID_LENGTH)>into.length ) {
-            throw new ArrayIndexOutOfBoundsException(sm.getString("uuidGenerator.unable.fit",
-                    Integer.toString(UUID_LENGTH), Integer.toString(into.length),
-                    Integer.toString(offset+UUID_LENGTH)));
+        if ((offset + UUID_LENGTH) > into.length) {
+            throw new ArrayIndexOutOfBoundsException(
+                    sm.getString("uuidGenerator.unable.fit", Integer.toString(UUID_LENGTH),
+                            Integer.toString(into.length), Integer.toString(offset + UUID_LENGTH)));
         }
-        Random r = (secure&&(secrand!=null))?secrand:rand;
-        nextBytes(into,offset,UUID_LENGTH,r);
-        into[6+offset] &= 0x0F;
-        into[6+offset] |= (UUID_VERSION << 4);
-        into[8+offset] &= 0x3F; //0011 1111
-        into[8+offset] |= 0x80; //1000 0000
+        Random r = (secure && (secrand != null)) ? secrand : rand;
+        nextBytes(into, offset, UUID_LENGTH, r);
+        into[6 + offset] &= 0x0F;
+        into[6 + offset] |= (UUID_VERSION << 4);
+        into[8 + offset] &= 0x3F; // 0011 1111
+        into[8 + offset] |= 0x80; // 1000 0000
         return into;
     }
 
     /**
      * Same as java.util.Random.nextBytes except this one we don't have to allocate a new byte array
-     * @param into byte[]
+     *
+     * @param into   byte[]
      * @param offset int
      * @param length int
-     * @param r Random
+     * @param r      Random
      */
     public static void nextBytes(byte[] into, int offset, int length, Random r) {
         int numRequested = length;
@@ -86,7 +85,7 @@ public class UUIDGenerator {
                     return;
                 }
                 rnd = (i == 0 ? r.nextInt() : rnd >> BITS_PER_BYTE);
-                into[offset+numGot] = (byte) rnd;
+                into[offset + numGot] = (byte) rnd;
                 numGot++;
             }
         }


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


[tomcat] 01/07: Code cleanup (format). No functional change.

Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 636e19f2a394463938eaad994a920aced10e0c29
Author: Mark Thomas <ma...@apache.org>
AuthorDate: Tue Jan 24 11:14:04 2023 +0000

    Code cleanup (format). No functional change.
---
 .../catalina/authenticator/AuthenticatorBase.java  | 456 ++++++++-------------
 .../catalina/authenticator/BasicAuthenticator.java |  87 ++--
 .../apache/catalina/authenticator/Constants.java   |  26 +-
 .../authenticator/DigestAuthenticator.java         | 134 +++---
 .../catalina/authenticator/FormAuthenticator.java  | 144 +++----
 .../authenticator/NonLoginAuthenticator.java       |  68 ++-
 .../catalina/authenticator/SSLAuthenticator.java   |  44 +-
 .../catalina/authenticator/SavedRequest.java       |  19 +-
 .../catalina/authenticator/SingleSignOn.java       | 257 +++++-------
 .../catalina/authenticator/SingleSignOnEntry.java  |  82 ++--
 .../authenticator/SingleSignOnSessionKey.java      |  17 +-
 .../authenticator/SpnegoAuthenticator.java         | 105 ++---
 12 files changed, 567 insertions(+), 872 deletions(-)

diff --git a/java/org/apache/catalina/authenticator/AuthenticatorBase.java b/java/org/apache/catalina/authenticator/AuthenticatorBase.java
index d9eb946e3d..9563b7a6ae 100644
--- a/java/org/apache/catalina/authenticator/AuthenticatorBase.java
+++ b/java/org/apache/catalina/authenticator/AuthenticatorBase.java
@@ -72,25 +72,21 @@ import org.apache.tomcat.util.http.RequestUtil;
 import org.apache.tomcat.util.res.StringManager;
 
 /**
- * Basic implementation of the <b>Valve</b> interface that enforces the
- * <code>&lt;security-constraint&gt;</code> elements in the web application
- * deployment descriptor. This functionality is implemented as a Valve so that
- * it can be omitted in environments that do not require these features.
- * Individual implementations of each supported authentication method can
- * subclass this base class as required.
+ * Basic implementation of the <b>Valve</b> interface that enforces the <code>&lt;security-constraint&gt;</code>
+ * elements in the web application deployment descriptor. This functionality is implemented as a Valve so that it can be
+ * omitted in environments that do not require these features. Individual implementations of each supported
+ * authentication method can subclass this base class as required.
  * <p>
- * <b>USAGE CONSTRAINT</b>: When this class is utilized, the Context to which it
- * is attached (or a parent Container in a hierarchy) must have an associated
- * Realm that can be used for authenticating users and enumerating the roles to
- * which they have been assigned.
+ * <b>USAGE CONSTRAINT</b>: When this class is utilized, the Context to which it is attached (or a parent Container in a
+ * hierarchy) must have an associated Realm that can be used for authenticating users and enumerating the roles to which
+ * they have been assigned.
  * <p>
- * <b>USAGE CONSTRAINT</b>: This Valve is only useful when processing HTTP
- * requests. Requests of any other type will simply be passed through.
+ * <b>USAGE CONSTRAINT</b>: This Valve is only useful when processing HTTP requests. Requests of any other type will
+ * simply be passed through.
  *
  * @author Craig R. McClanahan
  */
-public abstract class AuthenticatorBase extends ValveBase
-        implements Authenticator, RegistrationListener {
+public abstract class AuthenticatorBase extends ValveBase implements Authenticator, RegistrationListener {
 
     private final Log log = LogFactory.getLog(AuthenticatorBase.class); // must not be static
 
@@ -142,26 +138,21 @@ public abstract class AuthenticatorBase extends ValveBase
     // ----------------------------------------------------- Instance Variables
 
     /**
-     * Should a session always be used once a user is authenticated? This may
-     * offer some performance benefits since the session can then be used to
-     * cache the authenticated Principal, hence removing the need to
-     * authenticate the user via the Realm on every request. This may be of help
-     * for combinations such as BASIC authentication used with the JNDIRealm or
-     * DataSourceRealms. However there will also be the performance cost of
-     * creating and GC'ing the session. By default, a session will not be
-     * created.
+     * Should a session always be used once a user is authenticated? This may offer some performance benefits since the
+     * session can then be used to cache the authenticated Principal, hence removing the need to authenticate the user
+     * via the Realm on every request. This may be of help for combinations such as BASIC authentication used with the
+     * JNDIRealm or DataSourceRealms. However there will also be the performance cost of creating and GC'ing the
+     * session. By default, a session will not be created.
      */
     protected boolean alwaysUseSession = false;
 
     /**
-     * Should we cache authenticated Principals if the request is part of an
-     * HTTP session?
+     * Should we cache authenticated Principals if the request is part of an HTTP session?
      */
     protected boolean cache = true;
 
     /**
-     * Should the session ID, if any, be changed upon a successful
-     * authentication to prevent a session fixation attack?
+     * Should the session ID, if any, be changed upon a successful authentication to prevent a session fixation attack?
      */
     protected boolean changeSessionIdOnAuthentication = true;
 
@@ -171,64 +162,52 @@ public abstract class AuthenticatorBase extends ValveBase
     protected Context context = null;
 
     /**
-     * Flag to determine if we disable proxy caching, or leave the issue up to
-     * the webapp developer.
+     * Flag to determine if we disable proxy caching, or leave the issue up to the webapp developer.
      */
     protected boolean disableProxyCaching = true;
 
     /**
-     * Flag to determine if we disable proxy caching with headers incompatible
-     * with IE.
+     * Flag to determine if we disable proxy caching with headers incompatible with IE.
      */
     protected boolean securePagesWithPragma = false;
 
     /**
-     * The Java class name of the secure random number generator class to be
-     * used when generating SSO session identifiers. The random number generator
-     * class must be self-seeding and have a zero-argument constructor. If not
-     * specified, an instance of {@link java.security.SecureRandom} will be
-     * generated.
+     * The Java class name of the secure random number generator class to be used when generating SSO session
+     * identifiers. The random number generator class must be self-seeding and have a zero-argument constructor. If not
+     * specified, an instance of {@link java.security.SecureRandom} will be generated.
      */
     protected String secureRandomClass = null;
 
     /**
-     * The name of the algorithm to use to create instances of
-     * {@link java.security.SecureRandom} which are used to generate SSO session
-     * IDs. If no algorithm is specified, SHA1PRNG is used. If SHA1PRNG is not
-     * available, the platform default will be used. To use the platform default
-     * (which may be SHA1PRNG), specify the empty string. If an invalid
-     * algorithm and/or provider is specified the SecureRandom instances will be
-     * created using the defaults. If that fails, the SecureRandom instances
-     * will be created using platform defaults.
+     * The name of the algorithm to use to create instances of {@link java.security.SecureRandom} which are used to
+     * generate SSO session IDs. If no algorithm is specified, SHA1PRNG is used. If SHA1PRNG is not available, the
+     * platform default will be used. To use the platform default (which may be SHA1PRNG), specify the empty string. If
+     * an invalid algorithm and/or provider is specified the SecureRandom instances will be created using the defaults.
+     * If that fails, the SecureRandom instances will be created using platform defaults.
      */
     protected String secureRandomAlgorithm = SessionIdGeneratorBase.DEFAULT_SECURE_RANDOM_ALGORITHM;
 
     /**
-     * The name of the provider to use to create instances of
-     * {@link java.security.SecureRandom} which are used to generate session SSO
-     * IDs. If no provider is specified the platform default is used. If an
-     * invalid algorithm and/or provider is specified the SecureRandom instances
-     * will be created using the defaults. If that fails, the SecureRandom
-     * instances will be created using platform defaults.
+     * The name of the provider to use to create instances of {@link java.security.SecureRandom} which are used to
+     * generate session SSO IDs. If no provider is specified the platform default is used. If an invalid algorithm
+     * and/or provider is specified the SecureRandom instances will be created using the defaults. If that fails, the
+     * SecureRandom instances will be created using platform defaults.
      */
     protected String secureRandomProvider = null;
 
     /**
-     * The name of the JASPIC callback handler class. If none is specified the
-     * default {@link org.apache.catalina.authenticator.jaspic.CallbackHandlerImpl}
-     * will be used.
+     * The name of the JASPIC callback handler class. If none is specified the default
+     * {@link org.apache.catalina.authenticator.jaspic.CallbackHandlerImpl} will be used.
      */
     protected String jaspicCallbackHandlerClass = "org.apache.catalina.authenticator.jaspic.CallbackHandlerImpl";
 
     /**
-     * Should the auth information (remote user and auth type) be returned as response
-     * headers for a forwarded/proxied request? When the {@link RemoteIpValve} or
-     * {@link RemoteIpFilter} mark a forwarded request with the
-     * {@link Globals#REQUEST_FORWARDED_ATTRIBUTE} this authenticator can return the
-     * values of {@link HttpServletRequest#getRemoteUser()} and
-     * {@link HttpServletRequest#getAuthType()} as response headers {@code remote-user}
-     * and {@code auth-type} to a reverse proxy. This is useful, e.g., for access log
-     * consistency or other decisions to make.
+     * Should the auth information (remote user and auth type) be returned as response headers for a forwarded/proxied
+     * request? When the {@link RemoteIpValve} or {@link RemoteIpFilter} mark a forwarded request with the
+     * {@link Globals#REQUEST_FORWARDED_ATTRIBUTE} this authenticator can return the values of
+     * {@link HttpServletRequest#getRemoteUser()} and {@link HttpServletRequest#getAuthType()} as response headers
+     * {@code remote-user} and {@code auth-type} to a reverse proxy. This is useful, e.g., for access log consistency or
+     * other decisions to make.
      */
 
     protected boolean sendAuthInfoResponseHeaders = false;
@@ -236,8 +215,7 @@ public abstract class AuthenticatorBase extends ValveBase
     protected SessionIdGeneratorBase sessionIdGenerator = null;
 
     /**
-     * The SingleSignOn implementation in our request processing chain, if there
-     * is one.
+     * The SingleSignOn implementation in our request processing chain, if there is one.
      */
     protected SingleSignOn sso = null;
 
@@ -269,8 +247,7 @@ public abstract class AuthenticatorBase extends ValveBase
     /**
      * Return the cache authenticated Principals flag.
      *
-     * @return <code>true</code> if authenticated Principals will be cached,
-     *         otherwise <code>false</code>
+     * @return <code>true</code> if authenticated Principals will be cached, otherwise <code>false</code>
      */
     public boolean getCache() {
         return this.cache;
@@ -279,8 +256,7 @@ public abstract class AuthenticatorBase extends ValveBase
     /**
      * Set the cache authenticated Principals flag.
      *
-     * @param cache
-     *            The new cache flag
+     * @param cache The new cache flag
      */
     public void setCache(boolean cache) {
         this.cache = cache;
@@ -297,8 +273,7 @@ public abstract class AuthenticatorBase extends ValveBase
     /**
      * Set the Container to which this Valve is attached.
      *
-     * @param container
-     *            The container to which we are attached
+     * @param container The container to which we are attached
      */
     @Override
     public void setContainer(Container container) {
@@ -313,70 +288,60 @@ public abstract class AuthenticatorBase extends ValveBase
     }
 
     /**
-     * Return the flag that states if we add headers to disable caching by
-     * proxies.
+     * Return the flag that states if we add headers to disable caching by proxies.
      *
-     * @return <code>true</code> if the headers will be added, otherwise
-     *         <code>false</code>
+     * @return <code>true</code> if the headers will be added, otherwise <code>false</code>
      */
     public boolean getDisableProxyCaching() {
         return disableProxyCaching;
     }
 
     /**
-     * Set the value of the flag that states if we add headers to disable
-     * caching by proxies.
+     * Set the value of the flag that states if we add headers to disable caching by proxies.
      *
-     * @param nocache
-     *            <code>true</code> if we add headers to disable proxy caching,
-     *            <code>false</code> if we leave the headers alone.
+     * @param nocache <code>true</code> if we add headers to disable proxy caching, <code>false</code> if we leave the
+     *                    headers alone.
      */
     public void setDisableProxyCaching(boolean nocache) {
         disableProxyCaching = nocache;
     }
 
     /**
-     * Return the flag that states, if proxy caching is disabled, what headers
-     * we add to disable the caching.
+     * Return the flag that states, if proxy caching is disabled, what headers we add to disable the caching.
      *
-     * @return <code>true</code> if a Pragma header should be used, otherwise
-     *         <code>false</code>
+     * @return <code>true</code> if a Pragma header should be used, otherwise <code>false</code>
      */
     public boolean getSecurePagesWithPragma() {
         return securePagesWithPragma;
     }
 
     /**
-     * Set the value of the flag that states what headers we add to disable
-     * proxy caching.
+     * Set the value of the flag that states what headers we add to disable proxy caching.
      *
-     * @param securePagesWithPragma
-     *            <code>true</code> if we add headers which are incompatible
-     *            with downloading office documents in IE under SSL but which
-     *            fix a caching problem in Mozilla.
+     * @param securePagesWithPragma <code>true</code> if we add headers which are incompatible with downloading office
+     *                                  documents in IE under SSL but which fix a caching problem in Mozilla.
      */
     public void setSecurePagesWithPragma(boolean securePagesWithPragma) {
         this.securePagesWithPragma = securePagesWithPragma;
     }
 
     /**
-     * Return the flag that states if we should change the session ID of an
-     * existing session upon successful authentication.
+     * Return the flag that states if we should change the session ID of an existing session upon successful
+     * authentication.
      *
-     * @return <code>true</code> to change session ID upon successful
-     *         authentication, <code>false</code> to do not perform the change.
+     * @return <code>true</code> to change session ID upon successful authentication, <code>false</code> to do not
+     *             perform the change.
      */
     public boolean getChangeSessionIdOnAuthentication() {
         return changeSessionIdOnAuthentication;
     }
 
     /**
-     * Set the value of the flag that states if we should change the session ID
-     * of an existing session upon successful authentication.
+     * Set the value of the flag that states if we should change the session ID of an existing session upon successful
+     * authentication.
      *
-     * @param changeSessionIdOnAuthentication <code>true</code> to change
-     *            session ID upon successful authentication, <code>false</code>
-     *            to do not perform the change.
+     * @param changeSessionIdOnAuthentication <code>true</code> to change session ID upon successful authentication,
+     *                                            <code>false</code> to do not perform the change.
      */
     public void setChangeSessionIdOnAuthentication(boolean changeSessionIdOnAuthentication) {
         this.changeSessionIdOnAuthentication = changeSessionIdOnAuthentication;
@@ -385,8 +350,7 @@ public abstract class AuthenticatorBase extends ValveBase
     /**
      * Return the secure random number generator class name.
      *
-     * @return The fully qualified name of the SecureRandom implementation to
-     *         use
+     * @return The fully qualified name of the SecureRandom implementation to use
      */
     public String getSecureRandomClass() {
         return this.secureRandomClass;
@@ -395,8 +359,7 @@ public abstract class AuthenticatorBase extends ValveBase
     /**
      * Set the secure random number generator class name.
      *
-     * @param secureRandomClass
-     *            The new secure random number generator class name
+     * @param secureRandomClass The new secure random number generator class name
      */
     public void setSecureRandomClass(String secureRandomClass) {
         this.secureRandomClass = secureRandomClass;
@@ -414,8 +377,7 @@ public abstract class AuthenticatorBase extends ValveBase
     /**
      * Set the secure random number generator algorithm name.
      *
-     * @param secureRandomAlgorithm
-     *            The new secure random number generator algorithm name
+     * @param secureRandomAlgorithm The new secure random number generator algorithm name
      */
     public void setSecureRandomAlgorithm(String secureRandomAlgorithm) {
         this.secureRandomAlgorithm = secureRandomAlgorithm;
@@ -433,8 +395,7 @@ public abstract class AuthenticatorBase extends ValveBase
     /**
      * Set the secure random number generator provider name.
      *
-     * @param secureRandomProvider
-     *            The new secure random number generator provider name
+     * @param secureRandomProvider The new secure random number generator provider name
      */
     public void setSecureRandomProvider(String secureRandomProvider) {
         this.secureRandomProvider = secureRandomProvider;
@@ -452,29 +413,25 @@ public abstract class AuthenticatorBase extends ValveBase
     /**
      * Set the JASPIC callback handler class name
      *
-     * @param jaspicCallbackHandlerClass
-     *            The new JASPIC callback handler class name
+     * @param jaspicCallbackHandlerClass The new JASPIC callback handler class name
      */
     public void setJaspicCallbackHandlerClass(String jaspicCallbackHandlerClass) {
         this.jaspicCallbackHandlerClass = jaspicCallbackHandlerClass;
     }
 
     /**
-     * Returns the flag whether authentication information will be sent to a reverse
-     * proxy on a forwarded request.
+     * Returns the flag whether authentication information will be sent to a reverse proxy on a forwarded request.
      *
-     * @return {@code true} if response headers shall be sent,  {@code false} otherwise
+     * @return {@code true} if response headers shall be sent, {@code false} otherwise
      */
     public boolean isSendAuthInfoResponseHeaders() {
         return sendAuthInfoResponseHeaders;
     }
 
     /**
-     * Sets the flag whether authentication information will be send to a reverse
-     * proxy on a forwarded request.
+     * Sets the flag whether authentication information will be send to a reverse proxy on a forwarded request.
      *
-     * @param sendAuthInfoResponseHeaders {@code true} if response headers shall be
-     *                                    sent, {@code false} otherwise
+     * @param sendAuthInfoResponseHeaders {@code true} if response headers shall be sent, {@code false} otherwise
      */
     public void setSendAuthInfoResponseHeaders(boolean sendAuthInfoResponseHeaders) {
         this.sendAuthInfoResponseHeaders = sendAuthInfoResponseHeaders;
@@ -483,25 +440,19 @@ public abstract class AuthenticatorBase extends ValveBase
     // --------------------------------------------------------- Public Methods
 
     /**
-     * Enforce the security restrictions in the web application deployment
-     * descriptor of our associated Context.
+     * Enforce the security restrictions in the web application deployment descriptor of our associated Context.
      *
-     * @param request
-     *            Request to be processed
-     * @param response
-     *            Response to be processed
+     * @param request  Request to be processed
+     * @param response Response to be processed
      *
-     * @exception IOException
-     *                if an input/output error occurs
-     * @exception ServletException
-     *                if thrown by a processing element
+     * @exception IOException      if an input/output error occurs
+     * @exception ServletException if thrown by a processing element
      */
     @Override
     public void invoke(Request request, Response response) throws IOException, ServletException {
 
         if (log.isDebugEnabled()) {
-            log.debug("Security checking request " + request.getMethod() + " " +
-                    request.getRequestURI());
+            log.debug("Security checking request " + request.getMethod() + " " + request.getRequestURI());
         }
 
         // Have we got a cached authenticated Principal to record?
@@ -513,8 +464,8 @@ public abstract class AuthenticatorBase extends ValveBase
                     principal = session.getPrincipal();
                     if (principal != null) {
                         if (log.isDebugEnabled()) {
-                            log.debug("We have cached auth type " + session.getAuthType() +
-                                    " for principal " + principal);
+                            log.debug("We have cached auth type " + session.getAuthType() + " for principal " +
+                                    principal);
                         }
                         request.setAuthType(session.getAuthType());
                         request.setUserPrincipal(principal);
@@ -544,8 +495,7 @@ public abstract class AuthenticatorBase extends ValveBase
 
         // Make sure that constrained resources are not cached by web proxies
         // or browsers as caching can provide a security hole
-        if (constraints != null && disableProxyCaching &&
-                !"POST".equalsIgnoreCase(request.getMethod())) {
+        if (constraints != null && disableProxyCaching && !"POST".equalsIgnoreCase(request.getMethod())) {
             if (securePagesWithPragma) {
                 // Note: These can cause problems with downloading files with IE
                 response.setHeader("Pragma", "No-cache");
@@ -566,8 +516,8 @@ public abstract class AuthenticatorBase extends ValveBase
                     log.debug("Failed hasUserDataPermission() test");
                 }
                 /*
-                 * ASSERT: Authenticator already set the appropriate HTTP status
-                 * code, so we do not have to do anything special
+                 * ASSERT: Authenticator already set the appropriate HTTP status code, so we do not have to do anything
+                 * special
                  */
                 return;
             }
@@ -581,8 +531,7 @@ public abstract class AuthenticatorBase extends ValveBase
             for (int i = 0; i < constraints.length && hasAuthConstraint; i++) {
                 if (!constraints[i].getAuthConstraint()) {
                     hasAuthConstraint = false;
-                } else if (!constraints[i].getAllRoles() &&
-                        !constraints[i].getAuthenticatedUsers()) {
+                } else if (!constraints[i].getAllRoles() && !constraints[i].getAuthenticatedUsers()) {
                     String[] roles = constraints[i].findAuthRoles();
                     if (roles == null || roles.length == 0) {
                         hasAuthConstraint = false;
@@ -595,8 +544,7 @@ public abstract class AuthenticatorBase extends ValveBase
             authRequired = true;
         }
 
-        if (!authRequired && context.getPreemptiveAuthentication() &&
-                isPreemptiveAuthPossible(request)) {
+        if (!authRequired && context.getPreemptiveAuthentication() && isPreemptiveAuthPossible(request)) {
             authRequired = true;
         }
 
@@ -623,14 +571,13 @@ public abstract class AuthenticatorBase extends ValveBase
             }
 
             if (jaspicProvider == null && !doAuthenticate(request, response) ||
-                    jaspicProvider != null &&
-                            !authenticateJaspic(request, response, jaspicState, false)) {
+                    jaspicProvider != null && !authenticateJaspic(request, response, jaspicState, false)) {
                 if (log.isDebugEnabled()) {
                     log.debug("Failed authenticate() test");
                 }
                 /*
-                 * ASSERT: Authenticator already set the appropriate HTTP status
-                 * code, so we do not have to do anything special
+                 * ASSERT: Authenticator already set the appropriate HTTP status code, so we do not have to do anything
+                 * special
                  */
                 return;
             }
@@ -646,8 +593,8 @@ public abstract class AuthenticatorBase extends ValveBase
                     log.debug("Failed accessControl() test");
                 }
                 /*
-                 * ASSERT: AccessControl method has already set the appropriate
-                 * HTTP status code, so we do not have to do anything special
+                 * ASSERT: AccessControl method has already set the appropriate HTTP status code, so we do not have to
+                 * do anything special
                  */
                 return;
             }
@@ -673,14 +620,11 @@ public abstract class AuthenticatorBase extends ValveBase
             // This is a subset of the tests in CorsFilter.checkRequestType
             if ("OPTIONS".equals(request.getMethod())) {
                 String originHeader = request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN);
-                if (originHeader != null &&
-                        !originHeader.isEmpty() &&
-                        RequestUtil.isValidOrigin(originHeader) &&
+                if (originHeader != null && !originHeader.isEmpty() && RequestUtil.isValidOrigin(originHeader) &&
                         !RequestUtil.isSameOrigin(request, originHeader)) {
-                    String accessControlRequestMethodHeader =
-                            request.getHeader(CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
-                    if (accessControlRequestMethodHeader != null &&
-                            !accessControlRequestMethodHeader.isEmpty()) {
+                    String accessControlRequestMethodHeader = request
+                            .getHeader(CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
+                    if (accessControlRequestMethodHeader != null && !accessControlRequestMethodHeader.isEmpty()) {
                         // This appears to be a CORS Preflight request
                         if (allowCorsPreflight == AllowCorsPreflight.ALWAYS) {
                             allowBypass = true;
@@ -724,8 +668,7 @@ public abstract class AuthenticatorBase extends ValveBase
 
 
     @Override
-    public boolean authenticate(Request request, HttpServletResponse httpResponse)
-            throws IOException {
+    public boolean authenticate(Request request, HttpServletResponse httpResponse) throws IOException {
 
         AuthConfigProvider jaspicProvider = getJaspicProvider();
 
@@ -758,17 +701,16 @@ public abstract class AuthenticatorBase extends ValveBase
     }
 
 
-    private JaspicState getJaspicState(AuthConfigProvider jaspicProvider, Request request,
-            Response response, boolean authMandatory) throws IOException {
+    private JaspicState getJaspicState(AuthConfigProvider jaspicProvider, Request request, Response response,
+            boolean authMandatory) throws IOException {
         JaspicState jaspicState = new JaspicState();
 
-        jaspicState.messageInfo =
-                new MessageInfoImpl(request.getRequest(), response.getResponse(), authMandatory);
+        jaspicState.messageInfo = new MessageInfoImpl(request.getRequest(), response.getResponse(), authMandatory);
 
         try {
             CallbackHandler callbackHandler = getCallbackHandler();
-            ServerAuthConfig serverAuthConfig = jaspicProvider.getServerAuthConfig(
-                    "HttpServlet", jaspicAppContextID, callbackHandler);
+            ServerAuthConfig serverAuthConfig = jaspicProvider.getServerAuthConfig("HttpServlet", jaspicAppContextID,
+                    callbackHandler);
             String authContextID = serverAuthConfig.getAuthContextID(jaspicState.messageInfo);
             jaspicState.serverAuthContext = serverAuthConfig.getAuthContext(authContextID, null, null);
         } catch (AuthException e) {
@@ -795,8 +737,7 @@ public abstract class AuthenticatorBase extends ValveBase
 
         Class<?> clazz = null;
         try {
-            clazz = Class.forName(jaspicCallbackHandlerClass, true,
-                    Thread.currentThread().getContextClassLoader());
+            clazz = Class.forName(jaspicCallbackHandlerClass, true, Thread.currentThread().getContextClassLoader());
         } catch (ClassNotFoundException e) {
             // Proceed with the retry below
         }
@@ -805,7 +746,7 @@ public abstract class AuthenticatorBase extends ValveBase
             if (clazz == null) {
                 clazz = Class.forName(jaspicCallbackHandlerClass);
             }
-            callbackHandler = (CallbackHandler)clazz.getConstructor().newInstance();
+            callbackHandler = (CallbackHandler) clazz.getConstructor().newInstance();
         } catch (ReflectiveOperationException e) {
             throw new SecurityException(e);
         }
@@ -822,32 +763,26 @@ public abstract class AuthenticatorBase extends ValveBase
     // ------------------------------------------------------ Protected Methods
 
     /**
-     * Provided for sub-classes to implement their specific authentication
-     * mechanism.
+     * Provided for sub-classes to implement their specific authentication mechanism.
      *
-     * @param request The request that triggered the authentication
+     * @param request  The request that triggered the authentication
      * @param response The response associated with the request
      *
      * @return {@code true} if the the user was authenticated, otherwise {@code
-     *         false}, in which case an authentication challenge will have been
-     *         written to the response
+     *         false}, in which case an authentication challenge will have been written to the response
      *
-     * @throws IOException If an I/O problem occurred during the authentication
-     *                     process
+     * @throws IOException If an I/O problem occurred during the authentication process
      */
-    protected abstract boolean doAuthenticate(Request request, HttpServletResponse response)
-            throws IOException;
+    protected abstract boolean doAuthenticate(Request request, HttpServletResponse response) throws IOException;
 
 
     /**
-     * Does this authenticator require that {@link #authenticate(Request,
-     * HttpServletResponse)} is called to continue an authentication process
-     * that started in a previous request?
+     * Does this authenticator require that {@link #authenticate(Request, HttpServletResponse)} is called to continue an
+     * authentication process that started in a previous request?
      *
      * @param request The request currently being processed
      *
-     * @return {@code true} if authenticate() must be called, otherwise
-     *         {@code false}
+     * @return {@code true} if authenticate() must be called, otherwise {@code false}
      */
     protected boolean isContinuationRequired(Request request) {
         return false;
@@ -855,13 +790,10 @@ public abstract class AuthenticatorBase extends ValveBase
 
 
     /**
-     * Associate the specified single sign on identifier with the specified
-     * Session.
+     * Associate the specified single sign on identifier with the specified Session.
      *
-     * @param ssoId
-     *            Single sign on identifier
-     * @param session
-     *            Session to be associated
+     * @param ssoId   Single sign on identifier
+     * @param session Session to be associated
      */
     protected void associate(String ssoId, Session session) {
 
@@ -920,11 +852,9 @@ public abstract class AuthenticatorBase extends ValveBase
                 }
 
                 /*
-                 * Need to handle three cases.
-                 * See https://bz.apache.org/bugzilla/show_bug.cgi?id=64713
-                 * 1. registerSession TRUE    always use session, always cache
-                 * 2. registerSession NOT SET config for session, config for cache
-                 * 3. registerSession FALSE   config for session, never cache
+                 * Need to handle three cases. See https://bz.apache.org/bugzilla/show_bug.cgi?id=64713 1.
+                 * registerSession TRUE always use session, always cache 2. registerSession NOT SET config for session,
+                 * config for cache 3. registerSession FALSE config for session, never cache
                  */
                 if (register != null) {
                     register(request, response, principal, authType, null, null,
@@ -955,20 +885,14 @@ public abstract class AuthenticatorBase extends ValveBase
 
 
     /**
-     * Check to see if the user has already been authenticated earlier in the
-     * processing chain or if there is enough information available to
-     * authenticate the user without requiring further user interaction.
+     * Check to see if the user has already been authenticated earlier in the processing chain or if there is enough
+     * information available to authenticate the user without requiring further user interaction.
      *
-     * @param request
-     *            The current request
-     * @param response
-     *            The current response
-     * @param useSSO
-     *            Should information available from SSO be used to attempt to
-     *            authenticate the current user?
+     * @param request  The current request
+     * @param response The current response
+     * @param useSSO   Should information available from SSO be used to attempt to authenticate the current user?
      *
-     * @return <code>true</code> if the user was authenticated via the cache,
-     *         otherwise <code>false</code>
+     * @return <code>true</code> if the user was authenticated via the cache, otherwise <code>false</code>
      */
     protected boolean checkForCachedAuthentication(Request request, HttpServletResponse response, boolean useSSO) {
 
@@ -994,12 +918,10 @@ public abstract class AuthenticatorBase extends ValveBase
                 log.debug(sm.getString("authenticator.check.sso", ssoId));
             }
             /*
-             * Try to reauthenticate using data cached by SSO. If this fails,
-             * either the original SSO logon was of DIGEST or SSL (which we
-             * can't reauthenticate ourselves because there is no cached
-             * username and password), or the realm denied the user's
-             * reauthentication for some reason. In either case we have to
-             * prompt the user for a logon
+             * Try to reauthenticate using data cached by SSO. If this fails, either the original SSO logon was of
+             * DIGEST or SSL (which we can't reauthenticate ourselves because there is no cached username and password),
+             * or the realm denied the user's reauthentication for some reason. In either case we have to prompt the
+             * user for a logon
              */
             if (reauthenticateFromSSO(ssoId, request)) {
                 return true;
@@ -1035,14 +957,12 @@ public abstract class AuthenticatorBase extends ValveBase
     }
 
     /**
-     * Attempts reauthentication to the <code>Realm</code> using the credentials
-     * included in argument <code>entry</code>.
+     * Attempts reauthentication to the <code>Realm</code> using the credentials included in argument
+     * <code>entry</code>.
+     *
+     * @param ssoId   identifier of SingleSignOn session with which the caller is associated
+     * @param request the request that needs to be authenticated
      *
-     * @param ssoId
-     *            identifier of SingleSignOn session with which the caller is
-     *            associated
-     * @param request
-     *            the request that needs to be authenticated
      * @return <code>true</code> if the reauthentication from SSL occurred
      */
     protected boolean reauthenticateFromSSO(String ssoId, Request request) {
@@ -1065,8 +985,7 @@ public abstract class AuthenticatorBase extends ValveBase
             associate(ssoId, request.getSessionInternal(true));
 
             if (log.isDebugEnabled()) {
-                log.debug("Reauthenticated cached principal '" +
-                        request.getUserPrincipal().getName() +
+                log.debug("Reauthenticated cached principal '" + request.getUserPrincipal().getName() +
                         "' with auth type '" + request.getAuthType() + "'");
             }
         }
@@ -1075,57 +994,37 @@ public abstract class AuthenticatorBase extends ValveBase
     }
 
     /**
-     * Register an authenticated Principal and authentication type in our
-     * request, in the current session (if there is one), and with our
-     * SingleSignOn valve, if there is one. Set the appropriate cookie to be
-     * returned.
+     * Register an authenticated Principal and authentication type in our request, in the current session (if there is
+     * one), and with our SingleSignOn valve, if there is one. Set the appropriate cookie to be returned.
      *
-     * @param request
-     *            The servlet request we are processing
-     * @param response
-     *            The servlet response we are generating
-     * @param principal
-     *            The authenticated Principal to be registered
-     * @param authType
-     *            The authentication type to be registered
-     * @param username
-     *            Username used to authenticate (if any)
-     * @param password
-     *            Password used to authenticate (if any)
+     * @param request   The servlet request we are processing
+     * @param response  The servlet response we are generating
+     * @param principal The authenticated Principal to be registered
+     * @param authType  The authentication type to be registered
+     * @param username  Username used to authenticate (if any)
+     * @param password  Password used to authenticate (if any)
      */
-    public void register(Request request, HttpServletResponse response, Principal principal,
-            String authType, String username, String password) {
+    public void register(Request request, HttpServletResponse response, Principal principal, String authType,
+            String username, String password) {
         register(request, response, principal, authType, username, password, alwaysUseSession, cache);
     }
 
 
     /**
-     * Register an authenticated Principal and authentication type in our
-     * request, in the current session (if there is one), and with our
-     * SingleSignOn valve, if there is one. Set the appropriate cookie to be
-     * returned.
+     * Register an authenticated Principal and authentication type in our request, in the current session (if there is
+     * one), and with our SingleSignOn valve, if there is one. Set the appropriate cookie to be returned.
      *
-     * @param request
-     *            The servlet request we are processing
-     * @param response
-     *            The servlet response we are generating
-     * @param principal
-     *            The authenticated Principal to be registered
-     * @param authType
-     *            The authentication type to be registered
-     * @param username
-     *            Username used to authenticate (if any)
-     * @param password
-     *            Password used to authenticate (if any)
-     * @param alwaysUseSession
-     *            Should a session always be used once a user is authenticated?
-     * @param cache
-     *            Should we cache authenticated Principals if the request is part of an
-     *            HTTP session?
+     * @param request          The servlet request we are processing
+     * @param response         The servlet response we are generating
+     * @param principal        The authenticated Principal to be registered
+     * @param authType         The authentication type to be registered
+     * @param username         Username used to authenticate (if any)
+     * @param password         Password used to authenticate (if any)
+     * @param alwaysUseSession Should a session always be used once a user is authenticated?
+     * @param cache            Should we cache authenticated Principals if the request is part of an HTTP session?
      */
-    protected void register(Request request, HttpServletResponse response, Principal principal,
-            String authType, String username, String password, boolean alwaysUseSession,
-            boolean cache) {
+    protected void register(Request request, HttpServletResponse response, Principal principal, String authType,
+            String username, String password, boolean alwaysUseSession, boolean cache) {
 
         if (log.isDebugEnabled()) {
             String name = (principal == null) ? "none" : principal.getName();
@@ -1136,8 +1035,8 @@ public abstract class AuthenticatorBase extends ValveBase
         request.setAuthType(authType);
         request.setUserPrincipal(principal);
 
-        if (sendAuthInfoResponseHeaders
-            && Boolean.TRUE.equals(request.getAttribute(Globals.REQUEST_FORWARDED_ATTRIBUTE))) {
+        if (sendAuthInfoResponseHeaders &&
+                Boolean.TRUE.equals(request.getAttribute(Globals.REQUEST_FORWARDED_ATTRIBUTE))) {
             response.setHeader("remote-user", request.getRemoteUser());
             response.setHeader("auth-type", request.getAuthType());
         }
@@ -1252,18 +1151,15 @@ public abstract class AuthenticatorBase extends ValveBase
     /**
      * Process the login request.
      *
-     * @param request
-     *            Associated request
-     * @param username
-     *            The user
-     * @param password
-     *            The password
+     * @param request  Associated request
+     * @param username The user
+     * @param password The password
+     *
      * @return The authenticated Principal
-     * @throws ServletException
-     *             No principal was authenticated with the specified credentials
+     *
+     * @throws ServletException No principal was authenticated with the specified credentials
      */
-    protected Principal doLogin(Request request, String username, String password)
-            throws ServletException {
+    protected Principal doLogin(Request request, String username, String password) throws ServletException {
         Principal p = context.getRealm().authenticate(username, password);
         if (p == null) {
             throw new ServletException(sm.getString("authenticator.loginFail"));
@@ -1280,8 +1176,8 @@ public abstract class AuthenticatorBase extends ValveBase
             if (client != null) {
                 ServerAuthContext serverAuthContext;
                 try {
-                    ServerAuthConfig serverAuthConfig = provider.getServerAuthConfig("HttpServlet",
-                            jaspicAppContextID, getCallbackHandler());
+                    ServerAuthConfig serverAuthConfig = provider.getServerAuthConfig("HttpServlet", jaspicAppContextID,
+                            getCallbackHandler());
                     String authContextID = serverAuthConfig.getAuthContextID(messageInfo);
                     serverAuthContext = serverAuthConfig.getAuthContext(authContextID, null, null);
                     serverAuthContext.cleanSubject(messageInfo, client);
@@ -1309,15 +1205,13 @@ public abstract class AuthenticatorBase extends ValveBase
      * Start this component and implement the requirements of
      * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
      *
-     * @exception LifecycleException
-     *                if this component detects a fatal error that prevents this
-     *                component from being used
+     * @exception LifecycleException if this component detects a fatal error that prevents this component from being
+     *                                   used
      */
     @Override
     protected synchronized void startInternal() throws LifecycleException {
         ServletContext servletContext = context.getServletContext();
-        jaspicAppContextID = servletContext.getVirtualServerName() + " " +
-                servletContext.getContextPath();
+        jaspicAppContextID = servletContext.getVirtualServerName() + " " + servletContext.getContextPath();
 
         // Look up the SingleSignOn implementation in our request processing
         // path, if there is one
@@ -1355,9 +1249,8 @@ public abstract class AuthenticatorBase extends ValveBase
      * Stop this component and implement the requirements of
      * {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
      *
-     * @exception LifecycleException
-     *                if this component detects a fatal error that prevents this
-     *                component from being used
+     * @exception LifecycleException if this component detects a fatal error that prevents this component from being
+     *                                   used
      */
     @Override
     protected synchronized void stopInternal() throws LifecycleException {
@@ -1369,13 +1262,11 @@ public abstract class AuthenticatorBase extends ValveBase
 
 
     /**
-     * Can the authenticator perform preemptive authentication for the given
-     * request?
+     * Can the authenticator perform preemptive authentication for the given request?
      *
      * @param request The request to check for credentials
      *
-     * @return {@code true} if preemptive authentication is possible, otherwise
-     *         {@code false}
+     * @return {@code true} if preemptive authentication is possible, otherwise {@code false}
      */
     protected boolean isPreemptiveAuthPossible(Request request) {
         return false;
@@ -1397,8 +1288,7 @@ public abstract class AuthenticatorBase extends ValveBase
         if (factory == null) {
             provider = Optional.empty();
         } else {
-            provider = Optional.ofNullable(
-                    factory.getConfigProvider("HttpServlet", jaspicAppContextID, this));
+            provider = Optional.ofNullable(factory.getConfigProvider("HttpServlet", jaspicAppContextID, this));
         }
         jaspicProvider = provider;
         return provider;
@@ -1418,8 +1308,6 @@ public abstract class AuthenticatorBase extends ValveBase
 
 
     protected enum AllowCorsPreflight {
-        NEVER,
-        FILTER,
-        ALWAYS
+        NEVER, FILTER, ALWAYS
     }
 }
diff --git a/java/org/apache/catalina/authenticator/BasicAuthenticator.java b/java/org/apache/catalina/authenticator/BasicAuthenticator.java
index 452dc108bf..103b7d3a0c 100644
--- a/java/org/apache/catalina/authenticator/BasicAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/BasicAuthenticator.java
@@ -32,9 +32,8 @@ import org.apache.tomcat.util.buf.MessageBytes;
 import org.apache.tomcat.util.codec.binary.Base64;
 
 /**
- * An <b>Authenticator</b> and <b>Valve</b> implementation of HTTP BASIC
- * Authentication, as outlined in RFC 2617:  "HTTP Authentication: Basic
- * and Digest Access Authentication."
+ * An <b>Authenticator</b> and <b>Valve</b> implementation of HTTP BASIC Authentication, as outlined in RFC 2617: "HTTP
+ * Authentication: Basic and Digest Access Authentication."
  *
  * @author Craig R. McClanahan
  */
@@ -65,7 +64,6 @@ public class BasicAuthenticator extends AuthenticatorBase {
     }
 
 
-
     public boolean getTrimCredentials() {
         return trimCredentials;
     }
@@ -77,17 +75,14 @@ public class BasicAuthenticator extends AuthenticatorBase {
 
 
     @Override
-    protected boolean doAuthenticate(Request request, HttpServletResponse response)
-            throws IOException {
+    protected boolean doAuthenticate(Request request, HttpServletResponse response) throws IOException {
 
         if (checkForCachedAuthentication(request, response, true)) {
             return true;
         }
 
         // Validate any credentials already included with this request
-        MessageBytes authorization =
-            request.getCoyoteRequest().getMimeHeaders()
-            .getValue("authorization");
+        MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders().getValue("authorization");
 
         if (authorization != null) {
             authorization.toBytes();
@@ -100,12 +95,10 @@ public class BasicAuthenticator extends AuthenticatorBase {
 
                 Principal principal = context.getRealm().authenticate(username, password);
                 if (principal != null) {
-                    register(request, response, principal,
-                        HttpServletRequest.BASIC_AUTH, username, password);
+                    register(request, response, principal, HttpServletRequest.BASIC_AUTH, username, password);
                     return true;
                 }
-            }
-            catch (IllegalArgumentException iae) {
+            } catch (IllegalArgumentException iae) {
                 if (log.isDebugEnabled()) {
                     log.debug("Invalid Authorization" + iae.getMessage());
                 }
@@ -142,9 +135,8 @@ public class BasicAuthenticator extends AuthenticatorBase {
 
 
     /**
-     * Parser for an HTTP Authorization header for BASIC authentication
-     * as per RFC 2617 section 2, and the Base64 encoded credentials as
-     * per RFC 2045 section 6.8.
+     * Parser for an HTTP Authorization header for BASIC authentication as per RFC 2617 section 2, and the Base64
+     * encoded credentials as per RFC 2045 section 6.8.
      */
     public static class BasicCredentials {
 
@@ -163,16 +155,14 @@ public class BasicAuthenticator extends AuthenticatorBase {
         private String password = null;
 
         /**
-         * Parse the HTTP Authorization header for BASIC authentication
-         * as per RFC 2617 section 2, and the Base64 encoded credentials
-         * as per RFC 2045 section 6.8.
+         * Parse the HTTP Authorization header for BASIC authentication as per RFC 2617 section 2, and the Base64
+         * encoded credentials as per RFC 2045 section 6.8.
          *
          * @param input   The header value to parse in-place
-         * @param charset The character set to use to convert the bytes to a
-         *                string
+         * @param charset The character set to use to convert the bytes to a string
+         *
+         * @throws IllegalArgumentException If the header does not conform to RFC 2617
          *
-         * @throws IllegalArgumentException If the header does not conform
-         *                                  to RFC 2617
          * @deprecated Unused. Will be removed in Tomcat 10. Use 3-arg constructor
          */
         @Deprecated
@@ -181,18 +171,14 @@ public class BasicAuthenticator extends AuthenticatorBase {
         }
 
         /**
-         * Parse the HTTP Authorization header for BASIC authentication
-         * as per RFC 2617 section 2, and the Base64 encoded credentials
-         * as per RFC 2045 section 6.8.
+         * Parse the HTTP Authorization header for BASIC authentication as per RFC 2617 section 2, and the Base64
+         * encoded credentials as per RFC 2045 section 6.8.
          *
          * @param input           The header value to parse in-place
-         * @param charset         The character set to use to convert the bytes
-         *                        to a string
-         * @param trimCredentials Should leading and trailing whitespace be
-         *                        removed from the parsed credentials
+         * @param charset         The character set to use to convert the bytes to a string
+         * @param trimCredentials Should leading and trailing whitespace be removed from the parsed credentials
          *
-         * @throws IllegalArgumentException If the header does not conform
-         *                                  to RFC 2617
+         * @throws IllegalArgumentException If the header does not conform to RFC 2617
          */
         public BasicCredentials(ByteChunk input, Charset charset, boolean trimCredentials)
                 throws IllegalArgumentException {
@@ -209,8 +195,7 @@ public class BasicAuthenticator extends AuthenticatorBase {
         /**
          * Trivial accessor.
          *
-         * @return  the decoded username token as a String, which is
-         *          never be <code>null</code>, but can be empty.
+         * @return the decoded username token as a String, which is never be <code>null</code>, but can be empty.
          */
         public String getUsername() {
             return username;
@@ -219,16 +204,15 @@ public class BasicAuthenticator extends AuthenticatorBase {
         /**
          * Trivial accessor.
          *
-         * @return  the decoded password token as a String, or <code>null</code>
-         *          if no password was found in the credentials.
+         * @return the decoded password token as a String, or <code>null</code> if no password was found in the
+         *             credentials.
          */
         public String getPassword() {
             return password;
         }
 
         /*
-         * The authorization method string is case-insensitive and must
-         * hae at least one space character as a delimiter.
+         * The authorization method string is case-insensitive and must hae at least one space character as a delimiter.
          */
         private void parseMethod() throws IllegalArgumentException {
             if (authorization.startsWithIgnoreCase(METHOD, 0)) {
@@ -237,35 +221,30 @@ public class BasicAuthenticator extends AuthenticatorBase {
                 base64blobLength = authorization.getLength() - METHOD.length();
             } else {
                 // is this possible, or permitted?
-                throw new IllegalArgumentException(
-                        "Authorization header method is not \"Basic\"");
+                throw new IllegalArgumentException("Authorization header method is not \"Basic\"");
             }
         }
+
         /*
-         * Decode the base64-user-pass token, which RFC 2617 states
-         * can be longer than the 76 characters per line limit defined
-         * in RFC 2045. The base64 decoder will ignore embedded line
-         * break characters as well as surplus surrounding white space.
+         * Decode the base64-user-pass token, which RFC 2617 states can be longer than the 76 characters per line limit
+         * defined in RFC 2045. The base64 decoder will ignore embedded line break characters as well as surplus
+         * surrounding white space.
          */
         private byte[] parseBase64() throws IllegalArgumentException {
-            byte[] decoded = Base64.decodeBase64(
-                        authorization.getBuffer(),
-                        base64blobOffset, base64blobLength);
-            //  restore original offset
+            byte[] decoded = Base64.decodeBase64(authorization.getBuffer(), base64blobOffset, base64blobLength);
+            // restore original offset
             authorization.setOffset(initialOffset);
             if (decoded == null) {
-                throw new IllegalArgumentException(
-                        "Basic Authorization credentials are not Base64");
+                throw new IllegalArgumentException("Basic Authorization credentials are not Base64");
             }
             return decoded;
         }
 
         /*
-         * Extract the mandatory username token and separate it from the
-         * optional password token. Tolerate surplus surrounding white space.
+         * Extract the mandatory username token and separate it from the optional password token. Tolerate surplus
+         * surrounding white space.
          */
-        private void parseCredentials(byte[] decoded)
-                throws IllegalArgumentException {
+        private void parseCredentials(byte[] decoded) throws IllegalArgumentException {
 
             int colon = -1;
             for (int i = 0; i < decoded.length; i++) {
diff --git a/java/org/apache/catalina/authenticator/Constants.java b/java/org/apache/catalina/authenticator/Constants.java
index 3b649f8ebf..b6bfd8f914 100644
--- a/java/org/apache/catalina/authenticator/Constants.java
+++ b/java/org/apache/catalina/authenticator/Constants.java
@@ -36,15 +36,14 @@ public class Constants {
     public static final String DEFAULT_LOGIN_MODULE_NAME = "com.sun.security.jgss.krb5.accept";
 
     // Cookie name for single sign on support
-    public static final String SINGLE_SIGN_ON_COOKIE = System.getProperty(
-            "org.apache.catalina.authenticator.Constants.SSO_SESSION_COOKIE_NAME", "JSESSIONIDSSO");
+    public static final String SINGLE_SIGN_ON_COOKIE = System
+            .getProperty("org.apache.catalina.authenticator.Constants.SSO_SESSION_COOKIE_NAME", "JSESSIONIDSSO");
 
 
     // --------------------------------------------------------- Request Notes
 
     /**
-     * The notes key to track the single-sign-on identity with which this
-     * request is associated.
+     * The notes key to track the single-sign-on identity with which this request is associated.
      */
     public static final String REQ_SSOID_NOTE = "org.apache.catalina.request.SSOID";
 
@@ -60,18 +59,16 @@ public class Constants {
 
 
     /**
-     * If the <code>cache</code> property of the authenticator is set, and the
-     * current request is part of a session, the password used to authenticate
-     * this user will be cached under this key to avoid the need for repeated
-     * calls to <code>Realm.authenticate()</code>.
+     * If the <code>cache</code> property of the authenticator is set, and the current request is part of a session, the
+     * password used to authenticate this user will be cached under this key to avoid the need for repeated calls to
+     * <code>Realm.authenticate()</code>.
      */
     public static final String SESS_PASSWORD_NOTE = "org.apache.catalina.session.PASSWORD";
 
     /**
-     * If the <code>cache</code> property of the authenticator is set, and the
-     * current request is part of a session, the user name used to authenticate
-     * this user will be cached under this key to avoid the need for repeated
-     * calls to <code>Realm.authenticate()</code>.
+     * If the <code>cache</code> property of the authenticator is set, and the current request is part of a session, the
+     * user name used to authenticate this user will be cached under this key to avoid the need for repeated calls to
+     * <code>Realm.authenticate()</code>.
      */
     public static final String SESS_USERNAME_NOTE = "org.apache.catalina.session.USERNAME";
 
@@ -85,9 +82,8 @@ public class Constants {
     public static final String FORM_PRINCIPAL_NOTE = "org.apache.catalina.authenticator.PRINCIPAL";
 
     /**
-     * The original request information, to which the user will be redirected if
-     * authentication succeeds, is cached in the notes under this key during the
-     * authentication process.
+     * The original request information, to which the user will be redirected if authentication succeeds, is cached in
+     * the notes under this key during the authentication process.
      */
     public static final String FORM_REQUEST_NOTE = "org.apache.catalina.authenticator.REQUEST";
 }
diff --git a/java/org/apache/catalina/authenticator/DigestAuthenticator.java b/java/org/apache/catalina/authenticator/DigestAuthenticator.java
index 1ccf62dcfa..e43fabd244 100644
--- a/java/org/apache/catalina/authenticator/DigestAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/DigestAuthenticator.java
@@ -38,8 +38,7 @@ import org.apache.tomcat.util.security.MD5Encoder;
 
 
 /**
- * An <b>Authenticator</b> and <b>Valve</b> implementation of HTTP DIGEST
- * Authentication (see RFC 2069).
+ * An <b>Authenticator</b> and <b>Valve</b> implementation of HTTP DIGEST Authentication (see RFC 2069).
  *
  * @author Craig R. McClanahan
  * @author Remy Maucherat
@@ -70,27 +69,25 @@ public class DigestAuthenticator extends AuthenticatorBase {
     /**
      * List of server nonce values currently being tracked
      */
-    protected Map<String,NonceInfo> nonces;
+    protected Map<String, NonceInfo> nonces;
 
 
     /**
-     * The last timestamp used to generate a nonce. Each nonce should get a
-     * unique timestamp.
+     * The last timestamp used to generate a nonce. Each nonce should get a unique timestamp.
      */
     protected long lastTimestamp = 0;
     protected final Object lastTimestampLock = new Object();
 
 
     /**
-     * Maximum number of server nonces to keep in the cache. If not specified,
-     * the default value of 1000 is used.
+     * Maximum number of server nonces to keep in the cache. If not specified, the default value of 1000 is used.
      */
     protected int nonceCacheSize = 1000;
 
 
     /**
-     * The window size to use to track seen nonce count values for a given
-     * nonce. If not specified, the default of 100 is used.
+     * The window size to use to track seen nonce count values for a given nonce. If not specified, the default of 100
+     * is used.
      */
     protected int nonceCountWindowSize = 100;
 
@@ -101,8 +98,7 @@ public class DigestAuthenticator extends AuthenticatorBase {
 
 
     /**
-     * How long server nonces are valid for in milliseconds. Defaults to 5
-     * minutes.
+     * How long server nonces are valid for in milliseconds. Defaults to 5 minutes.
      */
     protected long nonceValidity = 5 * 60 * 1000;
 
@@ -114,8 +110,8 @@ public class DigestAuthenticator extends AuthenticatorBase {
 
 
     /**
-     * Should the URI be validated as required by RFC2617? Can be disabled in
-     * reverse proxies where the proxy has modified the URI.
+     * Should the URI be validated as required by RFC2617? Can be disabled in reverse proxies where the proxy has
+     * modified the URI.
      */
     protected boolean validateUri = true;
 
@@ -184,19 +180,17 @@ public class DigestAuthenticator extends AuthenticatorBase {
     // --------------------------------------------------------- Public Methods
 
     /**
-     * Authenticate the user making this request, based on the specified
-     * login configuration.  Return <code>true</code> if any specified
-     * constraint has been satisfied, or <code>false</code> if we have
-     * created a response challenge already.
+     * Authenticate the user making this request, based on the specified login configuration. Return <code>true</code>
+     * if any specified constraint has been satisfied, or <code>false</code> if we have created a response challenge
+     * already.
      *
-     * @param request Request we are processing
+     * @param request  Request we are processing
      * @param response Response we are creating
      *
      * @exception IOException if an input/output error occurs
      */
     @Override
-    protected boolean doAuthenticate(Request request, HttpServletResponse response)
-            throws IOException {
+    protected boolean doAuthenticate(Request request, HttpServletResponse response) throws IOException {
 
         // NOTE: We don't try to reauthenticate using any existing SSO session,
         // because that will only work if the original authentication was
@@ -213,8 +207,7 @@ public class DigestAuthenticator extends AuthenticatorBase {
         // Validate any credentials already included with this request
         Principal principal = null;
         String authorization = request.getHeader("authorization");
-        DigestInfo digestInfo = new DigestInfo(getOpaque(), getNonceValidity(),
-                getKey(), nonces, isValidateUri());
+        DigestInfo digestInfo = new DigestInfo(getOpaque(), getNonceValidity(), getKey(), nonces, isValidateUri());
         if (authorization != null) {
             if (digestInfo.parse(request, authorization)) {
                 if (digestInfo.validate(request)) {
@@ -222,9 +215,8 @@ public class DigestAuthenticator extends AuthenticatorBase {
                 }
 
                 if (principal != null && !digestInfo.isNonceStale()) {
-                    register(request, response, principal,
-                            HttpServletRequest.DIGEST_AUTH,
-                            digestInfo.getUsername(), null);
+                    register(request, response, principal, HttpServletRequest.DIGEST_AUTH, digestInfo.getUsername(),
+                            null);
                     return true;
                 }
             }
@@ -236,8 +228,7 @@ public class DigestAuthenticator extends AuthenticatorBase {
         // to be unique).
         String nonce = generateNonce(request);
 
-        setAuthenticateHeader(request, response, nonce,
-                principal != null && digestInfo.isNonceStale());
+        setAuthenticateHeader(request, response, nonce, principal != null && digestInfo.isNonceStale());
         response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
         return false;
     }
@@ -253,18 +244,16 @@ public class DigestAuthenticator extends AuthenticatorBase {
 
 
     /**
-     * Removes the quotes on a string. RFC2617 states quotes are optional for
-     * all parameters except realm.
+     * Removes the quotes on a string. RFC2617 states quotes are optional for all parameters except realm.
      *
-     * @param quotedString The quoted string
+     * @param quotedString   The quoted string
      * @param quotesRequired <code>true</code> if quotes were required
+     *
      * @return The unquoted string
      */
-    protected static String removeQuotes(String quotedString,
-                                         boolean quotesRequired) {
-        //support both quoted and non-quoted
-        if (quotedString.length() > 0 && quotedString.charAt(0) != '"' &&
-                !quotesRequired) {
+    protected static String removeQuotes(String quotedString, boolean quotesRequired) {
+        // support both quoted and non-quoted
+        if (quotedString.length() > 0 && quotedString.charAt(0) != '"' && !quotesRequired) {
             return quotedString;
         } else if (quotedString.length() > 2) {
             return quotedString.substring(1, quotedString.length() - 1);
@@ -277,6 +266,7 @@ public class DigestAuthenticator extends AuthenticatorBase {
      * Removes the quotes on a string.
      *
      * @param quotedString The quoted string
+     *
      * @return The unquoted string
      */
     protected static String removeQuotes(String quotedString) {
@@ -284,11 +274,11 @@ public class DigestAuthenticator extends AuthenticatorBase {
     }
 
     /**
-     * Generate a unique token. The token is generated according to the
-     * following pattern. NOnceToken = Base64 ( MD5 ( client-IP ":"
-     * time-stamp ":" private-key ) ).
+     * Generate a unique token. The token is generated according to the following pattern. NOnceToken = Base64 ( MD5 (
+     * client-IP ":" time-stamp ":" private-key ) ).
      *
      * @param request HTTP Servlet request
+     *
      * @return The generated nonce
      */
     protected String generateNonce(Request request) {
@@ -303,11 +293,9 @@ public class DigestAuthenticator extends AuthenticatorBase {
             }
         }
 
-        String ipTimeKey =
-            request.getRemoteAddr() + ":" + currentTime + ":" + getKey();
+        String ipTimeKey = request.getRemoteAddr() + ":" + currentTime + ":" + getKey();
 
-        byte[] buffer = ConcurrentMessageDigest.digestMD5(
-                ipTimeKey.getBytes(StandardCharsets.ISO_8859_1));
+        byte[] buffer = ConcurrentMessageDigest.digestMD5(ipTimeKey.getBytes(StandardCharsets.ISO_8859_1));
         String nonce = currentTime + ":" + MD5Encoder.encode(buffer);
 
         NonceInfo info = new NonceInfo(currentTime, getNonceCountWindowSize());
@@ -323,6 +311,7 @@ public class DigestAuthenticator extends AuthenticatorBase {
      * Generates the WWW-Authenticate header.
      * <p>
      * The header MUST follow this template :
+     *
      * <pre>
      *      WWW-Authenticate    = "WWW-Authenticate" ":" "Digest"
      *                            digest-challenge
@@ -340,27 +329,23 @@ public class DigestAuthenticator extends AuthenticatorBase {
      *      algorithm           = "algorithm" "=" ( "MD5" | token )
      * </pre>
      *
-     * @param request HTTP Servlet request
-     * @param response HTTP Servlet response
-     * @param nonce nonce token
+     * @param request      HTTP Servlet request
+     * @param response     HTTP Servlet response
+     * @param nonce        nonce token
      * @param isNonceStale <code>true</code> to add a stale parameter
      */
-    protected void setAuthenticateHeader(HttpServletRequest request,
-                                         HttpServletResponse response,
-                                         String nonce,
-                                         boolean isNonceStale) {
+    protected void setAuthenticateHeader(HttpServletRequest request, HttpServletResponse response, String nonce,
+            boolean isNonceStale) {
 
         String realmName = getRealmName(context);
 
         String authenticateHeader;
         if (isNonceStale) {
-            authenticateHeader = "Digest realm=\"" + realmName + "\", " +
-                    "qop=\"" + QOP + "\", nonce=\"" + nonce + "\", " + "opaque=\"" +
-            getOpaque() + "\", stale=true";
+            authenticateHeader = "Digest realm=\"" + realmName + "\", " + "qop=\"" + QOP + "\", nonce=\"" + nonce +
+                    "\", " + "opaque=\"" + getOpaque() + "\", stale=true";
         } else {
-            authenticateHeader = "Digest realm=\"" + realmName + "\", " +
-                    "qop=\"" + QOP + "\", nonce=\"" + nonce + "\", " + "opaque=\"" +
-            getOpaque() + "\"";
+            authenticateHeader = "Digest realm=\"" + realmName + "\", " + "qop=\"" + QOP + "\", nonce=\"" + nonce +
+                    "\", " + "opaque=\"" + getOpaque() + "\"";
         }
 
         response.setHeader(AUTH_HEADER_NAME, authenticateHeader);
@@ -399,17 +384,13 @@ public class DigestAuthenticator extends AuthenticatorBase {
             private long lastLog = 0;
 
             @Override
-            protected boolean removeEldestEntry(
-                    Map.Entry<String,NonceInfo> eldest) {
+            protected boolean removeEldestEntry(Map.Entry<String, NonceInfo> eldest) {
                 // This is called from a sync so keep it simple
                 long currentTime = System.currentTimeMillis();
                 if (size() > getNonceCacheSize()) {
-                    if (lastLog < currentTime &&
-                            currentTime - eldest.getValue().getTimestamp() <
-                            getNonceValidity()) {
+                    if (lastLog < currentTime && currentTime - eldest.getValue().getTimestamp() < getNonceValidity()) {
                         // Replay attack is possible
-                        log.warn(sm.getString(
-                                "digestAuthenticator.cacheRemove"));
+                        log.warn(sm.getString("digestAuthenticator.cacheRemove"));
                         lastLog = currentTime + LOG_SUPPRESS_TIME;
                     }
                     return true;
@@ -424,7 +405,7 @@ public class DigestAuthenticator extends AuthenticatorBase {
         private final String opaque;
         private final long nonceValidity;
         private final String key;
-        private final Map<String,NonceInfo> nonces;
+        private final Map<String, NonceInfo> nonces;
         private boolean validateUri = true;
 
         private String userName = null;
@@ -441,8 +422,8 @@ public class DigestAuthenticator extends AuthenticatorBase {
         private boolean nonceStale = false;
 
 
-        public DigestInfo(String opaque, long nonceValidity, String key,
-                Map<String,NonceInfo> nonces, boolean validateUri) {
+        public DigestInfo(String opaque, long nonceValidity, String key, Map<String, NonceInfo> nonces,
+                boolean validateUri) {
             this.opaque = opaque;
             this.nonceValidity = nonceValidity;
             this.key = key;
@@ -462,10 +443,9 @@ public class DigestAuthenticator extends AuthenticatorBase {
                 return false;
             }
 
-            Map<String,String> directives;
+            Map<String, String> directives;
             try {
-                directives = Authorization.parseAuthorizationDigest(
-                        new StringReader(authorization));
+                directives = Authorization.parseAuthorizationDigest(new StringReader(authorization));
             } catch (IOException e) {
                 return false;
             }
@@ -489,8 +469,7 @@ public class DigestAuthenticator extends AuthenticatorBase {
         }
 
         public boolean validate(Request request) {
-            if ( (userName == null) || (realmName == null) || (nonce == null)
-                 || (uri == null) || (response == null) ) {
+            if ((userName == null) || (realmName == null) || (nonce == null) || (uri == null) || (response == null)) {
                 return false;
             }
 
@@ -554,10 +533,8 @@ public class DigestAuthenticator extends AuthenticatorBase {
                     nonces.remove(nonce);
                 }
             }
-            String serverIpTimeKey =
-                request.getRemoteAddr() + ":" + nonceTime + ":" + key;
-            byte[] buffer = ConcurrentMessageDigest.digestMD5(
-                    serverIpTimeKey.getBytes(StandardCharsets.ISO_8859_1));
+            String serverIpTimeKey = request.getRemoteAddr() + ":" + nonceTime + ":" + key;
+            byte[] buffer = ConcurrentMessageDigest.digestMD5(serverIpTimeKey.getBytes(StandardCharsets.ISO_8859_1));
             String md5ServerIpTimeKey = MD5Encoder.encode(buffer);
             if (!md5ServerIpTimeKey.equals(md5clientIpTimeKey)) {
                 return false;
@@ -615,12 +592,10 @@ public class DigestAuthenticator extends AuthenticatorBase {
             // MD5(Method + ":" + uri)
             String a2 = method + ":" + uri;
 
-            byte[] buffer = ConcurrentMessageDigest.digestMD5(
-                    a2.getBytes(StandardCharsets.ISO_8859_1));
+            byte[] buffer = ConcurrentMessageDigest.digestMD5(a2.getBytes(StandardCharsets.ISO_8859_1));
             String md5a2 = MD5Encoder.encode(buffer);
 
-            return realm.authenticate(userName, response, nonce, nc, cnonce,
-                    qop, realmName, md5a2);
+            return realm.authenticate(userName, response, nonce, nc, cnonce, qop, realmName, md5a2);
         }
 
     }
@@ -638,8 +613,7 @@ public class DigestAuthenticator extends AuthenticatorBase {
         }
 
         public synchronized boolean nonceCountValid(long nonceCount) {
-            if ((count - offset) >= nonceCount ||
-                    (nonceCount > count - offset + seen.length)) {
+            if ((count - offset) >= nonceCount || (nonceCount > count - offset + seen.length)) {
                 return false;
             }
             int checkIndex = (int) ((nonceCount + offset) % seen.length);
diff --git a/java/org/apache/catalina/authenticator/FormAuthenticator.java b/java/org/apache/catalina/authenticator/FormAuthenticator.java
index 7a5dfca930..cdc357c118 100644
--- a/java/org/apache/catalina/authenticator/FormAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/FormAuthenticator.java
@@ -43,14 +43,13 @@ import org.apache.tomcat.util.descriptor.web.LoginConfig;
 import org.apache.tomcat.util.http.MimeHeaders;
 
 /**
- * An <b>Authenticator</b> and <b>Valve</b> implementation of FORM BASED
- * Authentication, as described in the Servlet API Specification.
+ * An <b>Authenticator</b> and <b>Valve</b> implementation of FORM BASED Authentication, as described in the Servlet API
+ * Specification.
  *
  * @author Craig R. McClanahan
  * @author Remy Maucherat
  */
-public class FormAuthenticator
-    extends AuthenticatorBase {
+public class FormAuthenticator extends AuthenticatorBase {
 
     private final Log log = LogFactory.getLog(FormAuthenticator.class); // must not be static
 
@@ -58,16 +57,14 @@ public class FormAuthenticator
     // ----------------------------------------------------- Instance Variables
 
     /**
-     * Character encoding to use to read the username and password parameters
-     * from the request. If not set, the encoding of the request body will be
-     * used.
+     * Character encoding to use to read the username and password parameters from the request. If not set, the encoding
+     * of the request body will be used.
      */
     protected String characterEncoding = null;
 
     /**
-     * Landing page to use if a user tries to access the login page directly or
-     * if the session times out during login. If not set, error responses will
-     * be sent instead.
+     * Landing page to use if a user tries to access the login page directly or if the session times out during login.
+     * If not set, error responses will be sent instead.
      */
     protected String landingPage = null;
 
@@ -107,8 +104,7 @@ public class FormAuthenticator
     /**
      * Set the landing page to use when the FORM auth is mis-used.
      *
-     * @param landingPage The path to the landing page relative to the web
-     *                    application root
+     * @param landingPage The path to the landing page relative to the web application root
      */
     public void setLandingPage(String landingPage) {
         this.landingPage = landingPage;
@@ -119,19 +115,17 @@ public class FormAuthenticator
 
 
     /**
-     * Authenticate the user making this request, based on the specified
-     * login configuration.  Return <code>true</code> if any specified
-     * constraint has been satisfied, or <code>false</code> if we have
-     * created a response challenge already.
+     * Authenticate the user making this request, based on the specified login configuration. Return <code>true</code>
+     * if any specified constraint has been satisfied, or <code>false</code> if we have created a response challenge
+     * already.
      *
-     * @param request Request we are processing
+     * @param request  Request we are processing
      * @param response Response we are creating
      *
      * @exception IOException if an input/output error occurs
      */
     @Override
-    protected boolean doAuthenticate(Request request, HttpServletResponse response)
-            throws IOException {
+    protected boolean doAuthenticate(Request request, HttpServletResponse response) throws IOException {
 
         // References to objects we will need later
         Session session = null;
@@ -163,7 +157,7 @@ public class FormAuthenticator
         }
 
         // Is this the re-submit of the original request URI after successful
-        // authentication?  If so, forward the *original* request instead.
+        // authentication? If so, forward the *original* request instead.
         if (matchRequest(request)) {
             session = request.getSessionInternal(true);
             if (log.isDebugEnabled()) {
@@ -270,8 +264,8 @@ public class FormAuthenticator
                 containerLog.debug("User took so long to log on the session expired");
             }
             if (landingPage == null) {
-                response.sendError(
-                        HttpServletResponse.SC_REQUEST_TIMEOUT, sm.getString("authenticator.sessionExpired"));
+                response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT,
+                        sm.getString("authenticator.sessionExpired"));
             } else {
                 // Make the authenticator think the user originally requested
                 // the landing page
@@ -330,8 +324,7 @@ public class FormAuthenticator
         // to which it submits) might be outside the secured area
         String contextPath = this.context.getPath();
         String decodedRequestURI = request.getDecodedRequestURI();
-        if (decodedRequestURI.startsWith(contextPath) &&
-                decodedRequestURI.endsWith(Constants.FORM_ACTION)) {
+        if (decodedRequestURI.startsWith(contextPath) && decodedRequestURI.endsWith(Constants.FORM_ACTION)) {
             return true;
         }
 
@@ -344,8 +337,7 @@ public class FormAuthenticator
         Session session = request.getSessionInternal(false);
         if (session != null) {
             SavedRequest savedRequest = (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
-            if (savedRequest != null &&
-                    decodedRequestURI.equals(savedRequest.getDecodedRequestURI())) {
+            if (savedRequest != null && decodedRequestURI.equals(savedRequest.getDecodedRequestURI())) {
                 return true;
             }
         }
@@ -361,9 +353,8 @@ public class FormAuthenticator
 
 
     @Override
-    protected void register(Request request, HttpServletResponse response,
-            Principal principal, String authType, String username,
-            String password, boolean alwaysUseSession, boolean cache) {
+    protected void register(Request request, HttpServletResponse response, Principal principal, String authType,
+            String username, String password, boolean alwaysUseSession, boolean cache) {
 
         super.register(request, response, principal, authType, username, password, alwaysUseSession, cache);
 
@@ -390,31 +381,26 @@ public class FormAuthenticator
     /**
      * Called to forward to the login page
      *
-     * @param request Request we are processing
+     * @param request  Request we are processing
      * @param response Response we are populating
-     * @param config    Login configuration describing how authentication
-     *              should be performed
-     * @throws IOException  If the forward to the login page fails and the call
-     *                      to {@link HttpServletResponse#sendError(int, String)}
-     *                      throws an {@link IOException}
+     * @param config   Login configuration describing how authentication should be performed
+     *
+     * @throws IOException If the forward to the login page fails and the call to
+     *                         {@link HttpServletResponse#sendError(int, String)} throws an {@link IOException}
      */
-    protected void forwardToLoginPage(Request request,
-            HttpServletResponse response, LoginConfig config)
+    protected void forwardToLoginPage(Request request, HttpServletResponse response, LoginConfig config)
             throws IOException {
 
         if (log.isDebugEnabled()) {
-            log.debug(sm.getString("formAuthenticator.forwardLogin",
-                    request.getRequestURI(), request.getMethod(),
+            log.debug(sm.getString("formAuthenticator.forwardLogin", request.getRequestURI(), request.getMethod(),
                     config.getLoginPage(), context.getName()));
         }
 
         String loginPage = config.getLoginPage();
         if (loginPage == null || loginPage.length() == 0) {
-            String msg = sm.getString("formAuthenticator.noLoginPage",
-                    context.getName());
+            String msg = sm.getString("formAuthenticator.noLoginPage", context.getName());
             log.warn(msg);
-            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
-                    msg);
+            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
             return;
         }
 
@@ -434,8 +420,7 @@ public class FormAuthenticator
         String oldMethod = request.getMethod();
         request.getCoyoteRequest().method().setString("GET");
 
-        RequestDispatcher disp =
-            context.getServletContext().getRequestDispatcher(loginPage);
+        RequestDispatcher disp = context.getServletContext().getRequestDispatcher(loginPage);
         try {
             if (context.fireRequestInitEvent(request.getRequest())) {
                 disp.forward(request.getRequest(), response);
@@ -446,8 +431,7 @@ public class FormAuthenticator
             String msg = sm.getString("formAuthenticator.forwardLoginFail");
             log.warn(msg, t);
             request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t);
-            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
-                    msg);
+            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
         } finally {
             // Restore original method so that it is written into access log
             request.getCoyoteRequest().method().setString(oldMethod);
@@ -458,30 +442,25 @@ public class FormAuthenticator
     /**
      * Called to forward to the error page
      *
-     * @param request Request we are processing
+     * @param request  Request we are processing
      * @param response Response we are populating
-     * @param config    Login configuration describing how authentication
-     *              should be performed
-     * @throws IOException  If the forward to the error page fails and the call
-     *                      to {@link HttpServletResponse#sendError(int, String)}
-     *                      throws an {@link IOException}
+     * @param config   Login configuration describing how authentication should be performed
+     *
+     * @throws IOException If the forward to the error page fails and the call to
+     *                         {@link HttpServletResponse#sendError(int, String)} throws an {@link IOException}
      */
-    protected void forwardToErrorPage(Request request,
-            HttpServletResponse response, LoginConfig config)
+    protected void forwardToErrorPage(Request request, HttpServletResponse response, LoginConfig config)
             throws IOException {
 
         String errorPage = config.getErrorPage();
         if (errorPage == null || errorPage.length() == 0) {
-            String msg = sm.getString("formAuthenticator.noErrorPage",
-                    context.getName());
+            String msg = sm.getString("formAuthenticator.noErrorPage", context.getName());
             log.warn(msg);
-            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
-                    msg);
+            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
             return;
         }
 
-        RequestDispatcher disp =
-                context.getServletContext().getRequestDispatcher(config.getErrorPage());
+        RequestDispatcher disp = context.getServletContext().getRequestDispatcher(config.getErrorPage());
         try {
             if (context.fireRequestInitEvent(request.getRequest())) {
                 disp.forward(request.getRequest(), response);
@@ -492,17 +471,17 @@ public class FormAuthenticator
             String msg = sm.getString("formAuthenticator.forwardErrorFail");
             log.warn(msg, t);
             request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t);
-            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
-                    msg);
+            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
         }
     }
 
 
     /**
-     * Does this request match the saved one (so that it must be the redirect
-     * we signaled after successful authentication?
+     * Does this request match the saved one (so that it must be the redirect we signaled after successful
+     * authentication?
      *
      * @param request The request to be verified
+     *
      * @return <code>true</code> if the requests matched the saved one
      */
     protected boolean matchRequest(Request request) {
@@ -541,18 +520,17 @@ public class FormAuthenticator
 
 
     /**
-     * Restore the original request from information stored in our session.
-     * If the original request is no longer present (because the session
-     * timed out), return <code>false</code>; otherwise, return
-     * <code>true</code>.
+     * Restore the original request from information stored in our session. If the original request is no longer present
+     * (because the session timed out), return <code>false</code>; otherwise, return <code>true</code>.
      *
      * @param request The request to be restored
      * @param session The session containing the saved information
+     *
      * @return <code>true</code> if the request was successfully restored
+     *
      * @throws IOException if an IO error occurred during the process
      */
-    protected boolean restoreRequest(Request request, Session session)
-            throws IOException {
+    protected boolean restoreRequest(Request request, Session session) throws IOException {
 
         // Retrieve and remove the SavedRequest object from our session
         SavedRequest saved = (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
@@ -582,16 +560,15 @@ public class FormAuthenticator
         String method = saved.getMethod();
         MimeHeaders rmh = request.getCoyoteRequest().getMimeHeaders();
         rmh.recycle();
-        boolean cacheable = "GET".equalsIgnoreCase(method) ||
-                           "HEAD".equalsIgnoreCase(method);
+        boolean cacheable = "GET".equalsIgnoreCase(method) || "HEAD".equalsIgnoreCase(method);
         Iterator<String> names = saved.getHeaderNames();
         while (names.hasNext()) {
             String name = names.next();
             // The browser isn't expecting this conditional response now.
             // Assuming that it can quietly recover from an unexpected 412.
             // BZ 43687
-            if(!("If-Modified-Since".equalsIgnoreCase(name) ||
-                 (cacheable && "If-None-Match".equalsIgnoreCase(name)))) {
+            if (!("If-Modified-Since".equalsIgnoreCase(name) ||
+                    (cacheable && "If-None-Match".equalsIgnoreCase(name)))) {
                 Iterator<String> values = saved.getHeaderValues(name);
                 while (values.hasNext()) {
                     rmh.addValue(name).setString(values.next());
@@ -610,8 +587,7 @@ public class FormAuthenticator
         ByteChunk body = saved.getBody();
 
         if (body != null) {
-            request.getCoyoteRequest().action
-                (ActionCode.REQ_SET_BODY_REPLAY, body);
+            request.getCoyoteRequest().action(ActionCode.REQ_SET_BODY_REPLAY, body);
 
             // Set content type
             MessageBytes contentType = MessageBytes.newInstance();
@@ -649,10 +625,10 @@ public class FormAuthenticator
      *
      * @param request The request to be saved
      * @param session The session to contain the saved information
+     *
      * @throws IOException if an IO error occurred during the process
      */
-    protected void saveRequest(Request request, Session session)
-        throws IOException {
+    protected void saveRequest(Request request, Session session) throws IOException {
 
         // Create and populate a SavedRequest object for this request
         SavedRequest saved = new SavedRequest();
@@ -689,7 +665,7 @@ public class FormAuthenticator
             int bytesRead;
             InputStream is = request.getInputStream();
 
-            while ( (bytesRead = is.read(buffer) ) >= 0) {
+            while ((bytesRead = is.read(buffer)) >= 0) {
                 body.append(buffer, 0, bytesRead);
             }
 
@@ -711,15 +687,15 @@ public class FormAuthenticator
 
 
     /**
-     * Return the request URI (with the corresponding query string, if any)
-     * from the saved request so that we can redirect to it.
+     * Return the request URI (with the corresponding query string, if any) from the saved request so that we can
+     * redirect to it.
      *
      * @param session Our current session
+     *
      * @return the original request URL
      */
     protected String savedRequestURL(Session session) {
-        SavedRequest saved =
-            (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
+        SavedRequest saved = (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
         if (saved == null) {
             return null;
         }
diff --git a/java/org/apache/catalina/authenticator/NonLoginAuthenticator.java b/java/org/apache/catalina/authenticator/NonLoginAuthenticator.java
index be6403af47..db9133f475 100644
--- a/java/org/apache/catalina/authenticator/NonLoginAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/NonLoginAuthenticator.java
@@ -23,8 +23,8 @@ import javax.servlet.http.HttpServletResponse;
 import org.apache.catalina.connector.Request;
 
 /**
- * An <b>Authenticator</b> and <b>Valve</b> implementation that checks
- * only security constraints not involving user authentication.
+ * An <b>Authenticator</b> and <b>Valve</b> implementation that checks only security constraints not involving user
+ * authentication.
  *
  * @author Craig R. McClanahan
  */
@@ -35,47 +35,44 @@ public final class NonLoginAuthenticator extends AuthenticatorBase {
 
 
     /**
-     * <p>Authenticate the user making this request, based on the fact that no
-     * <code>login-config</code> has been defined for the container.</p>
-     *
-     * <p>This implementation means "login the user even though there is no
-     * self-contained way to establish a security Principal for that user".</p>
-     *
-     * <p>This method is called by the AuthenticatorBase super class to
-     * establish a Principal for the user BEFORE the container security
-     * constraints are examined, i.e. it is not yet known whether the user
-     * will eventually be permitted to access the requested resource.
-     * Therefore, it is necessary to always return <code>true</code> to
-     * indicate the user has not failed authentication.</p>
-     *
-     * <p>There are two cases:</p>
+     * <p>
+     * Authenticate the user making this request, based on the fact that no <code>login-config</code> has been defined
+     * for the container.
+     * </p>
+     * <p>
+     * This implementation means "login the user even though there is no self-contained way to establish a security
+     * Principal for that user".
+     * </p>
+     * <p>
+     * This method is called by the AuthenticatorBase super class to establish a Principal for the user BEFORE the
+     * container security constraints are examined, i.e. it is not yet known whether the user will eventually be
+     * permitted to access the requested resource. Therefore, it is necessary to always return <code>true</code> to
+     * indicate the user has not failed authentication.
+     * </p>
+     * <p>
+     * There are two cases:
+     * </p>
      * <ul>
-     * <li>without SingleSignon: a Session instance does not yet exist
-     *     and there is no <code>auth-method</code> to authenticate the
-     *     user, so leave Request's Principal as null.
-     *     Note: AuthenticatorBase will later examine the security constraints
-     *           to determine whether the resource is accessible by a user
-     *           without a security Principal and Role (i.e. unauthenticated).
-     * </li>
-     * <li>with SingleSignon: if the user has already authenticated via
-     *     another container (using its own login configuration), then
-     *     associate this Session with the SSOEntry so it inherits the
-     *     already-established security Principal and associated Roles.
-     *     Note: This particular session will become a full member of the
-     *           SingleSignOnEntry Session collection and so will potentially
-     *           keep the SSOE "alive", even if all the other properly
-     *           authenticated Sessions expire first... until it expires too.
-     * </li>
+     * <li>without SingleSignon: a Session instance does not yet exist and there is no <code>auth-method</code> to
+     * authenticate the user, so leave Request's Principal as null. Note: AuthenticatorBase will later examine the
+     * security constraints to determine whether the resource is accessible by a user without a security Principal and
+     * Role (i.e. unauthenticated).</li>
+     * <li>with SingleSignon: if the user has already authenticated via another container (using its own login
+     * configuration), then associate this Session with the SSOEntry so it inherits the already-established security
+     * Principal and associated Roles. Note: This particular session will become a full member of the SingleSignOnEntry
+     * Session collection and so will potentially keep the SSOE "alive", even if all the other properly authenticated
+     * Sessions expire first... until it expires too.</li>
      * </ul>
      *
      * @param request  Request we are processing
      * @param response Response we are creating
+     *
      * @return boolean to indicate whether the user is authenticated
+     *
      * @exception IOException if an input/output error occurs
      */
     @Override
-    protected boolean doAuthenticate(Request request, HttpServletResponse response)
-        throws IOException {
+    protected boolean doAuthenticate(Request request, HttpServletResponse response) throws IOException {
 
         // Don't try and use SSO to authenticate since there is no auth
         // configured for this web application
@@ -101,8 +98,7 @@ public final class NonLoginAuthenticator extends AuthenticatorBase {
 
 
     /**
-     * Return the authentication method, which is vendor-specific and
-     * not defined by HttpServletRequest.
+     * Return the authentication method, which is vendor-specific and not defined by HttpServletRequest.
      */
     @Override
     protected String getAuthMethod() {
diff --git a/java/org/apache/catalina/authenticator/SSLAuthenticator.java b/java/org/apache/catalina/authenticator/SSLAuthenticator.java
index 0f6955bee1..226312765e 100644
--- a/java/org/apache/catalina/authenticator/SSLAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/SSLAuthenticator.java
@@ -39,8 +39,8 @@ import org.apache.tomcat.util.net.Constants;
 import org.apache.tomcat.util.net.SSLHostConfig;
 
 /**
- * An <b>Authenticator</b> and <b>Valve</b> implementation of authentication
- * that utilizes SSL certificates to identify client users.
+ * An <b>Authenticator</b> and <b>Valve</b> implementation of authentication that utilizes SSL certificates to identify
+ * client users.
  *
  * @author Craig R. McClanahan
  */
@@ -49,18 +49,16 @@ public class SSLAuthenticator extends AuthenticatorBase {
     private final Log log = LogFactory.getLog(SSLAuthenticator.class); // must not be static
 
     /**
-     * Authenticate the user by checking for the existence of a certificate
-     * chain, validating it against the trust manager for the connector and then
-     * validating the user's identity against the configured Realm.
+     * Authenticate the user by checking for the existence of a certificate chain, validating it against the trust
+     * manager for the connector and then validating the user's identity against the configured Realm.
      *
-     * @param request Request we are processing
+     * @param request  Request we are processing
      * @param response Response we are creating
      *
      * @exception IOException if an input/output error occurs
      */
     @Override
-    protected boolean doAuthenticate(Request request, HttpServletResponse response)
-            throws IOException {
+    protected boolean doAuthenticate(Request request, HttpServletResponse response) throws IOException {
 
         // NOTE: We don't try to reauthenticate using any existing SSO session,
         // because that will only work if the original authentication was
@@ -85,8 +83,7 @@ public class SSLAuthenticator extends AuthenticatorBase {
             if (containerLog.isDebugEnabled()) {
                 containerLog.debug("  No certificates included with this request");
             }
-            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
-                    sm.getString("authenticator.certificates"));
+            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, sm.getString("authenticator.certificates"));
             return false;
         }
 
@@ -96,14 +93,12 @@ public class SSLAuthenticator extends AuthenticatorBase {
             if (containerLog.isDebugEnabled()) {
                 containerLog.debug("  Realm.authenticate() returned false");
             }
-            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
-                               sm.getString("authenticator.unauthorized"));
+            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, sm.getString("authenticator.unauthorized"));
             return false;
         }
 
         // Cache the principal (if requested) and record this authentication
-        register(request, response, principal,
-                HttpServletRequest.CLIENT_CERT_AUTH, null, null);
+        register(request, response, principal, HttpServletRequest.CLIENT_CERT_AUTH, null, null);
         return true;
 
     }
@@ -124,19 +119,16 @@ public class SSLAuthenticator extends AuthenticatorBase {
 
     /**
      * Look for the X509 certificate chain in the Request under the key
-     * <code>jakarta.servlet.request.X509Certificate</code>. If not found, trigger
-     * extracting the certificate chain from the Coyote request.
+     * <code>jakarta.servlet.request.X509Certificate</code>. If not found, trigger extracting the certificate chain from
+     * the Coyote request.
      *
-     * @param request
-     *            Request to be processed
+     * @param request Request to be processed
      *
      * @return The X509 certificate chain if found, <code>null</code> otherwise.
      */
-    protected X509Certificate[] getRequestCertificates(final Request request)
-            throws IllegalStateException {
+    protected X509Certificate[] getRequestCertificates(final Request request) throws IllegalStateException {
 
-        X509Certificate certs[] =
-                (X509Certificate[]) request.getAttribute(Globals.CERTIFICATES_ATTR);
+        X509Certificate certs[] = (X509Certificate[]) request.getAttribute(Globals.CERTIFICATES_ATTR);
 
         if ((certs == null) || (certs.length < 1)) {
             try {
@@ -158,9 +150,8 @@ public class SSLAuthenticator extends AuthenticatorBase {
         super.startInternal();
 
         /*
-         * This Valve should only ever be added to a Context and if the Context
-         * is started there should always be a Host and an Engine but test at
-         * each stage to be safe.
+         * This Valve should only ever be added to a Context and if the Context is started there should always be a Host
+         * and an Engine but test at each stage to be safe.
          */
         Container container = getContainer();
         if (!(container instanceof Context)) {
@@ -204,7 +195,8 @@ public class SSLAuthenticator extends AuthenticatorBase {
                     }
                     for (String enbabledProtocol : enabledProtocols) {
                         if (Constants.SSL_PROTO_TLSv1_3.equals(enbabledProtocol)) {
-                            log.warn(sm.getString("sslAuthenticatorValve.tls13", context.getName(), host.getName(), connector));
+                            log.warn(sm.getString("sslAuthenticatorValve.tls13", context.getName(), host.getName(),
+                                    connector));
                         }
                     }
                 }
diff --git a/java/org/apache/catalina/authenticator/SavedRequest.java b/java/org/apache/catalina/authenticator/SavedRequest.java
index d1ca241ec3..a83d88ae88 100644
--- a/java/org/apache/catalina/authenticator/SavedRequest.java
+++ b/java/org/apache/catalina/authenticator/SavedRequest.java
@@ -30,13 +30,11 @@ import javax.servlet.http.Cookie;
 import org.apache.tomcat.util.buf.ByteChunk;
 
 /**
- * Object that saves the critical information from a request so that
- * form-based authentication can reproduce it once the user has been
- * authenticated.
+ * Object that saves the critical information from a request so that form-based authentication can reproduce it once the
+ * user has been authenticated.
  * <p>
- * <b>IMPLEMENTATION NOTE</b> - It is assumed that this object is accessed
- * only from the context of a single thread, so no synchronization around
- * internal collection classes is performed.
+ * <b>IMPLEMENTATION NOTE</b> - It is assumed that this object is accessed only from the context of a single thread, so
+ * no synchronization around internal collection classes is performed.
  *
  * @author Craig R. McClanahan
  */
@@ -59,10 +57,8 @@ public final class SavedRequest implements Serializable {
 
 
     /**
-     * The set of Headers associated with this Request.  Each key is a header
-     * name, while the value is a List containing one or more actual
-     * values for this header.  The values are returned as an Iterator when
-     * you ask for them.
+     * The set of Headers associated with this Request. Each key is a header name, while the value is a List containing
+     * one or more actual values for this header. The values are returned as an Iterator when you ask for them.
      */
     private final Map<String, List<String>> headers = new HashMap<>();
 
@@ -141,8 +137,7 @@ public final class SavedRequest implements Serializable {
 
 
     /**
-     * The decode request URI associated with this Request. Path parameters are
-     * also excluded
+     * The decode request URI associated with this Request. Path parameters are also excluded
      */
     private String decodedRequestURI = null;
 
diff --git a/java/org/apache/catalina/authenticator/SingleSignOn.java b/java/org/apache/catalina/authenticator/SingleSignOn.java
index 9ce30fe0c0..7bd5a9393c 100644
--- a/java/org/apache/catalina/authenticator/SingleSignOn.java
+++ b/java/org/apache/catalina/authenticator/SingleSignOn.java
@@ -39,20 +39,16 @@ import org.apache.catalina.valves.ValveBase;
 import org.apache.tomcat.util.res.StringManager;
 
 /**
- * A <strong>Valve</strong> that supports a "single sign on" user experience,
- * where the security identity of a user who successfully authenticates to one
- * web application is propagated to other web applications in the same
- * security domain.  For successful use, the following requirements must
- * be met:
+ * A <strong>Valve</strong> that supports a "single sign on" user experience, where the security identity of a user who
+ * successfully authenticates to one web application is propagated to other web applications in the same security
+ * domain. For successful use, the following requirements must be met:
  * <ul>
- * <li>This Valve must be configured on the Container that represents a
- *     virtual host (typically an implementation of <code>Host</code>).</li>
- * <li>The <code>Realm</code> that contains the shared user and role
- *     information must be configured on the same Container (or a higher
- *     one), and not overridden at the web application level.</li>
- * <li>The web applications themselves must use one of the standard
- *     Authenticators found in the
- *     <code>org.apache.catalina.authenticator</code> package.</li>
+ * <li>This Valve must be configured on the Container that represents a virtual host (typically an implementation of
+ * <code>Host</code>).</li>
+ * <li>The <code>Realm</code> that contains the shared user and role information must be configured on the same
+ * Container (or a higher one), and not overridden at the web application level.</li>
+ * <li>The web applications themselves must use one of the standard Authenticators found in the
+ * <code>org.apache.catalina.authenticator</code> package.</li>
  * </ul>
  *
  * @author Craig R. McClanahan
@@ -61,13 +57,13 @@ public class SingleSignOn extends ValveBase {
 
     private static final StringManager sm = StringManager.getManager(SingleSignOn.class);
 
-    /* The engine at the top of the container hierarchy in which this SSO Valve
-     * has been placed. It is used to get back to a session object from a
-     * SingleSignOnSessionKey and is updated when the Valve starts and stops.
+    /*
+     * The engine at the top of the container hierarchy in which this SSO Valve has been placed. It is used to get back
+     * to a session object from a SingleSignOnSessionKey and is updated when the Valve starts and stops.
      */
     private Engine engine;
 
-    //------------------------------------------------------ Constructor
+    // ------------------------------------------------------ Constructor
 
     public SingleSignOn() {
         super(true);
@@ -77,15 +73,14 @@ public class SingleSignOn extends ValveBase {
     // ----------------------------------------------------- Instance Variables
 
     /**
-     * The cache of SingleSignOnEntry instances for authenticated Principals,
-     * keyed by the cookie value that is used to select them.
+     * The cache of SingleSignOnEntry instances for authenticated Principals, keyed by the cookie value that is used to
+     * select them.
      */
-    protected Map<String,SingleSignOnEntry> cache = new ConcurrentHashMap<>();
+    protected Map<String, SingleSignOnEntry> cache = new ConcurrentHashMap<>();
 
     /**
-     * Indicates whether this valve should require a downstream Authenticator to
-     * reauthenticate each request, or if it itself can bind a UserPrincipal
-     * and AuthType object to the request.
+     * Indicates whether this valve should require a downstream Authenticator to reauthenticate each request, or if it
+     * itself can bind a UserPrincipal and AuthType object to the request.
      */
     private boolean requireReauthentication = false;
 
@@ -102,8 +97,7 @@ public class SingleSignOn extends ValveBase {
     // ------------------------------------------------------------- Properties
 
     /**
-     * Returns the optional cookie domain.
-     * May return null.
+     * Returns the optional cookie domain. May return null.
      *
      * @return The cookie domain
      */
@@ -136,6 +130,7 @@ public class SingleSignOn extends ValveBase {
 
     /**
      * Set the cookie name that will be used for the SSO cookie.
+     *
      * @param cookieName the cookieName to set
      */
     public void setCookieName(String cookieName) {
@@ -144,19 +139,15 @@ public class SingleSignOn extends ValveBase {
 
 
     /**
-     * Gets whether each request needs to be reauthenticated (by an
-     * Authenticator downstream in the pipeline) to the security
-     * <code>Realm</code>, or if this Valve can itself bind security info
-     * to the request based on the presence of a valid SSO entry without
-     * rechecking with the <code>Realm</code>.
+     * Gets whether each request needs to be reauthenticated (by an Authenticator downstream in the pipeline) to the
+     * security <code>Realm</code>, or if this Valve can itself bind security info to the request based on the presence
+     * of a valid SSO entry without rechecking with the <code>Realm</code>.
      *
-     * @return  <code>true</code> if it is required that a downstream
-     *          Authenticator reauthenticate each request before calls to
-     *          <code>HttpServletRequest.setUserPrincipal()</code>
-     *          and <code>HttpServletRequest.setAuthType()</code> are made;
-     *          <code>false</code> if the <code>Valve</code> can itself make
-     *          those calls relying on the presence of a valid SingleSignOn
-     *          entry associated with the request.
+     * @return <code>true</code> if it is required that a downstream Authenticator reauthenticate each request before
+     *             calls to <code>HttpServletRequest.setUserPrincipal()</code> and
+     *             <code>HttpServletRequest.setAuthType()</code> are made; <code>false</code> if the <code>Valve</code>
+     *             can itself make those calls relying on the presence of a valid SingleSignOn entry associated with the
+     *             request.
      *
      * @see #setRequireReauthentication
      */
@@ -166,42 +157,32 @@ public class SingleSignOn extends ValveBase {
 
 
     /**
-     * Sets whether each request needs to be reauthenticated (by an
-     * Authenticator downstream in the pipeline) to the security
-     * <code>Realm</code>, or if this Valve can itself bind security info
-     * to the request, based on the presence of a valid SSO entry, without
-     * rechecking with the <code>Realm</code>.
+     * Sets whether each request needs to be reauthenticated (by an Authenticator downstream in the pipeline) to the
+     * security <code>Realm</code>, or if this Valve can itself bind security info to the request, based on the presence
+     * of a valid SSO entry, without rechecking with the <code>Realm</code>.
      * <p>
-     * If this property is <code>false</code> (the default), this
-     * <code>Valve</code> will bind a UserPrincipal and AuthType to the request
-     * if a valid SSO entry is associated with the request.  It will not notify
-     * the security <code>Realm</code> of the incoming request.
+     * If this property is <code>false</code> (the default), this <code>Valve</code> will bind a UserPrincipal and
+     * AuthType to the request if a valid SSO entry is associated with the request. It will not notify the security
+     * <code>Realm</code> of the incoming request.
      * <p>
-     * This property should be set to <code>true</code> if the overall server
-     * configuration requires that the <code>Realm</code> reauthenticate each
-     * request thread.  An example of such a configuration would be one where
-     * the <code>Realm</code> implementation provides security for both a
-     * web tier and an associated EJB tier, and needs to set security
-     * credentials on each request thread in order to support EJB access.
+     * This property should be set to <code>true</code> if the overall server configuration requires that the
+     * <code>Realm</code> reauthenticate each request thread. An example of such a configuration would be one where the
+     * <code>Realm</code> implementation provides security for both a web tier and an associated EJB tier, and needs to
+     * set security credentials on each request thread in order to support EJB access.
      * <p>
-     * If this property is set to <code>true</code>, this Valve will set flags
-     * on the request notifying the downstream Authenticator that the request
-     * is associated with an SSO session.  The Authenticator will then call its
-     * {@link AuthenticatorBase#reauthenticateFromSSO reauthenticateFromSSO}
-     * method to attempt to reauthenticate the request to the
-     * <code>Realm</code>, using any credentials that were cached with this
-     * Valve.
+     * If this property is set to <code>true</code>, this Valve will set flags on the request notifying the downstream
+     * Authenticator that the request is associated with an SSO session. The Authenticator will then call its
+     * {@link AuthenticatorBase#reauthenticateFromSSO reauthenticateFromSSO} method to attempt to reauthenticate the
+     * request to the <code>Realm</code>, using any credentials that were cached with this Valve.
      * <p>
-     * The default value of this property is <code>false</code>, in order
-     * to maintain backward compatibility with previous versions of Tomcat.
+     * The default value of this property is <code>false</code>, in order to maintain backward compatibility with
+     * previous versions of Tomcat.
      *
-     * @param required  <code>true</code> if it is required that a downstream
-     *                  Authenticator reauthenticate each request before calls
-     *                  to  <code>HttpServletRequest.setUserPrincipal()</code>
-     *                  and <code>HttpServletRequest.setAuthType()</code> are
-     *                  made; <code>false</code> if the <code>Valve</code> can
-     *                  itself make those calls relying on the presence of a
-     *                  valid SingleSignOn entry associated with the request.
+     * @param required <code>true</code> if it is required that a downstream Authenticator reauthenticate each request
+     *                     before calls to <code>HttpServletRequest.setUserPrincipal()</code> and
+     *                     <code>HttpServletRequest.setAuthType()</code> are made; <code>false</code> if the
+     *                     <code>Valve</code> can itself make those calls relying on the presence of a valid
+     *                     SingleSignOn entry associated with the request.
      *
      * @see AuthenticatorBase#reauthenticateFromSSO
      */
@@ -215,15 +196,14 @@ public class SingleSignOn extends ValveBase {
     /**
      * Perform single-sign-on support processing for this request.
      *
-     * @param request The servlet request we are processing
+     * @param request  The servlet request we are processing
      * @param response The servlet response we are creating
      *
-     * @exception IOException if an input/output error occurs
+     * @exception IOException      if an input/output error occurs
      * @exception ServletException if a servlet error occurs
      */
     @Override
-    public void invoke(Request request, Response response)
-        throws IOException, ServletException {
+    public void invoke(Request request, Response response) throws IOException, ServletException {
 
         request.removeNote(Constants.REQ_SSOID_NOTE);
 
@@ -233,8 +213,8 @@ public class SingleSignOn extends ValveBase {
         }
         if (request.getUserPrincipal() != null) {
             if (containerLog.isDebugEnabled()) {
-                containerLog.debug(sm.getString("singleSignOn.debug.hasPrincipal",
-                        request.getUserPrincipal().getName()));
+                containerLog
+                        .debug(sm.getString("singleSignOn.debug.hasPrincipal", request.getUserPrincipal().getName()));
             }
             getNext().invoke(request, response);
             return;
@@ -264,15 +244,13 @@ public class SingleSignOn extends ValveBase {
 
         // Look up the cached Principal associated with this cookie value
         if (containerLog.isDebugEnabled()) {
-            containerLog.debug(sm.getString("singleSignOn.debug.principalCheck",
-                    cookie.getValue()));
+            containerLog.debug(sm.getString("singleSignOn.debug.principalCheck", cookie.getValue()));
         }
         SingleSignOnEntry entry = cache.get(cookie.getValue());
         if (entry != null) {
             if (containerLog.isDebugEnabled()) {
                 containerLog.debug(sm.getString("singleSignOn.debug.principalFound",
-                        entry.getPrincipal() != null ? entry.getPrincipal().getName() : "",
-                        entry.getAuthType()));
+                        entry.getPrincipal() != null ? entry.getPrincipal().getName() : "", entry.getAuthType()));
             }
             request.setNote(Constants.REQ_SSOID_NOTE, cookie.getValue());
             // Only set security elements if reauthentication is not required
@@ -282,8 +260,7 @@ public class SingleSignOn extends ValveBase {
             }
         } else {
             if (containerLog.isDebugEnabled()) {
-                containerLog.debug(sm.getString("singleSignOn.debug.principalNotFound",
-                        cookie.getValue()));
+                containerLog.debug(sm.getString("singleSignOn.debug.principalNotFound", cookie.getValue()));
             }
             // No need to return a valid SSO session ID
             cookie.setValue("REMOVE");
@@ -316,12 +293,10 @@ public class SingleSignOn extends ValveBase {
     // ------------------------------------------------------ Protected Methods
 
     /**
-     * Process a session destroyed event by removing references to that session
-     * from the caches and - if the session destruction is the result of a
-     * logout - destroy the associated SSO session.
+     * Process a session destroyed event by removing references to that session from the caches and - if the session
+     * destruction is the result of a logout - destroy the associated SSO session.
      *
-     * @param ssoId   The ID of the SSO session which which the destroyed
-     *                session was associated
+     * @param ssoId   The ID of the SSO session which which the destroyed session was associated
      * @param session The session that has been destroyed
      */
     public void sessionDestroyed(String ssoId, Session session) {
@@ -334,12 +309,11 @@ public class SingleSignOn extends ValveBase {
         // If so, we'll just remove the expired session from the SSO. If the
         // session was logged out, we'll log out of all session associated with
         // the SSO.
-        if (((session.getMaxInactiveInterval() > 0)
-            && (session.getIdleTimeInternal() >= session.getMaxInactiveInterval() * 1000))
-            || (!session.getManager().getContext().getState().isAvailable())) {
+        if (((session.getMaxInactiveInterval() > 0) &&
+                (session.getIdleTimeInternal() >= session.getMaxInactiveInterval() * 1000)) ||
+                (!session.getManager().getContext().getState().isAvailable())) {
             if (containerLog.isDebugEnabled()) {
-                containerLog.debug(sm.getString("singleSignOn.debug.sessionTimeout",
-                        ssoId, session));
+                containerLog.debug(sm.getString("singleSignOn.debug.sessionTimeout", ssoId, session));
             }
             removeSession(ssoId, session);
         } else {
@@ -347,8 +321,7 @@ public class SingleSignOn extends ValveBase {
             // Deregister this single session id, invalidating
             // associated sessions
             if (containerLog.isDebugEnabled()) {
-                containerLog.debug(sm.getString("singleSignOn.debug.sessionLogout",
-                        ssoId, session));
+                containerLog.debug(sm.getString("singleSignOn.debug.sessionLogout", ssoId, session));
             }
             // First remove the session that we know has expired / been logged
             // out since it has already been removed from its Manager and, if
@@ -365,27 +338,23 @@ public class SingleSignOn extends ValveBase {
 
 
     /**
-     * Associate the specified single sign on identifier with the
-     * specified Session.
+     * Associate the specified single sign on identifier with the specified Session.
      *
-     * @param ssoId Single sign on identifier
+     * @param ssoId   Single sign on identifier
      * @param session Session to be associated
      *
-     * @return <code>true</code> if the session was associated to the given SSO
-     *         session, otherwise <code>false</code>
+     * @return <code>true</code> if the session was associated to the given SSO session, otherwise <code>false</code>
      */
     protected boolean associate(String ssoId, Session session) {
         SingleSignOnEntry sso = cache.get(ssoId);
         if (sso == null) {
             if (containerLog.isDebugEnabled()) {
-                containerLog.debug(sm.getString("singleSignOn.debug.associateFail",
-                        ssoId, session));
+                containerLog.debug(sm.getString("singleSignOn.debug.associateFail", ssoId, session));
             }
             return false;
         } else {
             if (containerLog.isDebugEnabled()) {
-                containerLog.debug(sm.getString("singleSignOn.debug.associate",
-                        ssoId, session));
+                containerLog.debug(sm.getString("singleSignOn.debug.associate", ssoId, session));
             }
             sso.addSession(this, ssoId, session);
             return true;
@@ -394,8 +363,7 @@ public class SingleSignOn extends ValveBase {
 
 
     /**
-     * Deregister the specified single sign on identifier, and invalidate
-     * any associated sessions.
+     * Deregister the specified single sign on identifier, and invalidate any associated sessions.
      *
      * @param ssoId Single sign on identifier to deregister
      */
@@ -426,7 +394,7 @@ public class SingleSignOn extends ValveBase {
             expire(ssoKey);
         }
 
-        // NOTE:  Clients may still possess the old single sign on cookie,
+        // NOTE: Clients may still possess the old single sign on cookie,
         // but it will be removed on the next request since it is no longer
         // in the cache
     }
@@ -468,28 +436,21 @@ public class SingleSignOn extends ValveBase {
 
 
     /**
-     * Attempts reauthentication to the given <code>Realm</code> using
-     * the credentials associated with the single sign-on session
-     * identified by argument <code>ssoId</code>.
+     * Attempts reauthentication to the given <code>Realm</code> using the credentials associated with the single
+     * sign-on session identified by argument <code>ssoId</code>.
      * <p>
-     * If reauthentication is successful, the <code>Principal</code> and
-     * authorization type associated with the SSO session will be bound
-     * to the given <code>Request</code> object via calls to
-     * {@link Request#setAuthType Request.setAuthType()} and
-     * {@link Request#setUserPrincipal Request.setUserPrincipal()}
+     * If reauthentication is successful, the <code>Principal</code> and authorization type associated with the SSO
+     * session will be bound to the given <code>Request</code> object via calls to {@link Request#setAuthType
+     * Request.setAuthType()} and {@link Request#setUserPrincipal Request.setUserPrincipal()}
      * </p>
      *
-     * @param ssoId     identifier of SingleSignOn session with which the
-     *                  caller is associated
-     * @param realm     Realm implementation against which the caller is to
-     *                  be authenticated
-     * @param request   the request that needs to be authenticated
+     * @param ssoId   identifier of SingleSignOn session with which the caller is associated
+     * @param realm   Realm implementation against which the caller is to be authenticated
+     * @param request the request that needs to be authenticated
      *
-     * @return  <code>true</code> if reauthentication was successful,
-     *          <code>false</code> otherwise.
+     * @return <code>true</code> if reauthentication was successful, <code>false</code> otherwise.
      */
-    protected boolean reauthenticate(String ssoId, Realm realm,
-                                     Request request) {
+    protected boolean reauthenticate(String ssoId, Realm realm, Request request) {
 
         if (ssoId == null || realm == null) {
             return false;
@@ -502,8 +463,7 @@ public class SingleSignOn extends ValveBase {
 
             String username = entry.getUsername();
             if (username != null) {
-                Principal reauthPrincipal =
-                        realm.authenticate(username, entry.getPassword());
+                Principal reauthPrincipal = realm.authenticate(username, entry.getPassword());
                 if (reauthPrincipal != null) {
                     reauthenticated = true;
                     // Bind the authorization credentials to the request
@@ -518,18 +478,15 @@ public class SingleSignOn extends ValveBase {
 
 
     /**
-     * Register the specified Principal as being associated with the specified
-     * value for the single sign on identifier.
+     * Register the specified Principal as being associated with the specified value for the single sign on identifier.
      *
-     * @param ssoId Single sign on identifier to register
+     * @param ssoId     Single sign on identifier to register
      * @param principal Associated user principal that is identified
-     * @param authType Authentication type used to authenticate this
-     *  user principal
-     * @param username Username used to authenticate this user
-     * @param password Password used to authenticate this user
+     * @param authType  Authentication type used to authenticate this user principal
+     * @param username  Username used to authenticate this user
+     * @param password  Password used to authenticate this user
      */
-    protected void register(String ssoId, Principal principal, String authType,
-                  String username, String password) {
+    protected void register(String ssoId, Principal principal, String authType, String username, String password) {
 
         if (containerLog.isDebugEnabled()) {
             containerLog.debug(sm.getString("singleSignOn.debug.register", ssoId,
@@ -541,35 +498,26 @@ public class SingleSignOn extends ValveBase {
 
 
     /**
-     * Updates any <code>SingleSignOnEntry</code> found under key
-     * <code>ssoId</code> with the given authentication data.
+     * Updates any <code>SingleSignOnEntry</code> found under key <code>ssoId</code> with the given authentication data.
      * <p>
-     * The purpose of this method is to allow an SSO entry that was
-     * established without a username/password combination (i.e. established
-     * following DIGEST or CLIENT_CERT authentication) to be updated with
-     * a username and password if one becomes available through a subsequent
-     * BASIC or FORM authentication.  The SSO entry will then be usable for
+     * The purpose of this method is to allow an SSO entry that was established without a username/password combination
+     * (i.e. established following DIGEST or CLIENT_CERT authentication) to be updated with a username and password if
+     * one becomes available through a subsequent BASIC or FORM authentication. The SSO entry will then be usable for
      * reauthentication.
      * <p>
-     * <b>NOTE:</b> Only updates the SSO entry if a call to
-     * <code>SingleSignOnEntry.getCanReauthenticate()</code> returns
-     * <code>false</code>; otherwise, it is assumed that the SSO entry already
-     * has sufficient information to allow reauthentication and that no update
-     * is needed.
+     * <b>NOTE:</b> Only updates the SSO entry if a call to <code>SingleSignOnEntry.getCanReauthenticate()</code>
+     * returns <code>false</code>; otherwise, it is assumed that the SSO entry already has sufficient information to
+     * allow reauthentication and that no update is needed.
      *
      * @param ssoId     identifier of Single sign to be updated
-     * @param principal the <code>Principal</code> returned by the latest
-     *                  call to <code>Realm.authenticate</code>.
-     * @param authType  the type of authenticator used (BASIC, CLIENT_CERT,
-     *                  DIGEST or FORM)
+     * @param principal the <code>Principal</code> returned by the latest call to <code>Realm.authenticate</code>.
+     * @param authType  the type of authenticator used (BASIC, CLIENT_CERT, DIGEST or FORM)
      * @param username  the username (if any) used for the authentication
      * @param password  the password (if any) used for the authentication
      *
-     * @return <code>true</code> if the credentials were updated, otherwise
-     *         <code>false</code>
+     * @return <code>true</code> if the credentials were updated, otherwise <code>false</code>
      */
-    protected boolean update(String ssoId, Principal principal, String authType,
-                          String username, String password) {
+    protected boolean update(String ssoId, Principal principal, String authType, String username, String password) {
 
         SingleSignOnEntry sso = cache.get(ssoId);
         if (sso != null && !sso.getCanReauthenticate()) {
@@ -585,10 +533,9 @@ public class SingleSignOn extends ValveBase {
 
 
     /**
-     * Remove a single Session from a SingleSignOn.  Called when
-     * a session is timed out and no longer active.
+     * Remove a single Session from a SingleSignOn. Called when a session is timed out and no longer active.
      *
-     * @param ssoId Single sign on identifier from which to remove the session.
+     * @param ssoId   Single sign on identifier from which to remove the session.
      * @param session the session to be removed.
      */
     protected void removeSession(String ssoId, Session session) {
diff --git a/java/org/apache/catalina/authenticator/SingleSignOnEntry.java b/java/org/apache/catalina/authenticator/SingleSignOnEntry.java
index 24984f9ea8..047bbed8ba 100644
--- a/java/org/apache/catalina/authenticator/SingleSignOnEntry.java
+++ b/java/org/apache/catalina/authenticator/SingleSignOnEntry.java
@@ -30,12 +30,11 @@ import javax.servlet.http.HttpServletRequest;
 import org.apache.catalina.Session;
 
 /**
- * A class that represents entries in the cache of authenticated users.
- * This is necessary to make it available to
- * <code>AuthenticatorBase</code> subclasses that need it in order to perform
- * reauthentications when SingleSignOn is in use.
+ * A class that represents entries in the cache of authenticated users. This is necessary to make it available to
+ * <code>AuthenticatorBase</code> subclasses that need it in order to perform reauthentications when SingleSignOn is in
+ * use.
  *
- * @author  B Stansberry, based on work by Craig R. McClanahan
+ * @author B Stansberry, based on work by Craig R. McClanahan
  *
  * @see SingleSignOn
  * @see AuthenticatorBase#reauthenticateFromSSO
@@ -44,7 +43,7 @@ public class SingleSignOnEntry implements Serializable {
 
     private static final long serialVersionUID = 1L;
 
-    // ------------------------------------------------------  Instance Fields
+    // ------------------------------------------------------ Instance Fields
 
     private String authType = null;
 
@@ -53,27 +52,23 @@ public class SingleSignOnEntry implements Serializable {
     // Marked as transient so special handling can be applied to serialization
     private transient Principal principal = null;
 
-    private final Map<SingleSignOnSessionKey,SingleSignOnSessionKey> sessionKeys =
-            new ConcurrentHashMap<>();
+    private final Map<SingleSignOnSessionKey, SingleSignOnSessionKey> sessionKeys = new ConcurrentHashMap<>();
 
     private String username = null;
 
     private boolean canReauthenticate = false;
 
-    // ---------------------------------------------------------  Constructors
+    // --------------------------------------------------------- Constructors
 
     /**
      * Creates a new SingleSignOnEntry
      *
-     * @param principal the <code>Principal</code> returned by the latest
-     *                  call to <code>Realm.authenticate</code>.
-     * @param authType  the type of authenticator used (BASIC, CLIENT_CERT,
-     *                  DIGEST or FORM)
+     * @param principal the <code>Principal</code> returned by the latest call to <code>Realm.authenticate</code>.
+     * @param authType  the type of authenticator used (BASIC, CLIENT_CERT, DIGEST or FORM)
      * @param username  the username (if any) used for the authentication
      * @param password  the password (if any) used for the authentication
      */
-    public SingleSignOnEntry(Principal principal, String authType,
-                             String username, String password) {
+    public SingleSignOnEntry(Principal principal, String authType, String username, String password) {
 
         updateCredentials(principal, authType, username, password);
     }
@@ -81,13 +76,11 @@ public class SingleSignOnEntry implements Serializable {
     // ------------------------------------------------------- Package Methods
 
     /**
-     * Adds a <code>Session</code> to the list of those associated with
-     * this SSO.
+     * Adds a <code>Session</code> to the list of those associated with this SSO.
      *
-     * @param sso       The <code>SingleSignOn</code> valve that is managing
-     *                  the SSO session.
-     * @param ssoId     The ID of the SSO session.
-     * @param session   The <code>Session</code> being associated with the SSO.
+     * @param sso     The <code>SingleSignOn</code> valve that is managing the SSO session.
+     * @param ssoId   The ID of the SSO session.
+     * @param session The <code>Session</code> being associated with the SSO.
      */
     public void addSession(SingleSignOn sso, String ssoId, Session session) {
         SingleSignOnSessionKey key = new SingleSignOnSessionKey(session);
@@ -99,10 +92,9 @@ public class SingleSignOnEntry implements Serializable {
     }
 
     /**
-     * Removes the given <code>Session</code> from the list of those
-     * associated with this SSO.
+     * Removes the given <code>Session</code> from the list of those associated with this SSO.
      *
-     * @param session  the <code>Session</code> to remove.
+     * @param session the <code>Session</code> to remove.
      */
     public void removeSession(Session session) {
         SingleSignOnSessionKey key = new SingleSignOnSessionKey(session);
@@ -112,16 +104,14 @@ public class SingleSignOnEntry implements Serializable {
     /**
      * Returns the HTTP Session identifiers associated with this SSO.
      *
-     * @return The identifiers for the HTTP sessions that are current associated
-     *         with this SSo entry
+     * @return The identifiers for the HTTP sessions that are current associated with this SSo entry
      */
     public Set<SingleSignOnSessionKey> findSessions() {
         return sessionKeys.keySet();
     }
 
     /**
-     * Gets the name of the authentication type originally used to authenticate
-     * the user associated with the SSO.
+     * Gets the name of the authentication type originally used to authenticate the user associated with the SSO.
      *
      * @return "BASIC", "CLIENT_CERT", "DIGEST", "FORM" or "NONE"
      */
@@ -130,11 +120,9 @@ public class SingleSignOnEntry implements Serializable {
     }
 
     /**
-     * Gets whether the authentication type associated with the original
-     * authentication supports reauthentication.
+     * Gets whether the authentication type associated with the original authentication supports reauthentication.
      *
-     * @return  <code>true</code> if <code>getAuthType</code> returns
-     *          "BASIC" or "FORM", <code>false</code> otherwise.
+     * @return <code>true</code> if <code>getAuthType</code> returns "BASIC" or "FORM", <code>false</code> otherwise.
      */
     public boolean getCanReauthenticate() {
         return this.canReauthenticate;
@@ -143,9 +131,8 @@ public class SingleSignOnEntry implements Serializable {
     /**
      * Gets the password credential (if any) associated with the SSO.
      *
-     * @return  the password credential associated with the SSO, or
-     *          <code>null</code> if the original authentication type
-     *          does not involve a password.
+     * @return the password credential associated with the SSO, or <code>null</code> if the original authentication type
+     *             does not involve a password.
      */
     public String getPassword() {
         return this.password;
@@ -154,19 +141,17 @@ public class SingleSignOnEntry implements Serializable {
     /**
      * Gets the <code>Principal</code> that has been authenticated by the SSO.
      *
-     * @return The Principal that was created by the authentication that
-     *         triggered the creation of the SSO entry
+     * @return The Principal that was created by the authentication that triggered the creation of the SSO entry
      */
     public Principal getPrincipal() {
         return this.principal;
     }
 
     /**
-     * Gets the user name provided by the user as part of the authentication
-     * process.
+     * Gets the user name provided by the user as part of the authentication process.
      *
-     * @return The user name that was authenticated as part of the
-     *         authentication that triggered the creation of the SSO entry
+     * @return The user name that was authenticated as part of the authentication that triggered the creation of the SSO
+     *             entry
      */
     public String getUsername() {
         return this.username;
@@ -174,18 +159,14 @@ public class SingleSignOnEntry implements Serializable {
 
 
     /**
-     * Updates the SingleSignOnEntry to reflect the latest security
-     * information associated with the caller.
+     * Updates the SingleSignOnEntry to reflect the latest security information associated with the caller.
      *
-     * @param principal the <code>Principal</code> returned by the latest
-     *                  call to <code>Realm.authenticate</code>.
-     * @param authType  the type of authenticator used (BASIC, CLIENT_CERT,
-     *                  DIGEST or FORM)
+     * @param principal the <code>Principal</code> returned by the latest call to <code>Realm.authenticate</code>.
+     * @param authType  the type of authenticator used (BASIC, CLIENT_CERT, DIGEST or FORM)
      * @param username  the username (if any) used for the authentication
      * @param password  the password (if any) used for the authentication
      */
-    public synchronized void updateCredentials(Principal principal, String authType,
-                                  String username, String password) {
+    public synchronized void updateCredentials(Principal principal, String authType, String username, String password) {
         this.principal = principal;
         this.authType = authType;
         this.username = username;
@@ -205,8 +186,7 @@ public class SingleSignOnEntry implements Serializable {
         }
     }
 
-    private void readObject(ObjectInputStream in) throws IOException,
-            ClassNotFoundException {
+    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
         in.defaultReadObject();
         boolean hasPrincipal = in.readBoolean();
         if (hasPrincipal) {
diff --git a/java/org/apache/catalina/authenticator/SingleSignOnSessionKey.java b/java/org/apache/catalina/authenticator/SingleSignOnSessionKey.java
index a07946f783..521f404781 100644
--- a/java/org/apache/catalina/authenticator/SingleSignOnSessionKey.java
+++ b/java/org/apache/catalina/authenticator/SingleSignOnSessionKey.java
@@ -22,11 +22,9 @@ import org.apache.catalina.Context;
 import org.apache.catalina.Session;
 
 /**
- * Key used by SSO to identify a session. This key is used rather than the
- * actual session to facilitate the replication of the SSO information
- * across a cluster where replicating the entire session would generate
- * significant, unnecessary overhead.
- *
+ * Key used by SSO to identify a session. This key is used rather than the actual session to facilitate the replication
+ * of the SSO information across a cluster where replicating the entire session would generate significant, unnecessary
+ * overhead.
  */
 public class SingleSignOnSessionKey implements Serializable {
 
@@ -59,12 +57,9 @@ public class SingleSignOnSessionKey implements Serializable {
     public int hashCode() {
         final int prime = 31;
         int result = 1;
-        result = prime * result +
-                ((sessionId == null) ? 0 : sessionId.hashCode());
-        result = prime * result +
-                ((contextName == null) ? 0 : contextName.hashCode());
-        result = prime * result +
-                ((hostName == null) ? 0 : hostName.hashCode());
+        result = prime * result + ((sessionId == null) ? 0 : sessionId.hashCode());
+        result = prime * result + ((contextName == null) ? 0 : contextName.hashCode());
+        result = prime * result + ((hostName == null) ? 0 : hostName.hashCode());
         return result;
     }
 
diff --git a/java/org/apache/catalina/authenticator/SpnegoAuthenticator.java b/java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
index e208916583..38ac493fcf 100644
--- a/java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
@@ -46,11 +46,9 @@ import org.ietf.jgss.GSSManager;
 import org.ietf.jgss.Oid;
 
 /**
- * A SPNEGO authenticator that uses the SPNEGO/Kerberos support built in to Java
- * 6. Successful Kerberos authentication depends on the correct configuration of
- * multiple components. If the configuration is invalid, the error messages are
- * often cryptic although a Google search will usually point you in the right
- * direction.
+ * A SPNEGO authenticator that uses the SPNEGO/Kerberos support built in to Java 6. Successful Kerberos authentication
+ * depends on the correct configuration of multiple components. If the configuration is invalid, the error messages are
+ * often cryptic although a Google search will usually point you in the right direction.
  */
 public class SpnegoAuthenticator extends AuthenticatorBase {
 
@@ -58,23 +56,27 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
     private static final String AUTH_HEADER_VALUE_NEGOTIATE = "Negotiate";
 
     private String loginConfigName = Constants.DEFAULT_LOGIN_MODULE_NAME;
+
     public String getLoginConfigName() {
         return loginConfigName;
     }
+
     public void setLoginConfigName(String loginConfigName) {
         this.loginConfigName = loginConfigName;
     }
 
     private boolean storeDelegatedCredential = true;
+
     public boolean isStoreDelegatedCredential() {
         return storeDelegatedCredential;
     }
-    public void setStoreDelegatedCredential(
-            boolean storeDelegatedCredential) {
+
+    public void setStoreDelegatedCredential(boolean storeDelegatedCredential) {
         this.storeDelegatedCredential = storeDelegatedCredential;
     }
 
     private Pattern noKeepAliveUserAgents = null;
+
     public String getNoKeepAliveUserAgents() {
         Pattern p = noKeepAliveUserAgents;
         if (p == null) {
@@ -83,9 +85,9 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
             return p.pattern();
         }
     }
+
     public void setNoKeepAliveUserAgents(String noKeepAliveUserAgents) {
-        if (noKeepAliveUserAgents == null ||
-                noKeepAliveUserAgents.length() == 0) {
+        if (noKeepAliveUserAgents == null || noKeepAliveUserAgents.length() == 0) {
             this.noKeepAliveUserAgents = null;
         } else {
             this.noKeepAliveUserAgents = Pattern.compile(noKeepAliveUserAgents);
@@ -93,9 +95,11 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
     }
 
     private boolean applyJava8u40Fix = true;
+
     public boolean getApplyJava8u40Fix() {
         return applyJava8u40Fix;
     }
+
     public void setApplyJava8u40Fix(boolean applyJava8u40Fix) {
         this.applyJava8u40Fix = applyJava8u40Fix;
     }
@@ -115,35 +119,28 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
         String krb5Conf = System.getProperty(Constants.KRB5_CONF_PROPERTY);
         if (krb5Conf == null) {
             // System property not set, use the Tomcat default
-            File krb5ConfFile = new File(container.getCatalinaBase(),
-                    Constants.DEFAULT_KRB5_CONF);
-            System.setProperty(Constants.KRB5_CONF_PROPERTY,
-                    krb5ConfFile.getAbsolutePath());
+            File krb5ConfFile = new File(container.getCatalinaBase(), Constants.DEFAULT_KRB5_CONF);
+            System.setProperty(Constants.KRB5_CONF_PROPERTY, krb5ConfFile.getAbsolutePath());
         }
 
         // JAAS configuration file location
         String jaasConf = System.getProperty(Constants.JAAS_CONF_PROPERTY);
         if (jaasConf == null) {
             // System property not set, use the Tomcat default
-            File jaasConfFile = new File(container.getCatalinaBase(),
-                    Constants.DEFAULT_JAAS_CONF);
-            System.setProperty(Constants.JAAS_CONF_PROPERTY,
-                    jaasConfFile.getAbsolutePath());
+            File jaasConfFile = new File(container.getCatalinaBase(), Constants.DEFAULT_JAAS_CONF);
+            System.setProperty(Constants.JAAS_CONF_PROPERTY, jaasConfFile.getAbsolutePath());
         }
     }
 
 
     @Override
-    protected boolean doAuthenticate(Request request, HttpServletResponse response)
-            throws IOException {
+    protected boolean doAuthenticate(Request request, HttpServletResponse response) throws IOException {
 
         if (checkForCachedAuthentication(request, response, true)) {
             return true;
         }
 
-        MessageBytes authorization =
-            request.getCoyoteRequest().getMimeHeaders()
-            .getValue("authorization");
+        MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders().getValue("authorization");
 
         if (authorization == null) {
             if (log.isDebugEnabled()) {
@@ -159,8 +156,7 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
 
         if (!authorizationBC.startsWithIgnoreCase("negotiate ", 0)) {
             if (log.isDebugEnabled()) {
-                log.debug(sm.getString(
-                        "spnegoAuthenticator.authHeaderNotNego"));
+                log.debug(sm.getString("spnegoAuthenticator.authHeaderNotNego"));
             }
             response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
             response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
@@ -169,8 +165,7 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
 
         authorizationBC.setOffset(authorizationBC.getOffset() + 10);
 
-        byte[] decoded = Base64.decodeBase64(authorizationBC.getBuffer(),
-                authorizationBC.getOffset(),
+        byte[] decoded = Base64.decodeBase64(authorizationBC.getBuffer(), authorizationBC.getOffset(),
                 authorizationBC.getLength());
 
         if (getApplyJava8u40Fix()) {
@@ -179,8 +174,7 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
 
         if (decoded.length == 0) {
             if (log.isDebugEnabled()) {
-                log.debug(sm.getString(
-                        "spnegoAuthenticator.authHeaderNoToken"));
+                log.debug(sm.getString("spnegoAuthenticator.authHeaderNoToken"));
             }
             response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
             response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
@@ -196,10 +190,8 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
                 lc = new LoginContext(getLoginConfigName());
                 lc.login();
             } catch (LoginException e) {
-                log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"),
-                        e);
-                response.sendError(
-                        HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+                log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e);
+                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                 return false;
             }
 
@@ -215,19 +207,15 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
             } else {
                 credentialLifetime = GSSCredential.DEFAULT_LIFETIME;
             }
-            final PrivilegedExceptionAction<GSSCredential> action =
-                    () -> manager.createCredential(null,
-                            credentialLifetime,
-                            new Oid("1.3.6.1.5.5.2"),
-                            GSSCredential.ACCEPT_ONLY);
+            final PrivilegedExceptionAction<GSSCredential> action = () -> manager.createCredential(null,
+                    credentialLifetime, new Oid("1.3.6.1.5.5.2"), GSSCredential.ACCEPT_ONLY);
             gssContext = manager.createContext(Subject.doAs(subject, action));
 
             outToken = Subject.doAs(lc.getSubject(), new AcceptAction(gssContext, decoded));
 
             if (outToken == null) {
                 if (log.isDebugEnabled()) {
-                    log.debug(sm.getString(
-                            "spnegoAuthenticator.ticketValidateFail"));
+                    log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail"));
                 }
                 // Start again
                 response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
@@ -235,8 +223,8 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
                 return false;
             }
 
-            principal = Subject.doAs(subject, new AuthenticateAction(
-                    context.getRealm(), gssContext, storeDelegatedCredential));
+            principal = Subject.doAs(subject,
+                    new AuthenticateAction(context.getRealm(), gssContext, storeDelegatedCredential));
 
         } catch (GSSException e) {
             if (log.isDebugEnabled()) {
@@ -275,18 +263,14 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
         }
 
         // Send response token on success and failure
-        response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE + " "
-                + Base64.encodeBase64String(outToken));
+        response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE + " " + Base64.encodeBase64String(outToken));
 
         if (principal != null) {
-            register(request, response, principal, Constants.SPNEGO_METHOD,
-                    principal.getName(), null);
+            register(request, response, principal, Constants.SPNEGO_METHOD, principal.getName(), null);
 
             Pattern p = noKeepAliveUserAgents;
             if (p != null) {
-                MessageBytes ua =
-                        request.getCoyoteRequest().getMimeHeaders().getValue(
-                                "user-agent");
+                MessageBytes ua = request.getCoyoteRequest().getMimeHeaders().getValue("user-agent");
                 if (ua != null && p.matcher(ua.toString()).matches()) {
                     response.setHeader("Connection", "close");
                 }
@@ -322,8 +306,7 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
 
         @Override
         public byte[] run() throws GSSException {
-            return gssContext.acceptSecContext(decoded,
-                    0, decoded.length);
+            return gssContext.acceptSecContext(decoded, 0, decoded.length);
         }
     }
 
@@ -334,8 +317,7 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
         private final GSSContext gssContext;
         private final boolean storeDelegatedCredential;
 
-        public AuthenticateAction(Realm realm, GSSContext gssContext,
-                boolean storeDelegatedCredential) {
+        public AuthenticateAction(Realm realm, GSSContext gssContext, boolean storeDelegatedCredential) {
             this.realm = realm;
             this.gssContext = gssContext;
             this.storeDelegatedCredential = storeDelegatedCredential;
@@ -349,17 +331,14 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
 
 
     /**
-     * This class implements a hack around an incompatibility between the
-     * SPNEGO implementation in Windows and the SPNEGO implementation in Java 8
-     * update 40 onwards. It was introduced by the change to fix this bug:
-     * https://bugs.openjdk.java.net/browse/JDK-8048194
-     * (note: the change applied is not the one suggested in the bug report)
+     * This class implements a hack around an incompatibility between the SPNEGO implementation in Windows and the
+     * SPNEGO implementation in Java 8 update 40 onwards. It was introduced by the change to fix this bug:
+     * https://bugs.openjdk.java.net/browse/JDK-8048194 (note: the change applied is not the one suggested in the bug
+     * report)
      * <p>
-     * It is not clear to me if Windows, Java or Tomcat is at fault here. I
-     * think it is Java but I could be wrong.
+     * It is not clear to me if Windows, Java or Tomcat is at fault here. I think it is Java but I could be wrong.
      * <p>
-     * This hack works by re-ordering the list of mechTypes in the NegTokenInit
-     * token.
+     * This hack works by re-ordering the list of mechTypes in the NegTokenInit token.
      */
     public static class SpnegoTokenFixer {
 
@@ -381,9 +360,7 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
         // Fixes the token in-place
         private void fix() {
             /*
-             * Useful references:
-             * http://tools.ietf.org/html/rfc4121#page-5
-             * http://tools.ietf.org/html/rfc2743#page-81
+             * Useful references: http://tools.ietf.org/html/rfc4121#page-5 http://tools.ietf.org/html/rfc2743#page-81
              * https://msdn.microsoft.com/en-us/library/ms995330.aspx
              */
 


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


[tomcat] 05/07: Code cleanup (format). No functional change.

Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 91ca309136533aff96e3323843e2dae29ea4c5d6
Author: Mark Thomas <ma...@apache.org>
AuthorDate: Tue Jan 24 11:15:08 2023 +0000

    Code cleanup (format). No functional change.
---
 java/org/apache/juli/AsyncFileHandler.java      |  54 +++++------
 java/org/apache/juli/ClassLoaderLogManager.java | 114 ++++++++++--------------
 java/org/apache/juli/DateFormatCache.java       |  59 ++++++------
 java/org/apache/juli/FileHandler.java           | 111 ++++++++++-------------
 java/org/apache/juli/JdkLoggerFormatter.java    |  80 ++++++++++-------
 java/org/apache/juli/OneLineFormatter.java      |  50 +++++------
 java/org/apache/juli/VerbatimFormatter.java     |   8 +-
 java/org/apache/juli/WebappProperties.java      |  38 ++++----
 8 files changed, 231 insertions(+), 283 deletions(-)

diff --git a/java/org/apache/juli/AsyncFileHandler.java b/java/org/apache/juli/AsyncFileHandler.java
index d180dc738b..d2f3b2d919 100644
--- a/java/org/apache/juli/AsyncFileHandler.java
+++ b/java/org/apache/juli/AsyncFileHandler.java
@@ -26,42 +26,37 @@ import java.util.logging.LogRecord;
 
 /**
  * A {@link FileHandler} implementation that uses a queue of log entries.
- *
- * <p>Configuration properties are inherited from the {@link FileHandler}
- * class. This class does not add its own configuration properties for the
- * logging configuration, but relies on the following system properties
- * instead:</p>
- *
+ * <p>
+ * Configuration properties are inherited from the {@link FileHandler} class. This class does not add its own
+ * configuration properties for the logging configuration, but relies on the following system properties instead:
+ * </p>
  * <ul>
- *   <li><code>org.apache.juli.AsyncOverflowDropType</code>
- *    Default value: <code>1</code></li>
- *   <li><code>org.apache.juli.AsyncMaxRecordCount</code>
- *    Default value: <code>10000</code></li>
+ * <li><code>org.apache.juli.AsyncOverflowDropType</code> Default value: <code>1</code></li>
+ * <li><code>org.apache.juli.AsyncMaxRecordCount</code> Default value: <code>10000</code></li>
  * </ul>
- *
- * <p>See the System Properties page in the configuration reference of Tomcat.</p>
+ * <p>
+ * See the System Properties page in the configuration reference of Tomcat.
+ * </p>
  */
 public class AsyncFileHandler extends FileHandler {
 
     static final String THREAD_PREFIX = "AsyncFileHandlerWriter-";
 
-    public static final int OVERFLOW_DROP_LAST    = 1;
-    public static final int OVERFLOW_DROP_FIRST   = 2;
-    public static final int OVERFLOW_DROP_FLUSH   = 3;
+    public static final int OVERFLOW_DROP_LAST = 1;
+    public static final int OVERFLOW_DROP_FIRST = 2;
+    public static final int OVERFLOW_DROP_FLUSH = 3;
     public static final int OVERFLOW_DROP_CURRENT = 4;
 
     public static final int DEFAULT_OVERFLOW_DROP_TYPE = 1;
-    public static final int DEFAULT_MAX_RECORDS        = 10000;
+    public static final int DEFAULT_MAX_RECORDS = 10000;
 
     public static final int OVERFLOW_DROP_TYPE = Integer.parseInt(
-            System.getProperty("org.apache.juli.AsyncOverflowDropType",
-                               Integer.toString(DEFAULT_OVERFLOW_DROP_TYPE)));
-    public static final int MAX_RECORDS = Integer.parseInt(
-            System.getProperty("org.apache.juli.AsyncMaxRecordCount",
-                               Integer.toString(DEFAULT_MAX_RECORDS)));
+            System.getProperty("org.apache.juli.AsyncOverflowDropType", Integer.toString(DEFAULT_OVERFLOW_DROP_TYPE)));
+    public static final int MAX_RECORDS = Integer
+            .parseInt(System.getProperty("org.apache.juli.AsyncMaxRecordCount", Integer.toString(DEFAULT_MAX_RECORDS)));
 
-    private static final LoggerExecutorService LOGGER_SERVICE =
-            new LoggerExecutorService(OVERFLOW_DROP_TYPE, MAX_RECORDS);
+    private static final LoggerExecutorService LOGGER_SERVICE = new LoggerExecutorService(OVERFLOW_DROP_TYPE,
+            MAX_RECORDS);
 
     private final Object closeLock = new Object();
     protected volatile boolean closed = false;
@@ -129,9 +124,8 @@ public class AsyncFileHandler extends FileHandler {
             @Override
             public void run() {
                 /*
-                 * During Tomcat shutdown, the Handlers are closed before the
-                 * executor queue is flushed therefore the closed flag is
-                 * ignored if the executor is shutting down.
+                 * During Tomcat shutdown, the Handlers are closed before the executor queue is flushed therefore the
+                 * closed flag is ignored if the executor is shutting down.
                  */
                 if (!closed || loggerService.isTerminating()) {
                     publishInternal(record);
@@ -150,11 +144,9 @@ public class AsyncFileHandler extends FileHandler {
         private static final ThreadFactory THREAD_FACTORY = new ThreadFactory(THREAD_PREFIX);
 
         /*
-         * Implementation note: Use of this count could be extended to
-         * start/stop the LoggerExecutorService but that would require careful
-         * locking as the current size of the queue also needs to be taken into
-         * account and there are lost of edge cases when rapidly starting and
-         * stopping handlers.
+         * Implementation note: Use of this count could be extended to start/stop the LoggerExecutorService but that
+         * would require careful locking as the current size of the queue also needs to be taken into account and there
+         * are lost of edge cases when rapidly starting and stopping handlers.
          */
         private final AtomicInteger handlerCount = new AtomicInteger();
 
diff --git a/java/org/apache/juli/ClassLoaderLogManager.java b/java/org/apache/juli/ClassLoaderLogManager.java
index 18d500e21d..099f288f60 100644
--- a/java/org/apache/juli/ClassLoaderLogManager.java
+++ b/java/org/apache/juli/ClassLoaderLogManager.java
@@ -42,11 +42,9 @@ import java.util.logging.Logger;
 
 
 /**
- * Per classloader LogManager implementation.
- *
- * For light debugging, set the system property
- * <code>org.apache.juli.ClassLoaderLogManager.debug=true</code>.
- * Short configuration information will be sent to <code>System.err</code>.
+ * Per classloader LogManager implementation. For light debugging, set the system property
+ * <code>org.apache.juli.ClassLoaderLogManager.debug=true</code>. Short configuration information will be sent to
+ * <code>System.err</code>.
  */
 public class ClassLoaderLogManager extends LogManager {
 
@@ -54,8 +52,7 @@ public class ClassLoaderLogManager extends LogManager {
 
     private static ThreadLocal<Boolean> addingLocalRootLogger = ThreadLocal.withInitial(() -> Boolean.FALSE);
 
-    public static final String DEBUG_PROPERTY =
-            ClassLoaderLogManager.class.getName() + ".debug";
+    public static final String DEBUG_PROPERTY = ClassLoaderLogManager.class.getName() + ".debug";
 
     static {
         Class<?> c = null;
@@ -95,26 +92,22 @@ public class ClassLoaderLogManager extends LogManager {
 
 
     /**
-     * Map containing the classloader information, keyed per classloader. A
-     * weak hashmap is used to ensure no classloader reference is leaked from
-     * application redeployment.
+     * Map containing the classloader information, keyed per classloader. A weak hashmap is used to ensure no
+     * classloader reference is leaked from application redeployment.
      */
-    protected final Map<ClassLoader, ClassLoaderLogInfo> classLoaderLoggers =
-            new WeakHashMap<>(); // Guarded by this
+    protected final Map<ClassLoader, ClassLoaderLogInfo> classLoaderLoggers = new WeakHashMap<>(); // Guarded by this
 
 
     /**
-     * This prefix is used to allow using prefixes for the properties names
-     * of handlers and their subcomponents.
+     * This prefix is used to allow using prefixes for the properties names of handlers and their subcomponents.
      */
     protected final ThreadLocal<String> prefix = new ThreadLocal<>();
 
 
     /**
-     * Determines if the shutdown hook is used to perform any necessary
-     * clean-up such as flushing buffered handlers on JVM shutdown. Defaults to
-     * <code>true</code> but may be set to false if another component ensures
-     * that {@link #shutdown()} is called.
+     * Determines if the shutdown hook is used to perform any necessary clean-up such as flushing buffered handlers on
+     * JVM shutdown. Defaults to <code>true</code> but may be set to false if another component ensures that
+     * {@link #shutdown()} is called.
      */
     protected volatile boolean useShutdownHook = true;
 
@@ -225,10 +218,8 @@ public class ClassLoaderLogManager extends LogManager {
 
 
     /**
-     * Get the logger associated with the specified name inside
-     * the classloader local configuration. If this returns null,
-     * and the call originated for Logger.getLogger, a new
-     * logger with the specified name will be instantiated and
+     * Get the logger associated with the specified name inside the classloader local configuration. If this returns
+     * null, and the call originated for Logger.getLogger, a new logger with the specified name will be instantiated and
      * added using addLogger.
      *
      * @param name The name of the logger to retrieve
@@ -241,8 +232,7 @@ public class ClassLoaderLogManager extends LogManager {
 
 
     /**
-     * Get an enumeration of the logger names currently defined in the
-     * classloader local configuration.
+     * Get an enumeration of the logger names currently defined in the classloader local configuration.
      */
     @Override
     public synchronized Enumeration<String> getLoggerNames() {
@@ -252,8 +242,7 @@ public class ClassLoaderLogManager extends LogManager {
 
 
     /**
-     * Get the value of the specified property in the classloader local
-     * configuration.
+     * Get the value of the specified property in the classloader local configuration.
      *
      * @param name The property name
      */
@@ -332,8 +321,7 @@ public class ClassLoaderLogManager extends LogManager {
     @Override
     public void reset() throws SecurityException {
         Thread thread = Thread.currentThread();
-        if (thread.getClass().getName().startsWith(
-                "java.util.logging.LogManager$")) {
+        if (thread.getClass().getName().startsWith("java.util.logging.LogManager$")) {
             // Ignore the call from java.util.logging.LogManager.Cleaner,
             // because we have our own shutdown hook
             return;
@@ -389,12 +377,11 @@ public class ClassLoaderLogManager extends LogManager {
 
 
     /**
-     * Retrieve the configuration associated with the specified classloader. If
-     * it does not exist, it will be created. If no class loader is specified,
-     * the class loader used to load this class is used.
+     * Retrieve the configuration associated with the specified classloader. If it does not exist, it will be created.
+     * If no class loader is specified, the class loader used to load this class is used.
+     *
+     * @param classLoader The class loader for which we will retrieve or build the configuration
      *
-     * @param classLoader The class loader for which we will retrieve or build
-     *                    the configuration
      * @return the log configuration
      */
     protected synchronized ClassLoaderLogInfo getClassLoaderInfo(ClassLoader classLoader) {
@@ -423,10 +410,10 @@ public class ClassLoaderLogManager extends LogManager {
      * Read configuration for the specified classloader.
      *
      * @param classLoader The classloader
+     *
      * @throws IOException Error reading configuration
      */
-    protected synchronized void readConfiguration(ClassLoader classLoader)
-        throws IOException {
+    protected synchronized void readConfiguration(ClassLoader classLoader) throws IOException {
 
         InputStream is = null;
         // Special case for URL classloaders which are used in containers:
@@ -437,22 +424,19 @@ public class ClassLoaderLogManager extends LogManager {
                     is = classLoader.getResourceAsStream("logging.properties");
                 }
             } else if (classLoader instanceof URLClassLoader) {
-                URL logConfig = ((URLClassLoader)classLoader).findResource("logging.properties");
-
-                if(null != logConfig) {
-                    if(Boolean.getBoolean(DEBUG_PROPERTY)) {
-                        System.err.println(getClass().getName()
-                                           + ".readConfiguration(): "
-                                           + "Found logging.properties at "
-                                           + logConfig);
+                URL logConfig = ((URLClassLoader) classLoader).findResource("logging.properties");
+
+                if (null != logConfig) {
+                    if (Boolean.getBoolean(DEBUG_PROPERTY)) {
+                        System.err.println(getClass().getName() + ".readConfiguration(): " +
+                                "Found logging.properties at " + logConfig);
                     }
 
                     is = classLoader.getResourceAsStream("logging.properties");
                 } else {
-                    if(Boolean.getBoolean(DEBUG_PROPERTY)) {
-                        System.err.println(getClass().getName()
-                                           + ".readConfiguration(): "
-                                           + "Found no logging.properties");
+                    if (Boolean.getBoolean(DEBUG_PROPERTY)) {
+                        System.err.println(
+                                getClass().getName() + ".readConfiguration(): " + "Found no logging.properties");
                     }
                 }
             }
@@ -465,9 +449,11 @@ public class ClassLoaderLogManager extends LogManager {
                 if (log != null) {
                     Permission perm = ace.getPermission();
                     if (perm instanceof FilePermission && perm.getActions().equals("read")) {
-                        log.warning("Reading " + perm.getName() + " is not permitted. See \"per context logging\" in the default catalina.policy file.");
+                        log.warning("Reading " + perm.getName() +
+                                " is not permitted. See \"per context logging\" in the default catalina.policy file.");
                     } else {
-                        log.warning("Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file.");
+                        log.warning(
+                                "Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file.");
                         log.warning("Original error was: " + ace.getMessage());
                     }
                 }
@@ -485,9 +471,8 @@ public class ClassLoaderLogManager extends LogManager {
             }
             // Try the default JVM configuration
             if (is == null) {
-                File defaultFile = new File(new File(System.getProperty("java.home"),
-                                                     isJava9 ? "conf" : "lib"),
-                    "logging.properties");
+                File defaultFile = new File(new File(System.getProperty("java.home"), isJava9 ? "conf" : "lib"),
+                        "logging.properties");
                 try {
                     is = new FileInputStream(defaultFile);
                 } catch (IOException e) {
@@ -510,8 +495,7 @@ public class ClassLoaderLogManager extends LogManager {
                 localRootLogger.setParent(info.rootNode.logger);
             }
         }
-        ClassLoaderLogInfo info =
-            new ClassLoaderLogInfo(new LogNode(null, localRootLogger));
+        ClassLoaderLogInfo info = new ClassLoaderLogInfo(new LogNode(null, localRootLogger));
         classLoaderLoggers.put(classLoader, info);
 
         if (is != null) {
@@ -535,12 +519,12 @@ public class ClassLoaderLogManager extends LogManager {
     /**
      * Load specified configuration.
      *
-     * @param is InputStream to the properties file
+     * @param is          InputStream to the properties file
      * @param classLoader for which the configuration will be loaded
+     *
      * @throws IOException If something wrong happens during loading
      */
-    protected synchronized void readConfiguration(InputStream is, ClassLoader classLoader)
-        throws IOException {
+    protected synchronized void readConfiguration(InputStream is, ClassLoader classLoader) throws IOException {
 
         ClassLoaderLogInfo info = classLoaderLoggers.get(classLoader);
 
@@ -582,8 +566,7 @@ public class ClassLoaderLogManager extends LogManager {
                 }
                 try {
                     this.prefix.set(prefix);
-                    Handler handler = (Handler) classLoader.loadClass(
-                            handlerClassName).getConstructor().newInstance();
+                    Handler handler = (Handler) classLoader.loadClass(handlerClassName).getConstructor().newInstance();
                     // The specification strongly implies all configuration should be done
                     // during the creation of the handler object.
                     // This includes setting level, filter, formatter and encoding.
@@ -610,8 +593,7 @@ public class ClassLoaderLogManager extends LogManager {
      * @param logger The logger
      * @param parent The parent logger
      */
-    protected static void doSetParentLogger(final Logger logger,
-            final Logger parent) {
+    protected static void doSetParentLogger(final Logger logger, final Logger parent) {
         AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
             logger.setParent(parent);
             return null;
@@ -623,6 +605,7 @@ public class ClassLoaderLogManager extends LogManager {
      * System property replacement in the given string.
      *
      * @param str The original string
+     *
      * @return the modified string
      */
     protected String replace(String str) {
@@ -678,15 +661,13 @@ public class ClassLoaderLogManager extends LogManager {
 
 
     /**
-     * Obtain the class loader to use to lookup loggers, obtain configuration
-     * etc. The search order is:
+     * Obtain the class loader to use to lookup loggers, obtain configuration etc. The search order is:
      * <ol>
      * <li>Thread.currentThread().getContextClassLoader()</li>
      * <li>The class laoder of this class</li>
      * </ol>
      *
-     * @return The class loader to use to lookup loggers, obtain configuration
-     *         etc.
+     * @return The class loader to use to lookup loggers, obtain configuration etc.
      */
     static ClassLoader getClassLoader() {
         ClassLoader result = Thread.currentThread().getContextClassLoader();
@@ -783,8 +764,7 @@ public class ClassLoaderLogManager extends LogManager {
 
 
     /**
-     * This class is needed to instantiate the root of each per classloader
-     * hierarchy.
+     * This class is needed to instantiate the root of each per classloader hierarchy.
      */
     protected static class RootLogger extends Logger {
         public RootLogger() {
diff --git a/java/org/apache/juli/DateFormatCache.java b/java/org/apache/juli/DateFormatCache.java
index 517795530d..2016c113e6 100644
--- a/java/org/apache/juli/DateFormatCache.java
+++ b/java/org/apache/juli/DateFormatCache.java
@@ -23,21 +23,24 @@ import java.util.Locale;
 import java.util.TimeZone;
 
 /**
- * <p>Cache structure for SimpleDateFormat formatted timestamps based on
- * seconds.</p>
- *
- * <p>Millisecond formatting using S is not supported. You should add the
- * millisecond information after getting back the second formatting.</p>
- *
- * <p>The cache consists of entries for a consecutive range of
- * seconds. The length of the range is configurable. It is
- * implemented based on a cyclic buffer. New entries shift the range.</p>
- *
- * <p>The cache is not threadsafe. It can be used without synchronization
- * via thread local instances, or with synchronization as a global cache.</p>
- *
- * <p>The cache can be created with a parent cache to build a cache hierarchy.
- * Access to the parent cache is threadsafe.</p>
+ * <p>
+ * Cache structure for SimpleDateFormat formatted timestamps based on seconds.
+ * </p>
+ * <p>
+ * Millisecond formatting using S is not supported. You should add the millisecond information after getting back the
+ * second formatting.
+ * </p>
+ * <p>
+ * The cache consists of entries for a consecutive range of seconds. The length of the range is configurable. It is
+ * implemented based on a cyclic buffer. New entries shift the range.
+ * </p>
+ * <p>
+ * The cache is not threadsafe. It can be used without synchronization via thread local instances, or with
+ * synchronization as a global cache.
+ * </p>
+ * <p>
+ * The cache can be created with a parent cache to build a cache hierarchy. Access to the parent cache is threadsafe.
+ * </p>
  */
 public class DateFormatCache {
 
@@ -52,10 +55,8 @@ public class DateFormatCache {
     private final Cache cache;
 
     /**
-     * Replace the millisecond formatting character 'S' by
-     * some dummy characters in order to make the resulting
-     * formatted time stamps cacheable. Our consumer might
-     * choose to replace the dummy chars with the actual
+     * Replace the millisecond formatting character 'S' by some dummy characters in order to make the resulting
+     * formatted time stamps cacheable. Our consumer might choose to replace the dummy chars with the actual
      * milliseconds because that's relatively cheap.
      */
     private String tidyFormat(String format) {
@@ -82,7 +83,7 @@ public class DateFormatCache {
         this.format = tidyFormat(format);
         Cache parentCache = null;
         if (parent != null) {
-            synchronized(parent) {
+            synchronized (parent) {
                 parentCache = parent.cache;
             }
         }
@@ -129,26 +130,27 @@ public class DateFormatCache {
 
             long seconds = time / 1000;
 
-            /* First step: if we have seen this timestamp
-               during the previous call, return the previous value. */
+            /*
+             * First step: if we have seen this timestamp during the previous call, return the previous value.
+             */
             if (seconds == previousSeconds) {
                 return previousFormat;
             }
 
             /* Second step: Try to locate in cache */
             previousSeconds = seconds;
-            int index = (offset + (int)(seconds - first)) % cacheSize;
+            int index = (offset + (int) (seconds - first)) % cacheSize;
             if (index < 0) {
                 index += cacheSize;
             }
             if (seconds >= first && seconds <= last) {
                 if (cache[index] != null) {
-                    /* Found, so remember for next call and return.*/
+                    /* Found, so remember for next call and return. */
                     previousFormat = cache[index];
                     return previousFormat;
                 }
 
-            /* Third step: not found in cache, adjust cache and add item */
+                /* Third step: not found in cache, adjust cache and add item */
             } else if (seconds >= last + cacheSize || seconds <= first - cacheSize) {
                 first = seconds;
                 last = first + cacheSize - 1;
@@ -173,10 +175,11 @@ public class DateFormatCache {
                 offset = index;
             }
 
-            /* Last step: format new timestamp either using
-             * parent cache or locally. */
+            /*
+             * Last step: format new timestamp either using parent cache or locally.
+             */
             if (parent != null) {
-                synchronized(parent) {
+                synchronized (parent) {
                     previousFormat = parent.getFormat(time);
                 }
             } else {
diff --git a/java/org/apache/juli/FileHandler.java b/java/org/apache/juli/FileHandler.java
index 30a47a84a4..3b68c628eb 100644
--- a/java/org/apache/juli/FileHandler.java
+++ b/java/org/apache/juli/FileHandler.java
@@ -50,46 +50,35 @@ import java.util.logging.LogRecord;
 import java.util.regex.Pattern;
 
 /**
- * Implementation of <b>Handler</b> that appends log messages to a file
- * named {prefix}{date}{suffix} in a configured directory.
- *
- * <p>The following configuration properties are available:</p>
- *
+ * Implementation of <b>Handler</b> that appends log messages to a file named {prefix}{date}{suffix} in a configured
+ * directory.
+ * <p>
+ * The following configuration properties are available:
+ * </p>
  * <ul>
- *   <li><code>directory</code> - The directory where to create the log file.
- *    If the path is not absolute, it is relative to the current working
- *    directory of the application. The Apache Tomcat configuration files usually
- *    specify an absolute path for this property,
- *    <code>${catalina.base}/logs</code>
- *    Default value: <code>logs</code></li>
- *   <li><code>rotatable</code> - If <code>true</code>, the log file will be
- *    rotated on the first write past midnight and the filename will be
- *    <code>{prefix}{date}{suffix}</code>, where date is yyyy-MM-dd. If <code>false</code>,
- *    the file will not be rotated and the filename will be <code>{prefix}{suffix}</code>.
- *    Default value: <code>true</code></li>
- *   <li><code>prefix</code> - The leading part of the log file name.
- *    Default value: <code>juli.</code></li>
- *   <li><code>suffix</code> - The trailing part of the log file name. Default value: <code>.log</code></li>
- *   <li><code>bufferSize</code> - Configures buffering. The value of <code>0</code>
- *    uses system default buffering (typically an 8K buffer will be used). A
- *    value of <code>&lt;0</code> forces a writer flush upon each log write. A
- *    value <code>&gt;0</code> uses a BufferedOutputStream with the defined
- *    value but note that the system default buffering will also be
- *    applied. Default value: <code>-1</code></li>
- *   <li><code>encoding</code> - Character set used by the log file. Default value:
- *    empty string, which means to use the system default character set.</li>
- *   <li><code>level</code> - The level threshold for this Handler. See the
- *    <code>java.util.logging.Level</code> class for the possible levels.
- *    Default value: <code>ALL</code></li>
- *   <li><code>filter</code> - The <code>java.util.logging.Filter</code>
- *    implementation class name for this Handler. Default value: unset</li>
- *   <li><code>formatter</code> - The <code>java.util.logging.Formatter</code>
- *    implementation class name for this Handler. Default value:
- *    <code>org.apache.juli.OneLineFormatter</code></li>
- *   <li><code>maxDays</code> - The maximum number of days to keep the log
- *    files. If the specified value is <code>&lt;=0</code> then the log files
- *    will be kept on the file system forever, otherwise they will be kept the
- *    specified maximum days. Default value: <code>-1</code>.</li>
+ * <li><code>directory</code> - The directory where to create the log file. If the path is not absolute, it is relative
+ * to the current working directory of the application. The Apache Tomcat configuration files usually specify an
+ * absolute path for this property, <code>${catalina.base}/logs</code> Default value: <code>logs</code></li>
+ * <li><code>rotatable</code> - If <code>true</code>, the log file will be rotated on the first write past midnight and
+ * the filename will be <code>{prefix}{date}{suffix}</code>, where date is yyyy-MM-dd. If <code>false</code>, the file
+ * will not be rotated and the filename will be <code>{prefix}{suffix}</code>. Default value: <code>true</code></li>
+ * <li><code>prefix</code> - The leading part of the log file name. Default value: <code>juli.</code></li>
+ * <li><code>suffix</code> - The trailing part of the log file name. Default value: <code>.log</code></li>
+ * <li><code>bufferSize</code> - Configures buffering. The value of <code>0</code> uses system default buffering
+ * (typically an 8K buffer will be used). A value of <code>&lt;0</code> forces a writer flush upon each log write. A
+ * value <code>&gt;0</code> uses a BufferedOutputStream with the defined value but note that the system default
+ * buffering will also be applied. Default value: <code>-1</code></li>
+ * <li><code>encoding</code> - Character set used by the log file. Default value: empty string, which means to use the
+ * system default character set.</li>
+ * <li><code>level</code> - The level threshold for this Handler. See the <code>java.util.logging.Level</code> class for
+ * the possible levels. Default value: <code>ALL</code></li>
+ * <li><code>filter</code> - The <code>java.util.logging.Filter</code> implementation class name for this Handler.
+ * Default value: unset</li>
+ * <li><code>formatter</code> - The <code>java.util.logging.Formatter</code> implementation class name for this Handler.
+ * Default value: <code>org.apache.juli.OneLineFormatter</code></li>
+ * <li><code>maxDays</code> - The maximum number of days to keep the log files. If the specified value is
+ * <code>&lt;=0</code> then the log files will be kept on the file system forever, otherwise they will be kept the
+ * specified maximum days. Default value: <code>-1</code>.</li>
  * </ul>
  */
 public class FileHandler extends Handler {
@@ -99,8 +88,8 @@ public class FileHandler extends Handler {
     public static final int DEFAULT_BUFFER_SIZE = -1;
 
 
-    private static final ExecutorService DELETE_FILES_SERVICE =
-            Executors.newSingleThreadExecutor(new ThreadFactory("FileHandlerLogFilesCleaner-"));
+    private static final ExecutorService DELETE_FILES_SERVICE = Executors
+            .newSingleThreadExecutor(new ThreadFactory("FileHandlerLogFilesCleaner-"));
 
     // ------------------------------------------------------------ Constructor
 
@@ -120,8 +109,8 @@ public class FileHandler extends Handler {
     }
 
 
-    public FileHandler(String directory, String prefix, String suffix, Integer maxDays,
-            Boolean rotatable, Integer bufferSize) {
+    public FileHandler(String directory, String prefix, String suffix, Integer maxDays, Boolean rotatable,
+            Integer bufferSize) {
         this.directory = directory;
         this.prefix = prefix;
         this.suffix = suffix;
@@ -138,8 +127,7 @@ public class FileHandler extends Handler {
 
 
     /**
-     * The as-of date for the currently open log file, or a zero-length
-     * string if there is no open log file.
+     * The as-of date for the currently open log file, or a zero-length string if there is no open log file.
      */
     private volatile String date = "";
 
@@ -193,8 +181,7 @@ public class FileHandler extends Handler {
 
 
     /**
-     * Represents a file name pattern of type {prefix}{date}{suffix}.
-     * The date is YYYY-MM-DD
+     * Represents a file name pattern of type {prefix}{date}{suffix}. The date is YYYY-MM-DD
      */
     private Pattern pattern;
 
@@ -205,7 +192,7 @@ public class FileHandler extends Handler {
     /**
      * Format and publish a <code>LogRecord</code>.
      *
-     * @param  record  description of the log event
+     * @param record description of the log event
      */
     @Override
     public void publish(LogRecord record) {
@@ -256,8 +243,8 @@ public class FileHandler extends Handler {
                         writer.flush();
                     }
                 } else {
-                    reportError("FileHandler is closed or not yet initialized, unable to log ["
-                            + result + "]", null, ErrorManager.WRITE_FAILURE);
+                    reportError("FileHandler is closed or not yet initialized, unable to log [" + result + "]", null,
+                            ErrorManager.WRITE_FAILURE);
                 }
             } catch (Exception e) {
                 reportError(null, e, ErrorManager.WRITE_FAILURE);
@@ -328,7 +315,7 @@ public class FileHandler extends Handler {
         Timestamp ts = new Timestamp(System.currentTimeMillis());
         date = ts.toString().substring(0, 10);
 
-        String className = this.getClass().getName(); //allow classes to override
+        String className = this.getClass().getName(); // allow classes to override
 
         ClassLoader cl = ClassLoaderLogManager.getClassLoader();
 
@@ -347,17 +334,15 @@ public class FileHandler extends Handler {
         }
 
         // https://bz.apache.org/bugzilla/show_bug.cgi?id=61232
-        boolean shouldCheckForRedundantSeparator =
-                !rotatable.booleanValue() && !prefix.isEmpty() && !suffix.isEmpty();
+        boolean shouldCheckForRedundantSeparator = !rotatable.booleanValue() && !prefix.isEmpty() && !suffix.isEmpty();
         // assuming separator is just one char, if there are use cases with
         // more, the notion of separator might be introduced
-        if (shouldCheckForRedundantSeparator &&
-                (prefix.charAt(prefix.length() - 1) == suffix.charAt(0))) {
+        if (shouldCheckForRedundantSeparator && (prefix.charAt(prefix.length() - 1) == suffix.charAt(0))) {
             suffix = suffix.substring(1);
         }
 
-        pattern = Pattern.compile("^(" + Pattern.quote(prefix) + ")\\d{4}-\\d{1,2}-\\d{1,2}("
-                + Pattern.quote(suffix) + ")$");
+        pattern = Pattern
+                .compile("^(" + Pattern.quote(prefix) + ")\\d{4}-\\d{1,2}-\\d{1,2}(" + Pattern.quote(suffix) + ")$");
 
         if (maxDays == null) {
             String sMaxDays = getProperty(className + ".maxDays", String.valueOf(DEFAULT_MAX_DAYS));
@@ -369,8 +354,7 @@ public class FileHandler extends Handler {
         }
 
         if (bufferSize == null) {
-            String sBufferSize = getProperty(className + ".bufferSize",
-                    String.valueOf(DEFAULT_BUFFER_SIZE));
+            String sBufferSize = getProperty(className + ".bufferSize", String.valueOf(DEFAULT_BUFFER_SIZE));
             try {
                 bufferSize = Integer.valueOf(sBufferSize);
             } catch (NumberFormatException ignore) {
@@ -405,8 +389,7 @@ public class FileHandler extends Handler {
         String formatterName = getProperty(className + ".formatter", null);
         if (formatterName != null) {
             try {
-                setFormatter((Formatter) cl.loadClass(
-                        formatterName).getConstructor().newInstance());
+                setFormatter((Formatter) cl.loadClass(formatterName).getConstructor().newInstance());
             } catch (Exception e) {
                 // Ignore and fallback to defaults
                 setFormatter(new OneLineFormatter());
@@ -453,8 +436,7 @@ public class FileHandler extends Handler {
         FileOutputStream fos = null;
         OutputStream os = null;
         try {
-            File pathname = new File(dir.getAbsoluteFile(), prefix
-                    + (rotatable.booleanValue() ? date : "") + suffix);
+            File pathname = new File(dir.getAbsoluteFile(), prefix + (rotatable.booleanValue() ? date : "") + suffix);
             File parent = pathname.getParentFile();
             if (!parent.mkdirs() && !parent.isDirectory()) {
                 reportError("Unable to create [" + parent + "]", null, ErrorManager.OPEN_FAILURE);
@@ -465,8 +447,7 @@ public class FileHandler extends Handler {
             fos = new FileOutputStream(pathname, true);
             os = bufferSize.intValue() > 0 ? new BufferedOutputStream(fos, bufferSize.intValue()) : fos;
             writer = new PrintWriter(
-                    (encoding != null) ? new OutputStreamWriter(os, encoding)
-                                       : new OutputStreamWriter(os), false);
+                    (encoding != null) ? new OutputStreamWriter(os, encoding) : new OutputStreamWriter(os), false);
             writer.write(getFormatter().getHead(this));
         } catch (Exception e) {
             reportError(null, e, ErrorManager.OPEN_FAILURE);
diff --git a/java/org/apache/juli/JdkLoggerFormatter.java b/java/org/apache/juli/JdkLoggerFormatter.java
index d38b7d561c..80489b90b6 100644
--- a/java/org/apache/juli/JdkLoggerFormatter.java
+++ b/java/org/apache/juli/JdkLoggerFormatter.java
@@ -20,43 +20,40 @@ import java.util.logging.Formatter;
 import java.util.logging.LogRecord;
 
 /**
- * A more compact formatter.
+ * A more compact formatter. Equivalent log4j config:
  *
- * Equivalent log4j config:
- *   <pre>
+ * <pre>
  *  log4j.rootCategory=WARN, A1
  *  log4j.appender.A1=org.apache.log4j.ConsoleAppender
  *  log4j.appender.A1.layout=org.apache.log4j.PatternLayout
  *  log4j.appender.A1.Target=System.err
  *  log4j.appender.A1.layout.ConversionPattern=%r %-15.15c{2} %-1.1p %m %n
- *  </pre>
- *
- * Example:
- *  1130122891846 Http11BaseProtocol I Initializing Coyote HTTP/1.1 on http-8800
+ * </pre>
  *
+ * Example: 1130122891846 Http11BaseProtocol I Initializing Coyote HTTP/1.1 on http-8800
  *
  * @author Costin Manolache
  */
 public class JdkLoggerFormatter extends Formatter {
 
     // values from JDK Level
-    public static final int LOG_LEVEL_TRACE  = 400;
-    public static final int LOG_LEVEL_DEBUG  = 500;
-    public static final int LOG_LEVEL_INFO   = 800;
-    public static final int LOG_LEVEL_WARN   = 900;
-    public static final int LOG_LEVEL_ERROR  = 1000;
-    public static final int LOG_LEVEL_FATAL  = 1000;
+    public static final int LOG_LEVEL_TRACE = 400;
+    public static final int LOG_LEVEL_DEBUG = 500;
+    public static final int LOG_LEVEL_INFO = 800;
+    public static final int LOG_LEVEL_WARN = 900;
+    public static final int LOG_LEVEL_ERROR = 1000;
+    public static final int LOG_LEVEL_FATAL = 1000;
 
     @Override
     public String format(LogRecord record) {
-        Throwable t=record.getThrown();
-        int level=record.getLevel().intValue();
-        String name=record.getLoggerName();
-        long time=record.getMillis();
-        String message=formatMessage(record);
+        Throwable t = record.getThrown();
+        int level = record.getLevel().intValue();
+        String name = record.getLoggerName();
+        long time = record.getMillis();
+        String message = formatMessage(record);
 
 
-        if( name.indexOf('.') >= 0 ) {
+        if (name.indexOf('.') >= 0) {
             name = name.substring(name.lastIndexOf('.') + 1);
         }
 
@@ -66,18 +63,31 @@ public class JdkLoggerFormatter extends Formatter {
         buf.append(time);
 
         // pad to 8 to make it more readable
-        for( int i=0; i<8-buf.length(); i++ ) { buf.append(' '); }
+        for (int i = 0; i < 8 - buf.length(); i++) {
+            buf.append(' ');
+        }
 
-        //      Append a readable representation of the log level.
-        switch(level) {
-         case LOG_LEVEL_TRACE: buf.append(" T "); break;
-         case LOG_LEVEL_DEBUG: buf.append(" D "); break;
-         case LOG_LEVEL_INFO:  buf.append(" I ");  break;
-         case LOG_LEVEL_WARN:  buf.append(" W ");  break;
-         case LOG_LEVEL_ERROR: buf.append(" E "); break;
-         //case : buf.append(" F "); break;
-         default: buf.append("   ");
-         }
+        // Append a readable representation of the log level.
+        switch (level) {
+            case LOG_LEVEL_TRACE:
+                buf.append(" T ");
+                break;
+            case LOG_LEVEL_DEBUG:
+                buf.append(" D ");
+                break;
+            case LOG_LEVEL_INFO:
+                buf.append(" I ");
+                break;
+            case LOG_LEVEL_WARN:
+                buf.append(" W ");
+                break;
+            case LOG_LEVEL_ERROR:
+                buf.append(" E ");
+                break;
+            // case : buf.append(" F "); break;
+            default:
+                buf.append("   ");
+        }
 
 
         // Append the name of the log instance if so configured
@@ -85,17 +95,19 @@ public class JdkLoggerFormatter extends Formatter {
         buf.append(' ');
 
         // pad to 20 chars
-        for( int i=0; i<8-buf.length(); i++ ) { buf.append(' '); }
+        for (int i = 0; i < 8 - buf.length(); i++) {
+            buf.append(' ');
+        }
 
         // Append the message
         buf.append(message);
 
         // Append stack trace if not null
-        if(t != null) {
+        if (t != null) {
             buf.append(System.lineSeparator());
 
-            java.io.StringWriter sw= new java.io.StringWriter(1024);
-            java.io.PrintWriter pw= new java.io.PrintWriter(sw);
+            java.io.StringWriter sw = new java.io.StringWriter(1024);
+            java.io.PrintWriter pw = new java.io.PrintWriter(sw);
             t.printStackTrace(pw);
             pw.close();
             buf.append(sw.toString());
diff --git a/java/org/apache/juli/OneLineFormatter.java b/java/org/apache/juli/OneLineFormatter.java
index 374e9119c5..ccce077c0a 100644
--- a/java/org/apache/juli/OneLineFormatter.java
+++ b/java/org/apache/juli/OneLineFormatter.java
@@ -29,9 +29,8 @@ import java.util.logging.LogManager;
 import java.util.logging.LogRecord;
 
 /**
- * Provides same information as default log format but on a single line to make
- * it easier to grep the logs. The only exception is stacktraces which are
- * always preceded by whitespace to make it simple to skip them.
+ * Provides same information as default log format but on a single line to make it easier to grep the logs. The only
+ * exception is stacktraces which are always preceded by whitespace to make it simple to skip them.
  */
 /*
  * Date processing based on AccessLogValve.
@@ -42,8 +41,8 @@ public class OneLineFormatter extends Formatter {
     private static final Object threadMxBeanLock = new Object();
     private static volatile ThreadMXBean threadMxBean = null;
     private static final int THREAD_NAME_CACHE_SIZE = 10000;
-    private static final ThreadLocal<ThreadNameCache> threadNameCache =
-            ThreadLocal.withInitial(() -> new ThreadNameCache(THREAD_NAME_CACHE_SIZE));
+    private static final ThreadLocal<ThreadNameCache> threadNameCache = ThreadLocal
+            .withInitial(() -> new ThreadNameCache(THREAD_NAME_CACHE_SIZE));
 
     /* Timestamp format */
     private static final String DEFAULT_TIME_FORMAT = "dd-MMM-yyyy HH:mm:ss.SSS";
@@ -67,8 +66,7 @@ public class OneLineFormatter extends Formatter {
 
 
     public OneLineFormatter() {
-        String timeFormat = LogManager.getLogManager().getProperty(
-                OneLineFormatter.class.getName() + ".timeFormat");
+        String timeFormat = LogManager.getLogManager().getProperty(OneLineFormatter.class.getName() + ".timeFormat");
         if (timeFormat == null) {
             timeFormat = DEFAULT_TIME_FORMAT;
         }
@@ -79,14 +77,13 @@ public class OneLineFormatter extends Formatter {
     /**
      * Specify the time format to use for time stamps in log messages.
      *
-     * @param timeFormat The format to use using the
-     *                   {@link java.text.SimpleDateFormat} syntax
+     * @param timeFormat The format to use using the {@link java.text.SimpleDateFormat} syntax
      */
     public void setTimeFormat(final String timeFormat) {
         final String cachedTimeFormat;
 
         if (timeFormat.endsWith(".SSS")) {
-            cachedTimeFormat = timeFormat.substring(0,  timeFormat.length() - 4);
+            cachedTimeFormat = timeFormat.substring(0, timeFormat.length() - 4);
             millisHandling = MillisHandling.APPEND;
         } else if (timeFormat.contains("SSS")) {
             millisHandling = MillisHandling.REPLACE_SSS;
@@ -102,9 +99,9 @@ public class OneLineFormatter extends Formatter {
             cachedTimeFormat = timeFormat;
         }
 
-        final DateFormatCache globalDateCache =
-                new DateFormatCache(globalCacheSize, cachedTimeFormat, null);
-        localDateCache = ThreadLocal.withInitial(() -> new DateFormatCache(localCacheSize, cachedTimeFormat, globalDateCache));
+        final DateFormatCache globalDateCache = new DateFormatCache(globalCacheSize, cachedTimeFormat, null);
+        localDateCache = ThreadLocal
+                .withInitial(() -> new DateFormatCache(localCacheSize, cachedTimeFormat, globalDateCache));
     }
 
 
@@ -211,16 +208,14 @@ public class OneLineFormatter extends Formatter {
 
 
     /**
-     * LogRecord has threadID but no thread name.
-     * LogRecord uses an int for thread ID but thread IDs are longs.
-     * If the real thread ID > (Integer.MAXVALUE / 2) LogRecord uses it's own
-     * ID in an effort to avoid clashes due to overflow.
+     * LogRecord has threadID but no thread name. LogRecord uses an int for thread ID but thread IDs are longs. If the
+     * real thread ID > (Integer.MAXVALUE / 2) LogRecord uses it's own ID in an effort to avoid clashes due to overflow.
      * <p>
-     * Words fail me to describe what I think of the design decision to use an
-     * int in LogRecord for a long value and the resulting mess that follows.
+     * Words fail me to describe what I think of the design decision to use an int in LogRecord for a long value and the
+     * resulting mess that follows.
      */
     private static String getThreadName(int logRecordThreadId) {
-        Map<Integer,String> cache = threadNameCache.get();
+        Map<Integer, String> cache = threadNameCache.get();
         String result = cache.get(Integer.valueOf(logRecordThreadId));
 
         if (result != null) {
@@ -238,8 +233,7 @@ public class OneLineFormatter extends Formatter {
                     }
                 }
             }
-            ThreadInfo threadInfo =
-                    threadMxBean.getThreadInfo(logRecordThreadId);
+            ThreadInfo threadInfo = threadMxBean.getThreadInfo(logRecordThreadId);
             if (threadInfo == null) {
                 return Long.toString(logRecordThreadId);
             }
@@ -252,7 +246,7 @@ public class OneLineFormatter extends Formatter {
     }
 
 
-    private static class ThreadNameCache extends LinkedHashMap<Integer,String> {
+    private static class ThreadNameCache extends LinkedHashMap<Integer, String> {
 
         private static final long serialVersionUID = 1L;
 
@@ -270,8 +264,8 @@ public class OneLineFormatter extends Formatter {
 
 
     /*
-     * Minimal implementation to indent the printing of stack traces. This
-     * implementation depends on Throwable using WrappedPrintWriter.
+     * Minimal implementation to indent the printing of stack traces. This implementation depends on Throwable using
+     * WrappedPrintWriter.
      */
     private static class IndentingPrintWriter extends PrintWriter {
 
@@ -288,10 +282,6 @@ public class OneLineFormatter extends Formatter {
 
 
     private static enum MillisHandling {
-        NONE,
-        APPEND,
-        REPLACE_S,
-        REPLACE_SS,
-        REPLACE_SSS,
+        NONE, APPEND, REPLACE_S, REPLACE_SS, REPLACE_SSS,
     }
 }
diff --git a/java/org/apache/juli/VerbatimFormatter.java b/java/org/apache/juli/VerbatimFormatter.java
index d460971e7a..1c90a0ff1e 100644
--- a/java/org/apache/juli/VerbatimFormatter.java
+++ b/java/org/apache/juli/VerbatimFormatter.java
@@ -20,11 +20,9 @@ import java.util.logging.Formatter;
 import java.util.logging.LogRecord;
 
 /**
- * Outputs the just the log message with no additional elements. Stack traces
- * are not logged. Log messages are separated by
- * <code>System.lineSeparator()</code>. This is intended for use
- * by access logs and the like that need complete control over the output
- * format.
+ * Outputs the just the log message with no additional elements. Stack traces are not logged. Log messages are separated
+ * by <code>System.lineSeparator()</code>. This is intended for use by access logs and the like that need complete
+ * control over the output format.
  */
 public class VerbatimFormatter extends Formatter {
 
diff --git a/java/org/apache/juli/WebappProperties.java b/java/org/apache/juli/WebappProperties.java
index b524c5a5c4..8948702b51 100644
--- a/java/org/apache/juli/WebappProperties.java
+++ b/java/org/apache/juli/WebappProperties.java
@@ -17,49 +17,41 @@
 package org.apache.juli;
 
 /**
- * An interface intended for use by class loaders associated with a web
- * application that enables them to provide additional information to JULI about
- * the web application with which they are associated. For any web application
- * the combination of {@link #getWebappName()}, {@link #getHostName()} and
- * {@link #getServiceName()} must be unique.
+ * An interface intended for use by class loaders associated with a web application that enables them to provide
+ * additional information to JULI about the web application with which they are associated. For any web application the
+ * combination of {@link #getWebappName()}, {@link #getHostName()} and {@link #getServiceName()} must be unique.
  */
 public interface WebappProperties {
 
     /**
-     * Returns a name for the logging system to use for the web application, if
-     * any, associated with the class loader.
+     * Returns a name for the logging system to use for the web application, if any, associated with the class loader.
      *
-     * @return The name to use for the web application or null if none is
-     *         available.
+     * @return The name to use for the web application or null if none is available.
      */
     String getWebappName();
 
     /**
-     * Returns a name for the logging system to use for the Host where the
-     * web application, if any, associated with the class loader is deployed.
+     * Returns a name for the logging system to use for the Host where the web application, if any, associated with the
+     * class loader is deployed.
      *
-     * @return The name to use for the Host where the web application is
-     * deployed or null if none is available.
+     * @return The name to use for the Host where the web application is deployed or null if none is available.
      */
     String getHostName();
 
     /**
-     * Returns a name for the logging system to use for the Service where the
-     * Host, if any, associated with the class loader is deployed.
+     * Returns a name for the logging system to use for the Service where the Host, if any, associated with the class
+     * loader is deployed.
      *
-     * @return The name to use for the Service where the Host is deployed or
-     * null if none is available.
+     * @return The name to use for the Service where the Host is deployed or null if none is available.
      */
     String getServiceName();
 
     /**
-     * Enables JULI to determine if the web application includes a local
-     * configuration without JULI having to look for the file which it may not
-     * have permission to do when running under a SecurityManager.
+     * Enables JULI to determine if the web application includes a local configuration without JULI having to look for
+     * the file which it may not have permission to do when running under a SecurityManager.
      *
-     * @return {@code true} if the web application includes a logging
-     *         configuration at the standard location of
-     *         /WEB-INF/classes/logging.properties.
+     * @return {@code true} if the web application includes a logging configuration at the standard location of
+     *             /WEB-INF/classes/logging.properties.
      */
     boolean hasLoggingConfig();
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org


[tomcat] 07/07: Review all uses of LinkedHashMap#removeEldestEntry

Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

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

commit 3dab9abcee4fe8675089af8f94ff5c927635cf7e
Author: Mark Thomas <ma...@apache.org>
AuthorDate: Tue Jan 24 10:16:41 2023 +0000

    Review all uses of LinkedHashMap#removeEldestEntry
    
    Ensure FIFO or LRU is used as appropriate.
    Add/expand existing comments to make intentions clearer.
    Don't override default load factor to retain size/performance balance.
---
 java/org/apache/catalina/authenticator/DigestAuthenticator.java | 4 ++++
 java/org/apache/catalina/filters/CsrfPreventionFilter.java      | 6 ++++++
 java/org/apache/catalina/realm/LockOutRealm.java                | 7 +++++--
 java/org/apache/catalina/tribes/util/StringManager.java         | 9 ++++-----
 java/org/apache/juli/OneLineFormatter.java                      | 4 ++++
 java/org/apache/tomcat/util/res/StringManager.java              | 9 ++++-----
 6 files changed, 27 insertions(+), 12 deletions(-)

diff --git a/java/org/apache/catalina/authenticator/DigestAuthenticator.java b/java/org/apache/catalina/authenticator/DigestAuthenticator.java
index e43fabd244..5588119787 100644
--- a/java/org/apache/catalina/authenticator/DigestAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/DigestAuthenticator.java
@@ -376,6 +376,10 @@ public class DigestAuthenticator extends AuthenticatorBase {
             setOpaque(sessionIdGenerator.generateSessionId());
         }
 
+        /*
+         * This is a FIFO cache as using an older nonce should not delay its removal from the cache in favour of more
+         * recent values.
+         */
         nonces = new LinkedHashMap<String, DigestAuthenticator.NonceInfo>() {
 
             private static final long serialVersionUID = 1L;
diff --git a/java/org/apache/catalina/filters/CsrfPreventionFilter.java b/java/org/apache/catalina/filters/CsrfPreventionFilter.java
index 5568c4cc6d..9c2d7549c1 100644
--- a/java/org/apache/catalina/filters/CsrfPreventionFilter.java
+++ b/java/org/apache/catalina/filters/CsrfPreventionFilter.java
@@ -343,6 +343,12 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
     }
 
 
+    /**
+     * Despite its name, this is a FIFO cache not an LRU cache. Using an older nonce should not delay its removal from
+     * the cache in favour of more recent values.
+     *
+     * @param <T> The type held by this cache.
+     */
     protected static class LruCache<T> implements NonceCache<T> {
 
         private static final long serialVersionUID = 1L;
diff --git a/java/org/apache/catalina/realm/LockOutRealm.java b/java/org/apache/catalina/realm/LockOutRealm.java
index d061fb30cf..7bdee4fab2 100644
--- a/java/org/apache/catalina/realm/LockOutRealm.java
+++ b/java/org/apache/catalina/realm/LockOutRealm.java
@@ -81,8 +81,11 @@ public class LockOutRealm extends CombinedRealm {
      */
     @Override
     protected synchronized void startInternal() throws LifecycleException {
-        // Configure the list of failed users to delete the oldest entry once it
-        // exceeds the specified size
+        /*
+         * Configure the list of failed users to delete the oldest entry once it exceeds the specified size. This is an
+         * LRU cache so if the cache size is exceeded the users who most recently failed authentication will be
+         * retained.
+         */
         failedUsers = new LinkedHashMap<String, LockRecord>(cacheSize, 0.75f, true) {
             private static final long serialVersionUID = 1L;
 
diff --git a/java/org/apache/catalina/tribes/util/StringManager.java b/java/org/apache/catalina/tribes/util/StringManager.java
index fc4b8b5b21..4e349233bd 100644
--- a/java/org/apache/catalina/tribes/util/StringManager.java
+++ b/java/org/apache/catalina/tribes/util/StringManager.java
@@ -213,12 +213,11 @@ public class StringManager {
         Map<Locale, StringManager> map = managers.get(packageName);
         if (map == null) {
             /*
-             * Don't want the HashMap to be expanded beyond LOCALE_CACHE_SIZE. Expansion occurs when size() exceeds
-             * capacity. Therefore keep size at or below capacity. removeEldestEntry() executes after insertion
-             * therefore the test for removal needs to use one less than the maximum desired size
-             *
+             * Don't want the HashMap size to exceed LOCALE_CACHE_SIZE. Expansion occurs when size() exceeds capacity.
+             * Therefore keep size at or below capacity. removeEldestEntry() executes after insertion therefore the test
+             * for removal needs to use one less than the maximum desired size. Note this is an LRU cache.
              */
-            map = new LinkedHashMap<Locale, StringManager>(LOCALE_CACHE_SIZE, 1, true) {
+            map = new LinkedHashMap<Locale, StringManager>(LOCALE_CACHE_SIZE, 0.75f, true) {
                 private static final long serialVersionUID = 1L;
 
                 @Override
diff --git a/java/org/apache/juli/OneLineFormatter.java b/java/org/apache/juli/OneLineFormatter.java
index ccce077c0a..11993258dc 100644
--- a/java/org/apache/juli/OneLineFormatter.java
+++ b/java/org/apache/juli/OneLineFormatter.java
@@ -246,6 +246,9 @@ public class OneLineFormatter extends Formatter {
     }
 
 
+    /*
+     * This is an LRU cache.
+     */
     private static class ThreadNameCache extends LinkedHashMap<Integer, String> {
 
         private static final long serialVersionUID = 1L;
@@ -253,6 +256,7 @@ public class OneLineFormatter extends Formatter {
         private final int cacheSize;
 
         public ThreadNameCache(int cacheSize) {
+            super(cacheSize, 0.75f, true);
             this.cacheSize = cacheSize;
         }
 
diff --git a/java/org/apache/tomcat/util/res/StringManager.java b/java/org/apache/tomcat/util/res/StringManager.java
index 094c93727a..fd570c15bd 100644
--- a/java/org/apache/tomcat/util/res/StringManager.java
+++ b/java/org/apache/tomcat/util/res/StringManager.java
@@ -220,12 +220,11 @@ public class StringManager {
         Map<Locale, StringManager> map = managers.get(packageName);
         if (map == null) {
             /*
-             * Don't want the HashMap to be expanded beyond LOCALE_CACHE_SIZE. Expansion occurs when size() exceeds
-             * capacity. Therefore keep size at or below capacity. removeEldestEntry() executes after insertion
-             * therefore the test for removal needs to use one less than the maximum desired size
-             *
+             * Don't want the HashMap size to exceed LOCALE_CACHE_SIZE. Expansion occurs when size() exceeds capacity.
+             * Therefore keep size at or below capacity. removeEldestEntry() executes after insertion therefore the test
+             * for removal needs to use one less than the maximum desired size. Note this is an LRU cache.
              */
-            map = new LinkedHashMap<Locale, StringManager>(LOCALE_CACHE_SIZE, 1, true) {
+            map = new LinkedHashMap<Locale, StringManager>(LOCALE_CACHE_SIZE, 0.75f, true) {
                 private static final long serialVersionUID = 1L;
 
                 @Override


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org