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/02/15 12:02:16 UTC
[tomcat] branch main updated (273b37e350 -> b2ff1076f6)
This is an automated email from the ASF dual-hosted git repository.
markt pushed a change to branch main
in repository https://gitbox.apache.org/repos/asf/tomcat.git
from 273b37e350 Update to use new class name for callback handler
new fb4ec9984a Clean-up (format) - no functional change
new b2ff1076f6 Update clean-up configuration to add removal of redundant modifiers
The 2 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/valves/AbstractAccessLogValve.java | 754 ++++++++++-----------
.../org/apache/catalina/valves/AccessLogValve.java | 136 ++--
java/org/apache/catalina/valves/Constants.java | 3 +-
.../valves/CrawlerSessionManagerValve.java | 38 +-
.../apache/catalina/valves/ErrorReportValve.java | 71 +-
.../catalina/valves/ExtendedAccessLogValve.java | 311 ++++-----
.../apache/catalina/valves/HealthCheckValve.java | 20 +-
.../apache/catalina/valves/JDBCAccessLogValve.java | 257 ++++---
.../catalina/valves/JsonErrorReportValve.java | 21 +-
.../catalina/valves/LoadBalancerDrainingValve.java | 128 ++--
.../apache/catalina/valves/PersistentValve.java | 47 +-
.../catalina/valves/ProxyErrorReportValve.java | 5 +-
.../apache/catalina/valves/RemoteAddrValve.java | 9 +-
.../apache/catalina/valves/RemoteCIDRValve.java | 24 +-
.../apache/catalina/valves/RemoteHostValve.java | 8 +-
java/org/apache/catalina/valves/RemoteIpValve.java | 264 ++++----
.../apache/catalina/valves/RequestFilterValve.java | 186 +++--
java/org/apache/catalina/valves/SSLValve.java | 48 +-
.../org/apache/catalina/valves/SemaphoreValve.java | 98 ++-
.../catalina/valves/StuckThreadDetectionValve.java | 131 ++--
java/org/apache/catalina/valves/ValveBase.java | 44 +-
res/ide-support/eclipse/clean-up-asf-tomcat.xml | 2 +-
22 files changed, 1174 insertions(+), 1431 deletions(-)
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
[tomcat] 01/02: Clean-up (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 main
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit fb4ec9984ae136837397a856ab720256afb4e2be
Author: Mark Thomas <ma...@apache.org>
AuthorDate: Wed Feb 15 11:59:53 2023 +0000
Clean-up (format) - no functional change
---
.../catalina/valves/AbstractAccessLogValve.java | 754 ++++++++++-----------
.../org/apache/catalina/valves/AccessLogValve.java | 136 ++--
java/org/apache/catalina/valves/Constants.java | 3 +-
.../valves/CrawlerSessionManagerValve.java | 38 +-
.../apache/catalina/valves/ErrorReportValve.java | 71 +-
.../catalina/valves/ExtendedAccessLogValve.java | 311 ++++-----
.../apache/catalina/valves/HealthCheckValve.java | 20 +-
.../apache/catalina/valves/JDBCAccessLogValve.java | 257 ++++---
.../catalina/valves/JsonErrorReportValve.java | 21 +-
.../catalina/valves/LoadBalancerDrainingValve.java | 128 ++--
.../apache/catalina/valves/PersistentValve.java | 47 +-
.../catalina/valves/ProxyErrorReportValve.java | 5 +-
.../apache/catalina/valves/RemoteAddrValve.java | 9 +-
.../apache/catalina/valves/RemoteCIDRValve.java | 24 +-
.../apache/catalina/valves/RemoteHostValve.java | 8 +-
java/org/apache/catalina/valves/RemoteIpValve.java | 264 ++++----
.../apache/catalina/valves/RequestFilterValve.java | 186 +++--
java/org/apache/catalina/valves/SSLValve.java | 48 +-
.../org/apache/catalina/valves/SemaphoreValve.java | 98 ++-
.../catalina/valves/StuckThreadDetectionValve.java | 131 ++--
java/org/apache/catalina/valves/ValveBase.java | 44 +-
21 files changed, 1173 insertions(+), 1430 deletions(-)
diff --git a/java/org/apache/catalina/valves/AbstractAccessLogValve.java b/java/org/apache/catalina/valves/AbstractAccessLogValve.java
index f3a664e675..371dc3d550 100644
--- a/java/org/apache/catalina/valves/AbstractAccessLogValve.java
+++ b/java/org/apache/catalina/valves/AbstractAccessLogValve.java
@@ -58,29 +58,27 @@ import org.apache.tomcat.util.net.IPv6Utils;
/**
- * <p>Abstract implementation of the <b>Valve</b> interface that generates a web
- * server access log with the detailed line contents matching a configurable
- * pattern. The syntax of the available patterns is similar to that supported by
- * the <a href="https://httpd.apache.org/">Apache HTTP Server</a>
- * <code>mod_log_config</code> module.</p>
- *
- * <p>Patterns for the logged message may include constant text or any of the
- * following replacement strings, for which the corresponding information
- * from the specified Response is substituted:</p>
+ * <p>
+ * Abstract implementation of the <b>Valve</b> interface that generates a web server access log with the detailed line
+ * contents matching a configurable pattern. The syntax of the available patterns is similar to that supported by the
+ * <a href="https://httpd.apache.org/">Apache HTTP Server</a> <code>mod_log_config</code> module.
+ * </p>
+ * <p>
+ * Patterns for the logged message may include constant text or any of the following replacement strings, for which the
+ * corresponding information from the specified Response is substituted:
+ * </p>
* <ul>
* <li><b><code>%a</code></b> - Remote IP address
* <li><b><code>%A</code></b> - Local IP address
- * <li><b><code>%b</code></b> - Bytes sent, excluding HTTP headers, or '-' if no bytes
- * were sent
+ * <li><b><code>%b</code></b> - Bytes sent, excluding HTTP headers, or '-' if no bytes were sent
* <li><b><code>%B</code></b> - Bytes sent, excluding HTTP headers
- * <li><b><code>%h</code></b> - Remote host name (or IP address if
- * <code>enableLookups</code> for the connector is false)
+ * <li><b><code>%h</code></b> - Remote host name (or IP address if <code>enableLookups</code> for the connector is
+ * false)
* <li><b><code>%H</code></b> - Request protocol
* <li><b><code>%l</code></b> - Remote logical username from identd (always returns '-')
* <li><b><code>%m</code></b> - Request method
* <li><b><code>%p</code></b> - Local port
- * <li><b><code>%q</code></b> - Query string (prepended with a '?' if it exists, otherwise
- * an empty string
+ * <li><b><code>%q</code></b> - Query string (prepended with a '?' if it exists, otherwise an empty string
* <li><b><code>%r</code></b> - First line of the request
* <li><b><code>%s</code></b> - HTTP status code of the response
* <li><b><code>%S</code></b> - User session ID
@@ -93,52 +91,44 @@ import org.apache.tomcat.util.net.IPv6Utils;
* <li><b><code>%F</code></b> - Time taken to commit the response, in milliseconds
* <li><b><code>%I</code></b> - current Request thread name (can compare later with stacktraces)
* <li><b><code>%X</code></b> - Connection status when response is completed:
- * <ul>
- * <li><code>X</code> = Connection aborted before the response completed.</li>
- * <li><code>+</code> = Connection may be kept alive after the response is sent.</li>
- * <li><code>-</code> = Connection will be closed after the response is sent.</li>
- * </ul>
+ * <ul>
+ * <li><code>X</code> = Connection aborted before the response completed.</li>
+ * <li><code>+</code> = Connection may be kept alive after the response is sent.</li>
+ * <li><code>-</code> = Connection will be closed after the response is sent.</li>
* </ul>
- * <p>In addition, the caller can specify one of the following aliases for
- * commonly utilized patterns:</p>
+ * </ul>
+ * <p>
+ * In addition, the caller can specify one of the following aliases for commonly utilized patterns:
+ * </p>
* <ul>
* <li><b>common</b> - <code>%h %l %u %t "%r" %s %b</code>
- * <li><b>combined</b> -
- * <code>%h %l %u %t "%r" %s %b "%{Referer}i" "%{User-Agent}i"</code>
+ * <li><b>combined</b> - <code>%h %l %u %t "%r" %s %b "%{Referer}i" "%{User-Agent}i"</code>
* </ul>
- *
* <p>
- * There is also support to write information from the cookie, incoming
- * header, the Session or something else in the ServletRequest.<br>
- * It is modeled after the
- * <a href="https://httpd.apache.org/">Apache HTTP Server</a> log configuration
- * syntax:</p>
+ * There is also support to write information from the cookie, incoming header, the Session or something else in the
+ * ServletRequest.<br>
+ * It is modeled after the <a href="https://httpd.apache.org/">Apache HTTP Server</a> log configuration syntax:
+ * </p>
* <ul>
* <li><code>%{xxx}i</code> for incoming headers
* <li><code>%{xxx}o</code> for outgoing response headers
* <li><code>%{xxx}c</code> for a specific cookie
* <li><code>%{xxx}r</code> xxx is an attribute in the ServletRequest
* <li><code>%{xxx}s</code> xxx is an attribute in the HttpSession
- * <li><code>%{xxx}t</code> xxx is an enhanced SimpleDateFormat pattern
- * (see Configuration Reference document for details on supported time patterns)
- * <li><code>%{xxx}T</code> xxx is the unit for the time taken to process the request
- * (see Configuration Reference document for details on supported units)
+ * <li><code>%{xxx}t</code> xxx is an enhanced SimpleDateFormat pattern (see Configuration Reference document for
+ * details on supported time patterns)
+ * <li><code>%{xxx}T</code> xxx is the unit for the time taken to process the request (see Configuration Reference
+ * document for details on supported units)
* </ul>
- *
* <p>
- * Conditional logging is also supported. This can be done with the
- * <code>conditionUnless</code> and <code>conditionIf</code> properties.
- * If the value returned from ServletRequest.getAttribute(conditionUnless)
- * yields a non-null value, the logging will be skipped.
- * If the value returned from ServletRequest.getAttribute(conditionIf)
- * yields the null value, the logging will be skipped.
- * The <code>condition</code> attribute is synonym for
+ * Conditional logging is also supported. This can be done with the <code>conditionUnless</code> and
+ * <code>conditionIf</code> properties. If the value returned from ServletRequest.getAttribute(conditionUnless) yields a
+ * non-null value, the logging will be skipped. If the value returned from ServletRequest.getAttribute(conditionIf)
+ * yields the null value, the logging will be skipped. The <code>condition</code> attribute is synonym for
* <code>conditionUnless</code> and is provided for backwards compatibility.
* </p>
- *
* <p>
- * For extended attributes coming from a getAttribute() call,
- * it is you responsibility to ensure there are no newline or
+ * For extended attributes coming from a getAttribute() call, it is you responsibility to ensure there are no newline or
* control characters.
* </p>
*
@@ -156,24 +146,30 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
* The list of our time format types.
*/
private enum FormatType {
- CLF, SEC, MSEC, MSEC_FRAC, SDF
+ CLF,
+ SEC,
+ MSEC,
+ MSEC_FRAC,
+ SDF
}
/**
* The list of our port types.
*/
private enum PortType {
- LOCAL, REMOTE
+ LOCAL,
+ REMOTE
}
/**
* The list of our ip address types.
*/
private enum RemoteAddressType {
- REMOTE, PEER
+ REMOTE,
+ PEER
}
- //------------------------------------------------------ Constructor
+ // ------------------------------------------------------ Constructor
public AbstractAccessLogValve() {
super(true);
}
@@ -186,7 +182,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
*/
protected boolean enabled = true;
- /**
+ /**
* Use IPv6 canonical representation format as defined by RFC 5952.
*/
private boolean ipv6Canonical = false;
@@ -207,30 +203,33 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
private static final int localCacheSize = 60;
/**
- * <p>Cache structure for formatted timestamps based on seconds.</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>There is one cache for the CLF format (the access log standard
- * format) and a HashMap of caches for additional formats used by
- * SimpleDateFormat.</p>
- *
- * <p>Although the cache supports specifying a locale when retrieving a
- * formatted timestamp, each format will always use the locale given
- * when the format was first used. New locales can only be used for new formats.
- * The CLF format will always be formatted using the locale
- * <code>en_US</code>.</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>This class uses a small thread local first level cache and a bigger
- * synchronized global second level cache.</p>
+ * <p>
+ * Cache structure for formatted timestamps based on seconds.
+ * </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>
+ * There is one cache for the CLF format (the access log standard format) and a HashMap of caches for additional
+ * formats used by SimpleDateFormat.
+ * </p>
+ * <p>
+ * Although the cache supports specifying a locale when retrieving a formatted timestamp, each format will always
+ * use the locale given when the format was first used. New locales can only be used for new formats. The CLF format
+ * will always be formatted using the locale <code>en_US</code>.
+ * </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>
+ * This class uses a small thread local first level cache and a bigger synchronized global second level cache.
+ * </p>
*/
protected static class DateFormatCache {
@@ -290,26 +289,28 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
long seconds = time / 1000;
- /* First step: if we have seen this timestamp
- during the previous call, and we need CLF, return the previous value. */
+ /*
+ * First step: if we have seen this timestamp during the previous call, and we need CLF, 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;
@@ -334,10 +335,11 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
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.getFormatInternal(time);
}
} else {
@@ -370,7 +372,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
this.parent = parent;
Cache parentCache = null;
if (parent != null) {
- synchronized(parent) {
+ synchronized (parent) {
parentCache = parent.getCache(null, null);
}
}
@@ -386,7 +388,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
if (cache == null) {
Cache parentCache = null;
if (parent != null) {
- synchronized(parent) {
+ synchronized (parent) {
parentCache = parent.getCache(format, loc);
}
}
@@ -409,44 +411,39 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
/**
* Global date format cache.
*/
- private static final DateFormatCache globalDateCache =
- new DateFormatCache(globalCacheSize, Locale.getDefault(), null);
+ private static final DateFormatCache globalDateCache = new DateFormatCache(globalCacheSize, Locale.getDefault(),
+ null);
/**
* Thread local date format cache.
*/
- private static final ThreadLocal<DateFormatCache> localDateCache =
- ThreadLocal.withInitial(() -> new DateFormatCache(localCacheSize, Locale.getDefault(), globalDateCache));
+ private static final ThreadLocal<DateFormatCache> localDateCache = ThreadLocal
+ .withInitial(() -> new DateFormatCache(localCacheSize, Locale.getDefault(), globalDateCache));
/**
- * The system time when we last updated the Date that this valve
- * uses for log lines.
+ * The system time when we last updated the Date that this valve uses for log lines.
*/
private static final ThreadLocal<Date> localDate = ThreadLocal.withInitial(Date::new);
/**
- * Are we doing conditional logging. default null.
- * It is the value of <code>conditionUnless</code> property.
+ * Are we doing conditional logging. default null. It is the value of <code>conditionUnless</code> property.
*/
protected String condition = null;
/**
- * Are we doing conditional logging. default null.
- * It is the value of <code>conditionIf</code> property.
+ * Are we doing conditional logging. default null. It is the value of <code>conditionIf</code> property.
*/
protected String conditionIf = null;
/**
- * Name of locale used to format timestamps in log entries and in
- * log file name suffix.
+ * Name of locale used to format timestamps in log entries and in log file name suffix.
*/
protected String localeName = Locale.getDefault().toString();
/**
- * Locale used to format timestamps in log entries and in
- * log file name suffix.
+ * Locale used to format timestamps in log entries and in log file name suffix.
*/
protected Locale locale = Locale.getDefault();
@@ -456,31 +453,27 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
protected AccessLogElement[] logElements = null;
/**
- * Array of elements where the value needs to be cached at the start of the
- * request.
+ * Array of elements where the value needs to be cached at the start of the request.
*/
protected CachedElement[] cachedElements = null;
/**
- * Should this valve use request attributes for IP address, hostname,
- * protocol and port used for the request.
+ * Should this valve use request attributes for IP address, hostname, protocol and port used for the request.
* Default is <code>false</code>.
+ *
* @see #setRequestAttributesEnabled(boolean)
*/
protected boolean requestAttributesEnabled = false;
/**
- * Buffer pool used for log message generation. Pool used to reduce garbage
- * generation.
+ * Buffer pool used for log message generation. Pool used to reduce garbage generation.
*/
- private SynchronizedStack<CharArrayWriter> charArrayWriters =
- new SynchronizedStack<>();
+ private SynchronizedStack<CharArrayWriter> charArrayWriters = new SynchronizedStack<>();
/**
- * Log message buffers are usually recycled and re-used. To prevent
- * excessive memory usage, if a buffer grows beyond this size it will be
- * discarded. The default is 256 characters. This should be set to larger
- * than the typical access log message size.
+ * Log message buffers are usually recycled and re-used. To prevent excessive memory usage, if a buffer grows beyond
+ * this size it will be discarded. The default is 256 characters. This should be set to larger than the typical
+ * access log message size.
*/
private int maxLogMessageBufferSize = 256;
@@ -513,8 +506,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
/**
- * {@inheritDoc}
- * Default is <code>false</code>.
+ * {@inheritDoc} Default is <code>false</code>.
*/
@Override
public void setRequestAttributesEnabled(boolean requestAttributesEnabled) {
@@ -538,8 +530,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
}
/**
- * @param enabled
- * The enabled to set.
+ * @param enabled The enabled to set.
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
@@ -573,9 +564,9 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
}
/**
- * Return whether the attribute name to look for when
- * performing conditional logging. If null, every
- * request is logged.
+ * Return whether the attribute name to look for when performing conditional logging. If null, every request is
+ * logged.
+ *
* @return the attribute name
*/
public String getCondition() {
@@ -584,8 +575,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
/**
- * Set the ServletRequest.attribute to look for to perform
- * conditional logging. Set to null to log everything.
+ * Set the ServletRequest.attribute to look for to perform conditional logging. Set to null to log everything.
*
* @param condition Set to null to log everything
*/
@@ -595,9 +585,9 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
/**
- * Return whether the attribute name to look for when
- * performing conditional logging. If null, every
- * request is logged.
+ * Return whether the attribute name to look for when performing conditional logging. If null, every request is
+ * logged.
+ *
* @return the attribute name
*/
public String getConditionUnless() {
@@ -606,8 +596,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
/**
- * Set the ServletRequest.attribute to look for to perform
- * conditional logging. Set to null to log everything.
+ * Set the ServletRequest.attribute to look for to perform conditional logging. Set to null to log everything.
*
* @param condition Set to null to log everything
*/
@@ -616,9 +605,9 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
}
/**
- * Return whether the attribute name to look for when
- * performing conditional logging. If null, every
- * request is logged.
+ * Return whether the attribute name to look for when performing conditional logging. If null, every request is
+ * logged.
+ *
* @return the attribute name
*/
public String getConditionIf() {
@@ -627,8 +616,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
/**
- * Set the ServletRequest.attribute to look for to perform
- * conditional logging. Set to null to log everything.
+ * Set the ServletRequest.attribute to look for to perform conditional logging. Set to null to log everything.
*
* @param condition Set to null to log everything
*/
@@ -637,8 +625,8 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
}
/**
- * Return the locale used to format timestamps in log entries and in
- * log file name suffix.
+ * Return the locale used to format timestamps in log entries and in log file name suffix.
+ *
* @return the locale
*/
public String getLocale() {
@@ -647,10 +635,9 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
/**
- * Set the locale used to format timestamps in log entries and in
- * log file name suffix. Changing the locale is only supported
- * as long as the AccessLogValve has not logged anything. Changing
- * the locale later can lead to inconsistent formatting.
+ * Set the locale used to format timestamps in log entries and in log file name suffix. Changing the locale is only
+ * supported as long as the AccessLogValve has not logged anything. Changing the locale later can lead to
+ * inconsistent formatting.
*
* @param localeName The locale to use.
*/
@@ -662,18 +649,17 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
// --------------------------------------------------------- Public Methods
/**
- * Log a message summarizing the specified request and response, according
- * to the format specified by the <code>pattern</code> property.
+ * Log a message summarizing the specified request and response, according to the format specified by the
+ * <code>pattern</code> property.
*
- * @param request Request being processed
+ * @param request Request being processed
* @param response Response being processed
*
- * @exception IOException if an input/output error has occurred
+ * @exception IOException if an input/output error has occurred
* @exception ServletException if a servlet error has occurred
*/
@Override
- public void invoke(Request request, Response response) throws IOException,
- ServletException {
+ public void invoke(Request request, Response response) throws IOException, ServletException {
if (tlsAttributeRequired) {
// The log pattern uses TLS attributes. Ensure these are populated
// before the request is processed because with NIO2 it is possible
@@ -693,11 +679,9 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
@Override
public void log(Request request, Response response, long time) {
- if (!getState().isAvailable() || !getEnabled() || logElements == null
- || condition != null
- && null != request.getRequest().getAttribute(condition)
- || conditionIf != null
- && null == request.getRequest().getAttribute(conditionIf)) {
+ if (!getState().isAvailable() || !getEnabled() || logElements == null ||
+ condition != null && null != request.getRequest().getAttribute(condition) ||
+ conditionIf != null && null == request.getRequest().getAttribute(conditionIf)) {
return;
}
@@ -726,20 +710,19 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
/**
* Log the specified message.
*
- * @param message Message to be logged. This object will be recycled by
- * the calling method.
+ * @param message Message to be logged. This object will be recycled by the calling method.
*/
protected abstract void log(CharArrayWriter message);
// -------------------------------------------------------- Private Methods
/**
- * This method returns a Date object that is accurate to within one second.
- * If a thread calls this method to get a Date and it's been less than 1
- * second since a new Date was created, this method simply gives out the
- * same Date again so that the system doesn't spend time creating Date
- * objects unnecessarily.
+ * This method returns a Date object that is accurate to within one second. If a thread calls this method to get a
+ * Date and it's been less than 1 second since a new Date was created, this method simply gives out the same Date
+ * again so that the system doesn't spend time creating Date objects unnecessarily.
+ *
* @param systime The time
+ *
* @return the date object
*/
private static Date getDate(long systime) {
@@ -751,15 +734,17 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
/**
* Find a locale by name.
- * @param name The locale name
+ *
+ * @param name The locale name
* @param fallback Fallback locale if the name is not found
+ *
* @return the locale object
*/
protected static Locale findLocale(String name, Locale fallback) {
if (name == null || name.isEmpty()) {
return Locale.getDefault();
} else {
- for (Locale l: Locale.getAvailableLocales()) {
+ for (Locale l : Locale.getAvailableLocales()) {
if (name.equals(l.toString())) {
return l;
}
@@ -771,11 +756,11 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
/**
- * Start this component and implement the requirements
- * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
+ * 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 {
@@ -785,11 +770,11 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
/**
- * Stop this component and implement the requirements
- * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
+ * 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 {
@@ -801,19 +786,15 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
* AccessLogElement writes the partial message into the buffer.
*/
protected interface AccessLogElement {
- void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time);
+ void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time);
}
/**
- * Marks an AccessLogElement as needing to be have the value cached at the
- * start of the request rather than just recorded at the end as the source
- * data for the element may not be available at the end of the request. This
- * typically occurs for remote network information, such as ports, IP
- * addresses etc. when the connection is closed unexpectedly. These elements
- * take advantage of these values being cached elsewhere on first request
- * and do not cache the value in the element since the elements are
- * state-less.
+ * Marks an AccessLogElement as needing to be have the value cached at the start of the request rather than just
+ * recorded at the end as the source data for the element may not be available at the end of the request. This
+ * typically occurs for remote network information, such as ports, IP addresses etc. when the connection is closed
+ * unexpectedly. These elements take advantage of these values being cached elsewhere on first request and do not
+ * cache the value in the element since the elements are state-less.
*/
protected interface CachedElement {
void cache(Request request);
@@ -824,10 +805,9 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
*/
protected static class ThreadNameElement implements AccessLogElement {
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
RequestInfo info = request.getCoyoteRequest().getRequestProcessor();
- if(info != null) {
+ if (info != null) {
buf.append(info.getWorkerThreadName());
} else {
buf.append('-');
@@ -859,8 +839,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
}
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
buf.append(localAddrValue);
}
}
@@ -883,22 +862,21 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
public RemoteAddrElement(String type) {
switch (type) {
- case remoteAddress:
- remoteAddressType = RemoteAddressType.REMOTE;
- break;
- case peerAddress:
- remoteAddressType = RemoteAddressType.PEER;
- break;
- default:
- log.error(sm.getString("accessLogValve.invalidRemoteAddressType", type));
- remoteAddressType = RemoteAddressType.REMOTE;
- break;
+ case remoteAddress:
+ remoteAddressType = RemoteAddressType.REMOTE;
+ break;
+ case peerAddress:
+ remoteAddressType = RemoteAddressType.PEER;
+ break;
+ default:
+ log.error(sm.getString("accessLogValve.invalidRemoteAddressType", type));
+ remoteAddressType = RemoteAddressType.REMOTE;
+ break;
}
}
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
String value = null;
if (remoteAddressType == RemoteAddressType.PEER) {
value = request.getPeerAddr();
@@ -938,8 +916,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
*/
protected class HostElement implements AccessLogElement, CachedElement {
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
String value = null;
if (requestAttributesEnabled) {
Object host = request.getAttribute(REMOTE_HOST_ATTRIBUTE);
@@ -973,8 +950,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
*/
protected static class LogicalUserNameElement implements AccessLogElement {
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
buf.append('-');
}
}
@@ -984,8 +960,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
*/
protected class ProtocolElement implements AccessLogElement {
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
if (requestAttributesEnabled) {
Object proto = request.getAttribute(PROTOCOL_ATTRIBUTE);
if (proto == null) {
@@ -1004,8 +979,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
*/
protected static class UserElement implements AccessLogElement {
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
if (request != null) {
String value = request.getRemoteUser();
if (value != null) {
@@ -1055,12 +1029,10 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
private static final String msecFractionFormat = "msec_frac";
/**
- * The patterns we use to replace "S" and "SSS" millisecond
- * formatting of SimpleDateFormat by our own handling
+ * The patterns we use to replace "S" and "SSS" millisecond formatting of SimpleDateFormat by our own handling
*/
private static final String msecPattern = "{#}";
- private static final String tripleMsecPattern =
- msecPattern + msecPattern + msecPattern;
+ private static final String tripleMsecPattern = msecPattern + msecPattern + msecPattern;
/* Our format description string, null if CLF */
private final String format;
@@ -1076,10 +1048,8 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
}
/**
- * Replace the millisecond formatting character 'S' by
- * some dummy characters in order to make the resulting
- * formatted time stamps cacheable. We replace the dummy
- * chars later with the actual milliseconds because that's
+ * Replace the millisecond formatting character 'S' by some dummy characters in order to make the resulting
+ * formatted time stamps cacheable. We replace the dummy chars later with the actual milliseconds because that's
* relatively cheap.
*/
private String tidyFormat(String format) {
@@ -1196,8 +1166,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
*/
protected static class RequestElement implements AccessLogElement {
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
if (request != null) {
String method = request.getMethod();
if (method == null) {
@@ -1225,17 +1194,15 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
*/
protected static class HttpStatusCodeElement implements AccessLogElement {
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
if (response != null) {
// This approach is used to reduce GC from toString conversion
int status = response.getStatus();
if (100 <= status && status < 1000) {
- buf.append((char) ('0' + (status / 100)))
- .append((char) ('0' + ((status / 10) % 10)))
+ buf.append((char) ('0' + (status / 100))).append((char) ('0' + ((status / 10) % 10)))
.append((char) ('0' + (status % 10)));
} else {
- buf.append(Integer.toString(status));
+ buf.append(Integer.toString(status));
}
} else {
buf.append('-');
@@ -1262,22 +1229,21 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
public PortElement(String type) {
switch (type) {
- case remotePort:
- portType = PortType.REMOTE;
- break;
- case localPort:
- portType = PortType.LOCAL;
- break;
- default:
- log.error(sm.getString("accessLogValve.invalidPortType", type));
- portType = PortType.LOCAL;
- break;
+ case remotePort:
+ portType = PortType.REMOTE;
+ break;
+ case localPort:
+ portType = PortType.LOCAL;
+ break;
+ default:
+ log.error(sm.getString("accessLogValve.invalidPortType", type));
+ portType = PortType.LOCAL;
+ break;
}
}
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
if (requestAttributesEnabled && portType == PortType.LOCAL) {
Object port = request.getAttribute(SERVER_PORT_ATTRIBUTE);
if (port == null) {
@@ -1316,22 +1282,18 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
}
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
// Don't need to flush since trigger for log message is after the
// response has been committed
long length = response.getBytesWritten(false);
if (length <= 0) {
// Protect against nulls and unexpected types as these values
// may be set by untrusted applications
- Object start = request.getAttribute(
- Globals.SENDFILE_FILE_START_ATTR);
+ Object start = request.getAttribute(Globals.SENDFILE_FILE_START_ATTR);
if (start instanceof Long) {
- Object end = request.getAttribute(
- Globals.SENDFILE_FILE_END_ATTR);
+ Object end = request.getAttribute(Globals.SENDFILE_FILE_END_ATTR);
if (end instanceof Long) {
- length = ((Long) end).longValue() -
- ((Long) start).longValue();
+ length = ((Long) end).longValue() - ((Long) start).longValue();
}
}
}
@@ -1348,8 +1310,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
*/
protected static class MethodElement implements AccessLogElement {
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
if (request != null) {
buf.append(request.getMethod());
}
@@ -1365,8 +1326,8 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
/**
* @param micros <code>true</code>, write time in microseconds - %D
- * @param millis <code>true</code>, write time in milliseconds,
- * if both arguments are <code>false</code>, write time in seconds - %T
+ * @param millis <code>true</code>, write time in milliseconds, if both arguments are <code>false</code>, write
+ * time in seconds - %T
*/
public ElapsedTimeElement(boolean micros, boolean millis) {
this.micros = micros;
@@ -1374,8 +1335,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
}
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
if (micros) {
buf.append(Long.toString(TimeUnit.NANOSECONDS.toMicros(time)));
} else if (millis) {
@@ -1408,8 +1368,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
*/
protected static class QueryElement implements AccessLogElement {
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
String query = null;
if (request != null) {
query = request.getQueryString();
@@ -1426,8 +1385,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
*/
protected static class SessionIdElement implements AccessLogElement {
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
if (request == null) {
buf.append('-');
} else {
@@ -1446,8 +1404,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
*/
protected static class RequestURIElement implements AccessLogElement {
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
if (request != null) {
buf.append(request.getRequestURI());
} else {
@@ -1461,8 +1418,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
*/
protected class LocalServerNameElement implements AccessLogElement {
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
String value = null;
if (requestAttributesEnabled) {
Object serverName = request.getAttribute(SERVER_NAME_ATTRIBUTE);
@@ -1495,8 +1451,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
}
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
buf.append(str);
}
}
@@ -1512,8 +1467,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
}
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
Enumeration<String> iter = request.getHeaders(header);
if (iter.hasMoreElements()) {
escapeAndAppend(iter.nextElement(), buf);
@@ -1538,8 +1492,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
}
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
StringBuilder value = new StringBuilder();
boolean first = true;
Cookie[] cookies = request.getCookies();
@@ -1574,8 +1527,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
}
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
if (null != response) {
Iterator<String> iter = response.getHeaders(header).iterator();
if (iter.hasNext()) {
@@ -1602,8 +1554,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
}
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
Object value = null;
if (request != null) {
value = request.getAttribute(header);
@@ -1633,8 +1584,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
}
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
Object value = null;
if (null != request) {
HttpSession sess = request.getSession(false);
@@ -1700,6 +1650,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
/**
* Parse pattern string and create the array of AccessLogElement.
+ *
* @return the log elements array
*/
protected AccessLogElement[] createLogElements() {
@@ -1710,8 +1661,8 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
char ch = pattern.charAt(i);
if (replace) {
/*
- * For code that processes {, the behavior will be ... if I do
- * not encounter a closing } - then I ignore the {
+ * For code that processes {, the behavior will be ... if I do not encounter a closing } - then I ignore
+ * the {
*/
if ('{' == ch) {
StringBuilder name = new StringBuilder();
@@ -1722,8 +1673,7 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
if (j + 1 < pattern.length()) {
/* the +1 was to account for } which we increment now */
j++;
- list.add(createAccessLogElement(name.toString(),
- pattern.charAt(j)));
+ list.add(createAccessLogElement(name.toString(), pattern.charAt(j)));
i = j; /* Since we walked more than one character */
} else {
// D'oh - end of string - pretend we never did this
@@ -1762,152 +1712,134 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
/**
* Create an AccessLogElement implementation which needs an element name.
- * @param name Header name
+ *
+ * @param name Header name
* @param pattern char in the log pattern
+ *
* @return the log element
*/
protected AccessLogElement createAccessLogElement(String name, char pattern) {
switch (pattern) {
- case 'i':
- return new HeaderElement(name);
- case 'c':
- return new CookieElement(name);
- case 'o':
- return new ResponseHeaderElement(name);
- case 'a':
- return new RemoteAddrElement(name);
- case 'p':
- return new PortElement(name);
- case 'r':
- if (TLSUtil.isTLSRequestAttribute(name)) {
- tlsAttributeRequired = true;
- }
- return new RequestAttributeElement(name);
- case 's':
- return new SessionAttributeElement(name);
- case 't':
- return new DateAndTimeElement(name);
- case 'T':
- // ms for milliseconds, us for microseconds, and s for seconds
- if ("ms".equals(name)) {
- return new ElapsedTimeElement(false, true);
- } else if ("us".equals(name)) {
- return new ElapsedTimeElement(true, false);
- } else {
- return new ElapsedTimeElement(false, false);
- }
- default:
- return new StringElement("???");
+ case 'i':
+ return new HeaderElement(name);
+ case 'c':
+ return new CookieElement(name);
+ case 'o':
+ return new ResponseHeaderElement(name);
+ case 'a':
+ return new RemoteAddrElement(name);
+ case 'p':
+ return new PortElement(name);
+ case 'r':
+ if (TLSUtil.isTLSRequestAttribute(name)) {
+ tlsAttributeRequired = true;
+ }
+ return new RequestAttributeElement(name);
+ case 's':
+ return new SessionAttributeElement(name);
+ case 't':
+ return new DateAndTimeElement(name);
+ case 'T':
+ // ms for milliseconds, us for microseconds, and s for seconds
+ if ("ms".equals(name)) {
+ return new ElapsedTimeElement(false, true);
+ } else if ("us".equals(name)) {
+ return new ElapsedTimeElement(true, false);
+ } else {
+ return new ElapsedTimeElement(false, false);
+ }
+ default:
+ return new StringElement("???");
}
}
/**
* Create an AccessLogElement implementation.
+ *
* @param pattern char in the log pattern
+ *
* @return the log element
*/
protected AccessLogElement createAccessLogElement(char pattern) {
switch (pattern) {
- case 'a':
- return new RemoteAddrElement();
- case 'A':
- return new LocalAddrElement(ipv6Canonical);
- case 'b':
- return new ByteSentElement(true);
- case 'B':
- return new ByteSentElement(false);
- case 'D':
- return new ElapsedTimeElement(true, false);
- case 'F':
- return new FirstByteTimeElement();
- case 'h':
- return new HostElement();
- case 'H':
- return new ProtocolElement();
- case 'l':
- return new LogicalUserNameElement();
- case 'm':
- return new MethodElement();
- case 'p':
- return new PortElement();
- case 'q':
- return new QueryElement();
- case 'r':
- return new RequestElement();
- case 's':
- return new HttpStatusCodeElement();
- case 'S':
- return new SessionIdElement();
- case 't':
- return new DateAndTimeElement();
- case 'T':
- return new ElapsedTimeElement(false, false);
- case 'u':
- return new UserElement();
- case 'U':
- return new RequestURIElement();
- case 'v':
- return new LocalServerNameElement();
- case 'I':
- return new ThreadNameElement();
- case 'X':
- return new ConnectionStatusElement();
- default:
- return new StringElement("???" + pattern + "???");
+ case 'a':
+ return new RemoteAddrElement();
+ case 'A':
+ return new LocalAddrElement(ipv6Canonical);
+ case 'b':
+ return new ByteSentElement(true);
+ case 'B':
+ return new ByteSentElement(false);
+ case 'D':
+ return new ElapsedTimeElement(true, false);
+ case 'F':
+ return new FirstByteTimeElement();
+ case 'h':
+ return new HostElement();
+ case 'H':
+ return new ProtocolElement();
+ case 'l':
+ return new LogicalUserNameElement();
+ case 'm':
+ return new MethodElement();
+ case 'p':
+ return new PortElement();
+ case 'q':
+ return new QueryElement();
+ case 'r':
+ return new RequestElement();
+ case 's':
+ return new HttpStatusCodeElement();
+ case 'S':
+ return new SessionIdElement();
+ case 't':
+ return new DateAndTimeElement();
+ case 'T':
+ return new ElapsedTimeElement(false, false);
+ case 'u':
+ return new UserElement();
+ case 'U':
+ return new RequestURIElement();
+ case 'v':
+ return new LocalServerNameElement();
+ case 'I':
+ return new ThreadNameElement();
+ case 'X':
+ return new ConnectionStatusElement();
+ default:
+ return new StringElement("???" + pattern + "???");
}
}
/*
- * This method is intended to mimic the escaping performed by httpd and
- * mod_log_config. mod_log_config escapes more elements than indicated by the
- * documentation. See:
+ * This method is intended to mimic the escaping performed by httpd and mod_log_config. mod_log_config escapes more
+ * elements than indicated by the documentation. See:
* https://github.com/apache/httpd/blob/trunk/modules/loggers/mod_log_config.c
*
- * The following escaped elements are not supported by Tomcat:
- * - %C cookie value (see %{}c below)
- * - %e environment variable
- * - %f filename
- * - %l remote logname (always logs "-")
- * - %n note
- * - %R handler
- * - %ti trailer request header
- * - %to trailer response header
- * - %V server name per UseCanonicalName setting
+ * The following escaped elements are not supported by Tomcat: - %C cookie value (see %{}c below) - %e environment
+ * variable - %f filename - %l remote logname (always logs "-") - %n note - %R handler - %ti trailer request header
+ * - %to trailer response header - %V server name per UseCanonicalName setting
*
- * The following escaped elements are not escaped in Tomcat because values
- * that would require escaping are rejected before they reach the
- * AccessLogValve:
- * - %h remote host
- * - %H request protocol
- * - %m request method
- * - %q query string
- * - %r request line
- * - %U request URI
- * - %v canonical server name
+ * The following escaped elements are not escaped in Tomcat because values that would require escaping are rejected
+ * before they reach the AccessLogValve: - %h remote host - %H request protocol - %m request method - %q query
+ * string - %r request line - %U request URI - %v canonical server name
*
- * The following escaped elements are supported by Tomcat:
- * - %{}i request header
- * - %{}o response header
- * - %u remote user
+ * The following escaped elements are supported by Tomcat: - %{}i request header - %{}o response header - %u remote
+ * user
*
- * The following additional Tomcat elements are escaped for consistency:
- * - %{}c cookie value
- * - %{}r request attribute
- * - %{}s session attribute
+ * The following additional Tomcat elements are escaped for consistency: - %{}c cookie value - %{}r request
+ * attribute - %{}s session attribute
*
* giving a total of 6 elements that are escaped in Tomcat.
*
- * Quoting from the httpd docs:
- * "...non-printable and other special characters in %r, %i and %o are
- * escaped using \xhh sequences, where hh stands for the hexadecimal
- * representation of the raw byte. Exceptions from this rule are " and \,
- * which are escaped by prepending a backslash, and all whitespace
- * characters, which are written in their C-style notation (\n, \t, etc)."
+ * Quoting from the httpd docs: "...non-printable and other special characters in %r, %i and %o are escaped using
+ * \xhh sequences, where hh stands for the hexadecimal representation of the raw byte. Exceptions from this rule are
+ * " and \, which are escaped by prepending a backslash, and all whitespace characters, which are written in their
+ * C-style notation (\n, \t, etc)."
*
- * Reviewing the httpd code, characters with the high bit set are escaped.
- * The httpd is assuming a single byte encoding which may not be true for
- * Tomcat so Tomcat uses the Java \\uXXXX encoding.
+ * Reviewing the httpd code, characters with the high bit set are escaped. The httpd is assuming a single byte
+ * encoding which may not be true for Tomcat so Tomcat uses the Java \\uXXXX encoding.
*/
protected static void escapeAndAppend(String input, CharArrayWriter dest) {
if (input == null || input.isEmpty()) {
@@ -1917,37 +1849,37 @@ public abstract class AbstractAccessLogValve extends ValveBase implements Access
for (char c : input.toCharArray()) {
switch (c) {
- // " and \
- case '\\':
- dest.append("\\\\");
- break;
- case '\"':
- dest.append("\\\"");
- break;
- // Standard C escapes for whitespace (not all standard C escapes)
- case '\f':
- dest.append("\\f");
- break;
- case '\n':
- dest.append("\\n");
- break;
- case '\r':
- dest.append("\\r");
- break;
- case '\t':
- dest.append("\\t");
- break;
- case '\u000b':
- dest.append("\\v");
- break;
- default:
- // Control, delete (127) or above 127
- if (c < 32 || c > 126) {
- dest.append("\\u");
- dest.append(HexUtils.toHexString(c));
- } else {
- dest.append(c);
- }
+ // " and \
+ case '\\':
+ dest.append("\\\\");
+ break;
+ case '\"':
+ dest.append("\\\"");
+ break;
+ // Standard C escapes for whitespace (not all standard C escapes)
+ case '\f':
+ dest.append("\\f");
+ break;
+ case '\n':
+ dest.append("\\n");
+ break;
+ case '\r':
+ dest.append("\\r");
+ break;
+ case '\t':
+ dest.append("\\t");
+ break;
+ case '\u000b':
+ dest.append("\\v");
+ break;
+ default:
+ // Control, delete (127) or above 127
+ if (c < 32 || c > 126) {
+ dest.append("\\u");
+ dest.append(HexUtils.toHexString(c));
+ } else {
+ dest.append(c);
+ }
}
}
}
diff --git a/java/org/apache/catalina/valves/AccessLogValve.java b/java/org/apache/catalina/valves/AccessLogValve.java
index 12331ebb28..3acfaaf5f5 100644
--- a/java/org/apache/catalina/valves/AccessLogValve.java
+++ b/java/org/apache/catalina/valves/AccessLogValve.java
@@ -40,31 +40,27 @@ import org.apache.tomcat.util.buf.B2CConverter;
/**
- * This is a concrete implementation of {@link AbstractAccessLogValve} that
- * outputs the access log to a file. The features of this implementation
- * include:
+ * This is a concrete implementation of {@link AbstractAccessLogValve} that outputs the access log to a file. The
+ * features of this implementation include:
* <ul>
* <li>Automatic date-based rollover of log files</li>
* <li>Optional log file rotation</li>
* </ul>
* <p>
- * For UNIX users, another field called <code>checkExists</code> is also
- * available. If set to true, the log file's existence will be checked before
- * each logging. This way an external log rotator can move the file
- * somewhere and Tomcat will start with a new file.
+ * For UNIX users, another field called <code>checkExists</code> is also available. If set to true, the log file's
+ * existence will be checked before each logging. This way an external log rotator can move the file somewhere and
+ * Tomcat will start with a new file.
* </p>
- *
* <p>
- * For JMX junkies, a public method called <code>rotate</code> has
- * been made available to allow you to tell this instance to move
- * the existing log file to somewhere else and start writing a new log file.
+ * For JMX junkies, a public method called <code>rotate</code> has been made available to allow you to tell this
+ * instance to move the existing log file to somewhere else and start writing a new log file.
* </p>
*/
public class AccessLogValve extends AbstractAccessLogValve {
private static final Log log = LogFactory.getLog(AccessLogValve.class);
- //------------------------------------------------------ Constructor
+ // ------------------------------------------------------ Constructor
public AccessLogValve() {
super();
}
@@ -73,8 +69,7 @@ public class AccessLogValve extends AbstractAccessLogValve {
/**
- * 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 dateStamp = "";
@@ -96,8 +91,7 @@ public class AccessLogValve extends AbstractAccessLogValve {
protected boolean rotatable = true;
/**
- * Should we defer inclusion of the date stamp in the file
- * name until rotate time? Default is false.
+ * Should we defer inclusion of the date stamp in the file name until rotate time? Default is false.
*/
protected boolean renameOnRotate = false;
@@ -121,15 +115,13 @@ public class AccessLogValve extends AbstractAccessLogValve {
/**
- * A date formatter to format a Date using the format
- * given by <code>fileDateFormat</code>.
+ * A date formatter to format a Date using the format given by <code>fileDateFormat</code>.
*/
protected SimpleDateFormat fileDateFormatter = null;
/**
- * The current log file we are writing to. Helpful when checkExists
- * is true.
+ * The current log file we are writing to. Helpful when checkExists is true.
*/
protected File currentLogFile = null;
@@ -139,8 +131,8 @@ public class AccessLogValve extends AbstractAccessLogValve {
private volatile long rotationLastChecked = 0L;
/**
- * Do we check for log file existence? Helpful if an external
- * agent renames the log file so we can automagically recreate it.
+ * Do we check for log file existence? Helpful if an external agent renames the log file so we can automagically
+ * recreate it.
*/
private boolean checkExists = false;
@@ -150,15 +142,13 @@ public class AccessLogValve extends AbstractAccessLogValve {
protected String fileDateFormat = ".yyyy-MM-dd";
/**
- * Character set used by the log file. If it is <code>null</code>, UTF-8
- * will be used. An empty string will be treated as <code>null</code>
- * when this property is assigned.
+ * Character set used by the log file. If it is <code>null</code>, UTF-8 will be used. An empty string will be
+ * treated as <code>null</code> when this property is assigned.
*/
protected volatile String encoding = null;
/**
- * The number of days to retain the access log files before they are
- * removed.
+ * The number of days to retain the access log files before they are removed.
*/
private int maxDays = -1;
private volatile boolean checkForOldLogs = false;
@@ -195,6 +185,7 @@ public class AccessLogValve extends AbstractAccessLogValve {
/**
* Check for file existence before logging.
+ *
* @return <code>true</code> if file existence is checked first
*/
public boolean isCheckExists() {
@@ -255,10 +246,9 @@ public class AccessLogValve extends AbstractAccessLogValve {
/**
- * Should we defer inclusion of the date stamp in the file
- * name until rotate time.
- * @return <code>true</code> if the logs file names are time stamped
- * only when they are rotated
+ * Should we defer inclusion of the date stamp in the file name until rotate time.
+ *
+ * @return <code>true</code> if the logs file names are time stamped only when they are rotated
*/
public boolean isRenameOnRotate() {
return renameOnRotate;
@@ -266,8 +256,7 @@ public class AccessLogValve extends AbstractAccessLogValve {
/**
- * Set the value if we should defer inclusion of the date
- * stamp in the file name until rotate time
+ * Set the value if we should defer inclusion of the date stamp in the file name until rotate time
*
* @param renameOnRotate true if defer inclusion of date stamp
*/
@@ -278,6 +267,7 @@ public class AccessLogValve extends AbstractAccessLogValve {
/**
* Is the logging buffered. Usually buffering can increase performance.
+ *
* @return <code>true</code> if the logging uses a buffer
*/
public boolean isBuffered() {
@@ -322,6 +312,7 @@ public class AccessLogValve extends AbstractAccessLogValve {
/**
* Set the date format date based log rotation.
+ *
* @param fileDateFormat The format for the file timestamp
*/
public void setFileDateFormat(String fileDateFormat) {
@@ -342,8 +333,7 @@ public class AccessLogValve extends AbstractAccessLogValve {
/**
* Return the character set name that is used to write the log file.
*
- * @return Character set name, or <code>null</code> if the default
- * character set is used.
+ * @return Character set name, or <code>null</code> if the default character set is used.
*/
public String getEncoding() {
return encoding;
@@ -365,14 +355,12 @@ public class AccessLogValve extends AbstractAccessLogValve {
// --------------------------------------------------------- Public Methods
/**
- * 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 synchronized void backgroundProcess() {
- if (getState().isAvailable() && getEnabled() && writer != null &&
- buffered) {
+ if (getState().isAvailable() && getEnabled() && writer != null && buffered) {
writer.flush();
}
@@ -381,8 +369,7 @@ public class AccessLogValve extends AbstractAccessLogValve {
String suffix = this.suffix;
if (rotatable && checkForOldLogs && maxDays > 0) {
- long deleteIfLastModifiedBefore =
- System.currentTimeMillis() - (maxDays * 24L * 60 * 60 * 1000);
+ long deleteIfLastModifiedBefore = System.currentTimeMillis() - (maxDays * 24L * 60 * 60 * 1000);
File dir = getDirectoryFile();
if (dir.isDirectory()) {
String[] oldAccessLogs = dir.list();
@@ -409,8 +396,7 @@ public class AccessLogValve extends AbstractAccessLogValve {
File file = new File(dir, oldAccessLog);
if (file.isFile() && file.lastModified() < deleteIfLastModifiedBefore) {
if (!file.delete()) {
- log.warn(sm.getString(
- "accessLogValve.deleteFail", file.getAbsolutePath()));
+ log.warn(sm.getString("accessLogValve.deleteFail", file.getAbsolutePath()));
}
}
}
@@ -429,7 +415,7 @@ public class AccessLogValve extends AbstractAccessLogValve {
// Only do a logfile switch check once a second, max.
long systime = System.currentTimeMillis();
if ((systime - rotationLastChecked) > 1000) {
- synchronized(this) {
+ synchronized (this) {
if ((systime - rotationLastChecked) > 1000) {
rotationLastChecked = systime;
@@ -450,11 +436,11 @@ public class AccessLogValve extends AbstractAccessLogValve {
}
/**
- * Rename the existing log file to something else. Then open the
- * old log file name up once again. Intended to be called by a JMX
- * agent.
+ * Rename the existing log file to something else. Then open the old log file name up once again. Intended to be
+ * called by a JMX agent.
*
* @param newFileName The file name to move the log file entry to
+ *
* @return true if a file was rotated with no error
*/
public synchronized boolean rotate(String newFileName) {
@@ -470,8 +456,7 @@ public class AccessLogValve extends AbstractAccessLogValve {
}
/* Make sure date is correct */
- dateStamp = fileDateFormatter.format(
- new Date(System.currentTimeMillis()));
+ dateStamp = fileDateFormatter.format(new Date(System.currentTimeMillis()));
open();
return true;
@@ -494,11 +479,11 @@ public class AccessLogValve extends AbstractAccessLogValve {
/**
- * Create a File object based on the current log file name.
- * Directories are created as needed but the underlying file
- * is not created or opened.
+ * Create a File object based on the current log file name. Directories are created as needed but the underlying
+ * file is not created or opened.
*
* @param useDateStamp include the timestamp in the file name.
+ *
* @return the log file object
*/
private File getLogFile(boolean useDateStamp) {
@@ -511,8 +496,7 @@ public class AccessLogValve extends AbstractAccessLogValve {
// Calculate the current log file name
File pathname;
if (useDateStamp) {
- pathname = new File(dir.getAbsoluteFile(), prefix + dateStamp
- + suffix);
+ pathname = new File(dir.getAbsoluteFile(), prefix + dateStamp + suffix);
} else {
pathname = new File(dir.getAbsoluteFile(), prefix + suffix);
}
@@ -524,15 +508,13 @@ public class AccessLogValve extends AbstractAccessLogValve {
}
/**
- * Move a current but rotated log file back to the unrotated
- * one. Needed if date stamp inclusion is deferred to rotation
- * time.
+ * Move a current but rotated log file back to the unrotated one. Needed if date stamp inclusion is deferred to
+ * rotation time.
*/
private void restore() {
File newLogFile = getLogFile(false);
File rotatedLogFile = getLogFile(true);
- if (rotatedLogFile.exists() && !newLogFile.exists() &&
- !rotatedLogFile.equals(newLogFile)) {
+ if (rotatedLogFile.exists() && !newLogFile.exists() && !rotatedLogFile.equals(newLogFile)) {
try {
if (!rotatedLogFile.renameTo(newLogFile)) {
log.error(sm.getString("accessLogValve.renameFail", rotatedLogFile, newLogFile));
@@ -578,8 +560,7 @@ public class AccessLogValve extends AbstractAccessLogValve {
/**
- * Log the specified message to the log file, switching files if the date
- * has changed since the previous log call.
+ * Log the specified message to the log file, switching files if the date has changed since the previous log call.
*
* @param message Message to be logged
*/
@@ -600,8 +581,7 @@ public class AccessLogValve extends AbstractAccessLogValve {
}
/* Make sure date is correct */
- dateStamp = fileDateFormatter.format(
- new Date(System.currentTimeMillis()));
+ dateStamp = fileDateFormatter.format(new Date(System.currentTimeMillis()));
open();
}
@@ -611,7 +591,7 @@ public class AccessLogValve extends AbstractAccessLogValve {
// Log this message
try {
message.write(System.lineSeparator());
- synchronized(this) {
+ synchronized (this) {
if (writer != null) {
message.writeTo(writer);
if (!buffered) {
@@ -620,8 +600,7 @@ public class AccessLogValve extends AbstractAccessLogValve {
}
}
} catch (IOException ioe) {
- log.warn(sm.getString(
- "accessLogValve.writeFail", message.toString()), ioe);
+ log.warn(sm.getString("accessLogValve.writeFail", message.toString()), ioe);
}
}
@@ -639,8 +618,7 @@ public class AccessLogValve extends AbstractAccessLogValve {
try {
charset = B2CConverter.getCharset(encoding);
} catch (UnsupportedEncodingException ex) {
- log.error(sm.getString(
- "accessLogValve.unsupportedEncoding", encoding), ex);
+ log.error(sm.getString("accessLogValve.unsupportedEncoding", encoding), ex);
}
}
if (charset == null) {
@@ -648,8 +626,8 @@ public class AccessLogValve extends AbstractAccessLogValve {
}
try {
- writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
- new FileOutputStream(pathname, true), charset), 128000),
+ writer = new PrintWriter(
+ new BufferedWriter(new OutputStreamWriter(new FileOutputStream(pathname, true), charset), 128000),
false);
currentLogFile = pathname;
@@ -665,11 +643,11 @@ public class AccessLogValve extends AbstractAccessLogValve {
}
/**
- * Start this component and implement the requirements
- * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
+ * 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 {
@@ -689,11 +667,11 @@ public class AccessLogValve extends AbstractAccessLogValve {
/**
- * Stop this component and implement the requirements
- * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
+ * 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 {
diff --git a/java/org/apache/catalina/valves/Constants.java b/java/org/apache/catalina/valves/Constants.java
index b0d5909e2b..c19561fcf4 100644
--- a/java/org/apache/catalina/valves/Constants.java
+++ b/java/org/apache/catalina/valves/Constants.java
@@ -18,8 +18,7 @@ package org.apache.catalina.valves;
/**
- * Manifest constants for the <code>org.apache.catalina.valves</code>
- * package.
+ * Manifest constants for the <code>org.apache.catalina.valves</code> package.
*
* @author Craig R. McClanahan
*/
diff --git a/java/org/apache/catalina/valves/CrawlerSessionManagerValve.java b/java/org/apache/catalina/valves/CrawlerSessionManagerValve.java
index cfb46779e4..04472e5562 100644
--- a/java/org/apache/catalina/valves/CrawlerSessionManagerValve.java
+++ b/java/org/apache/catalina/valves/CrawlerSessionManagerValve.java
@@ -37,11 +37,9 @@ import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
- * Web crawlers can trigger the creation of many thousands of sessions as they
- * crawl a site which may result in significant memory consumption. This Valve
- * ensures that crawlers are associated with a single session - just like normal
- * users - regardless of whether or not they provide a session token with their
- * requests.
+ * Web crawlers can trigger the creation of many thousands of sessions as they crawl a site which may result in
+ * significant memory consumption. This Valve ensures that crawlers are associated with a single session - just like
+ * normal users - regardless of whether or not they provide a session token with their requests.
*/
public class CrawlerSessionManagerValve extends ValveBase {
@@ -72,9 +70,8 @@ public class CrawlerSessionManagerValve extends ValveBase {
/**
- * Specify the regular expression (using {@link Pattern}) that will be used
- * to identify crawlers based in the User-Agent header provided. The default
- * is ".*GoogleBot.*|.*bingbot.*|.*Yahoo! Slurp.*"
+ * Specify the regular expression (using {@link Pattern}) that will be used to identify crawlers based in the
+ * User-Agent header provided. The default is ".*GoogleBot.*|.*bingbot.*|.*Yahoo! Slurp.*"
*
* @param crawlerUserAgents The regular expression using {@link Pattern}
*/
@@ -89,7 +86,8 @@ public class CrawlerSessionManagerValve extends ValveBase {
/**
* @see #setCrawlerUserAgents(String)
- * @return The current regular expression being used to match user agents.
+ *
+ * @return The current regular expression being used to match user agents.
*/
public String getCrawlerUserAgents() {
return crawlerUserAgents;
@@ -97,9 +95,8 @@ public class CrawlerSessionManagerValve extends ValveBase {
/**
- * Specify the regular expression (using {@link Pattern}) that will be used
- * to identify crawlers based on their IP address. The default is no crawler
- * IPs.
+ * Specify the regular expression (using {@link Pattern}) that will be used to identify crawlers based on their IP
+ * address. The default is no crawler IPs.
*
* @param crawlerIps The regular expression using {@link Pattern}
*/
@@ -114,6 +111,7 @@ public class CrawlerSessionManagerValve extends ValveBase {
/**
* @see #setCrawlerIps(String)
+ *
* @return The current regular expression being used to match IP addresses.
*/
public String getCrawlerIps() {
@@ -122,10 +120,10 @@ public class CrawlerSessionManagerValve extends ValveBase {
/**
- * Specify the session timeout (in seconds) for a crawler's session. This is
- * typically lower than that for a user session. The default is 60 seconds.
+ * Specify the session timeout (in seconds) for a crawler's session. This is typically lower than that for a user
+ * session. The default is 60 seconds.
*
- * @param sessionInactiveInterval The new timeout for crawler sessions
+ * @param sessionInactiveInterval The new timeout for crawler sessions
*/
public void setSessionInactiveInterval(int sessionInactiveInterval) {
this.sessionInactiveInterval = sessionInactiveInterval;
@@ -133,7 +131,8 @@ public class CrawlerSessionManagerValve extends ValveBase {
/**
* @see #setSessionInactiveInterval(int)
- * @return The current timeout in seconds
+ *
+ * @return The current timeout in seconds
*/
public int getSessionInactiveInterval() {
return sessionInactiveInterval;
@@ -182,8 +181,8 @@ public class CrawlerSessionManagerValve extends ValveBase {
String clientIdentifier = getClientIdentifier(request.getHost(), request.getContext(), clientIp);
if (log.isDebugEnabled()) {
- log.debug(request.hashCode() + ": ClientIdentifier=" + clientIdentifier + ", RequestedSessionId="
- + request.getRequestedSessionId());
+ log.debug(request.hashCode() + ": ClientIdentifier=" + clientIdentifier + ", RequestedSessionId=" +
+ request.getRequestedSessionId());
}
// If the incoming request has a valid session ID, no action is required
@@ -252,8 +251,7 @@ public class CrawlerSessionManagerValve extends ValveBase {
}
} else {
if (log.isDebugEnabled()) {
- log.debug(
- request.hashCode() + ": Bot session accessed. SessionID=" + sessionId);
+ log.debug(request.hashCode() + ": Bot session accessed. SessionID=" + sessionId);
}
}
}
diff --git a/java/org/apache/catalina/valves/ErrorReportValve.java b/java/org/apache/catalina/valves/ErrorReportValve.java
index 44548e1170..ee5b4a2ec0 100644
--- a/java/org/apache/catalina/valves/ErrorReportValve.java
+++ b/java/org/apache/catalina/valves/ErrorReportValve.java
@@ -42,12 +42,15 @@ import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.util.security.Escape;
/**
- * <p>Implementation of a Valve that outputs HTML error pages.</p>
- *
- * <p>This Valve should be attached at the Host level, although it will work
- * if attached to a Context.</p>
- *
- * <p>HTML code from the Cocoon 2 project.</p>
+ * <p>
+ * Implementation of a Valve that outputs HTML error pages.
+ * </p>
+ * <p>
+ * This Valve should be attached at the Host level, although it will work if attached to a Context.
+ * </p>
+ * <p>
+ * HTML code from the Cocoon 2 project.
+ * </p>
*
* @author Remy Maucherat
* @author Craig R. McClanahan
@@ -64,7 +67,7 @@ public class ErrorReportValve extends ValveBase {
private final ErrorPageSupport errorPageSupport = new ErrorPageSupport();
- //------------------------------------------------------ Constructor
+ // ------------------------------------------------------ Constructor
public ErrorReportValve() {
super(true);
@@ -74,15 +77,13 @@ public class ErrorReportValve extends ValveBase {
// --------------------------------------------------------- Public Methods
/**
- * Invoke the next Valve in the sequence. When the invoke returns, check
- * the response state. If the status code is greater than or equal to 400
- * or an uncaught exception was thrown then the error handling will be
- * triggered.
+ * Invoke the next Valve in the sequence. When the invoke returns, check the response state. If the status code is
+ * greater than or equal to 400 or an uncaught exception was thrown then the error handling will be triggered.
*
- * @param request The servlet request to be processed
+ * @param request The servlet request to be processed
* @param response The servlet response to be created
*
- * @exception IOException if an input/output error occurs
+ * @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
@Override
@@ -155,7 +156,8 @@ public class ErrorReportValve extends ValveBase {
* Return the error page associated with the specified status and exception.
*
* @param statusCode the status code
- * @param throwable the exception
+ * @param throwable the exception
+ *
* @return the associated error page
*/
protected ErrorPage findErrorPage(int statusCode, Throwable throwable) {
@@ -177,10 +179,9 @@ public class ErrorReportValve extends ValveBase {
/**
* Prints out an error report.
*
- * @param request The request being processed
- * @param response The response being generated
- * @param throwable The exception that occurred (which possibly wraps
- * a root cause exception
+ * @param request The request being processed
+ * @param response The response being generated
+ * @param throwable The exception that occurred (which possibly wraps a root cause exception
*/
protected void report(Request request, Response response, Throwable throwable) {
@@ -189,7 +190,7 @@ public class ErrorReportValve extends ValveBase {
// Do nothing on a 1xx, 2xx and 3xx status
// Do nothing if anything has been written already
// Do nothing if the response hasn't been explicitly marked as in error
- // and that error has not been reported.
+ // and that error has not been reported.
if (statusCode < 400 || response.getContentWritten() > 0 || !response.setErrorReported()) {
return;
}
@@ -231,8 +232,7 @@ public class ErrorReportValve extends ValveBase {
// no error message provided
String reason = null;
String description = null;
- StringManager smClient = StringManager.getManager(
- Constants.Package, request.getLocales());
+ StringManager smClient = StringManager.getManager(Constants.Package, request.getLocales());
response.setLocale(smClient.getLocale());
try {
reason = smClient.getString("http." + statusCode + ".reason");
@@ -255,16 +255,15 @@ public class ErrorReportValve extends ValveBase {
sb.append(smClient.getLocale().getLanguage()).append("\">");
sb.append("<head>");
sb.append("<title>");
- sb.append(smClient.getString("errorReportValve.statusHeader",
- String.valueOf(statusCode), reason));
+ sb.append(smClient.getString("errorReportValve.statusHeader", String.valueOf(statusCode), reason));
sb.append("</title>");
sb.append("<style type=\"text/css\">");
sb.append(TomcatCSS.TOMCAT_CSS);
sb.append("</style>");
sb.append("</head><body>");
sb.append("<h1>");
- sb.append(smClient.getString("errorReportValve.statusHeader",
- String.valueOf(statusCode), reason)).append("</h1>");
+ sb.append(smClient.getString("errorReportValve.statusHeader", String.valueOf(statusCode), reason))
+ .append("</h1>");
if (isShowReport()) {
sb.append("<hr class=\"line\" />");
sb.append("<p><b>");
@@ -348,9 +347,10 @@ public class ErrorReportValve extends ValveBase {
/**
- * Print out a partial servlet stack trace (truncating at the last
- * occurrence of jakarta.servlet.).
+ * Print out a partial servlet stack trace (truncating at the last occurrence of jakarta.servlet.).
+ *
* @param t The stack trace to process
+ *
* @return the stack trace relative to the application layer
*/
protected String getPartialServletStackTrace(Throwable t) {
@@ -359,16 +359,14 @@ public class ErrorReportValve extends ValveBase {
StackTraceElement[] elements = t.getStackTrace();
int pos = elements.length;
for (int i = elements.length - 1; i >= 0; i--) {
- if ((elements[i].getClassName().startsWith
- ("org.apache.catalina.core.ApplicationFilterChain"))
- && (elements[i].getMethodName().equals("internalDoFilter"))) {
+ if ((elements[i].getClassName().startsWith("org.apache.catalina.core.ApplicationFilterChain")) &&
+ (elements[i].getMethodName().equals("internalDoFilter"))) {
pos = i;
break;
}
}
for (int i = 0; i < pos; i++) {
- if (!(elements[i].getClassName().startsWith
- ("org.apache.catalina.core."))) {
+ if (!(elements[i].getClassName().startsWith("org.apache.catalina.core."))) {
trace.append('\t').append(elements[i].toString()).append(System.lineSeparator());
}
}
@@ -382,8 +380,7 @@ public class ErrorReportValve extends ValveBase {
file = new File(getContainer().getCatalinaBase(), location);
}
if (!file.isFile() || !file.canRead()) {
- getContainer().getLogger().warn(
- sm.getString("errorReportValve.errorPageNotFound", location));
+ getContainer().getLogger().warn(sm.getString("errorReportValve.errorPageNotFound", location));
return false;
}
@@ -392,12 +389,10 @@ public class ErrorReportValve extends ValveBase {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
- try (OutputStream os = response.getOutputStream();
- InputStream is = new FileInputStream(file);){
+ try (OutputStream os = response.getOutputStream(); InputStream is = new FileInputStream(file);) {
IOTools.flow(is, os);
} catch (IOException e) {
- getContainer().getLogger().warn(
- sm.getString("errorReportValve.errorPageIOException", location), e);
+ getContainer().getLogger().warn(sm.getString("errorReportValve.errorPageIOException", location), e);
return false;
}
diff --git a/java/org/apache/catalina/valves/ExtendedAccessLogValve.java b/java/org/apache/catalina/valves/ExtendedAccessLogValve.java
index 62faf87356..86c87f5bf7 100644
--- a/java/org/apache/catalina/valves/ExtendedAccessLogValve.java
+++ b/java/org/apache/catalina/valves/ExtendedAccessLogValve.java
@@ -41,84 +41,63 @@ import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.ExceptionUtils;
/**
- * An implementation of the W3c Extended Log File Format. See
- * http://www.w3.org/TR/WD-logfile.html for more information about the format.
- *
- * The following fields are supported:
+ * An implementation of the W3c Extended Log File Format. See http://www.w3.org/TR/WD-logfile.html for more information
+ * about the format. The following fields are supported:
* <ul>
- * <li><code>c-dns</code>: Client hostname (or ip address if
- * <code>enableLookups</code> for the connector is false)</li>
- * <li><code>c-ip</code>: Client ip address</li>
- * <li><code>bytes</code>: bytes served</li>
- * <li><code>cs-method</code>: request method</li>
- * <li><code>cs-uri</code>: The full uri requested</li>
- * <li><code>cs-uri-query</code>: The query string</li>
- * <li><code>cs-uri-stem</code>: The uri without query string</li>
- * <li><code>date</code>: The date in yyyy-mm-dd format for GMT</li>
- * <li><code>s-dns</code>: The server dns entry </li>
- * <li><code>s-ip</code>: The server ip address</li>
- * <li><code>cs(XXX)</code>: The value of header XXX from client to server</li>
- * <li><code>sc(XXX)</code>: The value of header XXX from server to client </li>
- * <li><code>sc-status</code>: The status code</li>
- * <li><code>time</code>: Time the request was served</li>
- * <li><code>time-taken</code>: Time (in seconds) taken to serve the request</li>
+ * <li><code>c-dns</code>: Client hostname (or ip address if <code>enableLookups</code> for the connector is false)</li>
+ * <li><code>c-ip</code>: Client ip address</li>
+ * <li><code>bytes</code>: bytes served</li>
+ * <li><code>cs-method</code>: request method</li>
+ * <li><code>cs-uri</code>: The full uri requested</li>
+ * <li><code>cs-uri-query</code>: The query string</li>
+ * <li><code>cs-uri-stem</code>: The uri without query string</li>
+ * <li><code>date</code>: The date in yyyy-mm-dd format for GMT</li>
+ * <li><code>s-dns</code>: The server dns entry</li>
+ * <li><code>s-ip</code>: The server ip address</li>
+ * <li><code>cs(XXX)</code>: The value of header XXX from client to server</li>
+ * <li><code>sc(XXX)</code>: The value of header XXX from server to client</li>
+ * <li><code>sc-status</code>: The status code</li>
+ * <li><code>time</code>: Time the request was served</li>
+ * <li><code>time-taken</code>: Time (in seconds) taken to serve the request</li>
* <li><code>x-threadname</code>: Current request thread name (can compare later with stacktraces)</li>
- * <li><code>x-A(XXX)</code>: Pull XXX attribute from the servlet context </li>
- * <li><code>x-C(XXX)</code>: Pull the cookie(s) of the name XXX </li>
- * <li><code>x-O(XXX)</code>: Pull the all response header values XXX </li>
- * <li><code>x-R(XXX)</code>: Pull XXX attribute from the servlet request </li>
- * <li><code>x-S(XXX)</code>: Pull XXX attribute from the session </li>
- * <li><code>x-P(...)</code>: Call request.getParameter(...)
- * and URLencode it. Helpful to capture
- * certain POST parameters.
- * </li>
- * <li>For any of the x-H(...) the following method will be called from the
- * HttpServletRequest object </li>
- * <li><code>x-H(authType)</code>: getAuthType </li>
- * <li><code>x-H(characterEncoding)</code>: getCharacterEncoding </li>
- * <li><code>x-H(contentLength)</code>: getContentLength </li>
- * <li><code>x-H(locale)</code>: getLocale</li>
- * <li><code>x-H(protocol)</code>: getProtocol </li>
- * <li><code>x-H(remoteUser)</code>: getRemoteUser</li>
+ * <li><code>x-A(XXX)</code>: Pull XXX attribute from the servlet context</li>
+ * <li><code>x-C(XXX)</code>: Pull the cookie(s) of the name XXX</li>
+ * <li><code>x-O(XXX)</code>: Pull the all response header values XXX</li>
+ * <li><code>x-R(XXX)</code>: Pull XXX attribute from the servlet request</li>
+ * <li><code>x-S(XXX)</code>: Pull XXX attribute from the session</li>
+ * <li><code>x-P(...)</code>: Call request.getParameter(...) and URLencode it. Helpful to capture certain POST
+ * parameters.</li>
+ * <li>For any of the x-H(...) the following method will be called from the HttpServletRequest object</li>
+ * <li><code>x-H(authType)</code>: getAuthType</li>
+ * <li><code>x-H(characterEncoding)</code>: getCharacterEncoding</li>
+ * <li><code>x-H(contentLength)</code>: getContentLength</li>
+ * <li><code>x-H(locale)</code>: getLocale</li>
+ * <li><code>x-H(protocol)</code>: getProtocol</li>
+ * <li><code>x-H(remoteUser)</code>: getRemoteUser</li>
* <li><code>x-H(requestedSessionId)</code>: getRequestedSessionId</li>
- * <li><code>x-H(requestedSessionIdFromCookie)</code>:
- * isRequestedSessionIdFromCookie </li>
- * <li><code>x-H(requestedSessionIdValid)</code>:
- * isRequestedSessionIdValid</li>
- * <li><code>x-H(scheme)</code>: getScheme</li>
- * <li><code>x-H(secure)</code>: isSecure</li>
+ * <li><code>x-H(requestedSessionIdFromCookie)</code>: isRequestedSessionIdFromCookie</li>
+ * <li><code>x-H(requestedSessionIdValid)</code>: isRequestedSessionIdValid</li>
+ * <li><code>x-H(scheme)</code>: getScheme</li>
+ * <li><code>x-H(secure)</code>: isSecure</li>
* </ul>
- *
- *
- *
* <p>
- * Log rotation can be on or off. This is dictated by the
- * <code>rotatable</code> property.
+ * Log rotation can be on or off. This is dictated by the <code>rotatable</code> property.
* </p>
- *
* <p>
- * For UNIX users, another field called <code>checkExists</code> is also
- * available. If set to true, the log file's existence will be checked before
- * each logging. This way an external log rotator can move the file
- * somewhere and Tomcat will start with a new file.
+ * For UNIX users, another field called <code>checkExists</code> is also available. If set to true, the log file's
+ * existence will be checked before each logging. This way an external log rotator can move the file somewhere and
+ * Tomcat will start with a new file.
* </p>
- *
* <p>
- * For JMX junkies, a public method called <code>rotate</code> has
- * been made available to allow you to tell this instance to move
- * the existing log file to somewhere else and start writing a new log file.
+ * For JMX junkies, a public method called <code>rotate</code> has been made available to allow you to tell this
+ * instance to move the existing log file to somewhere else and start writing a new log file.
* </p>
- *
* <p>
- * Conditional logging is also supported. This can be done with the
- * <code>condition</code> property.
- * If the value returned from ServletRequest.getAttribute(condition)
- * yields a non-null value, the logging will be skipped.
+ * Conditional logging is also supported. This can be done with the <code>condition</code> property. If the value
+ * returned from ServletRequest.getAttribute(condition) yields a non-null value, the logging will be skipped.
* </p>
- *
* <p>
- * For extended attributes coming from a getAttribute() call,
- * it is you responsibility to ensure there are no newline or
+ * For extended attributes coming from a getAttribute() call, it is you responsibility to ensure there are no newline or
* control characters.
* </p>
*
@@ -131,14 +110,13 @@ public class ExtendedAccessLogValve extends AccessLogValve {
// -------------------------------------------------------- Private Methods
/**
- * Wrap the incoming value with double quotes (") and escape any double
- * quotes appearing in the value using two double quotes ("").
+ * Wrap the incoming value with double quotes (") and escape any double quotes appearing in the value using two
+ * double quotes ("").
+ *
+ * @param value - The value to wrap
*
- * @param value - The value to wrap
- * @return '-' if null. Otherwise, toString() will
- * be called on the object and the value will be wrapped
- * in quotes and any quotes will be escaped with 2
- * sets of quotes.
+ * @return '-' if null. Otherwise, toString() will be called on the object and the value will be wrapped in quotes
+ * and any quotes will be escaped with 2 sets of quotes.
*/
static String wrap(Object value) {
String svalue;
@@ -181,7 +159,7 @@ public class ExtendedAccessLogValve extends AccessLogValve {
@Override
protected synchronized void open() {
super.open();
- if (currentLogFile.length()==0) {
+ if (currentLogFile.length() == 0) {
writer.println("#Fields: " + pattern);
writer.println("#Version: 2.0");
writer.println("#Software: " + ServerInfo.getServerInfo());
@@ -196,20 +174,16 @@ public class ExtendedAccessLogValve extends AccessLogValve {
// Milli-seconds in 24 hours
private static final long INTERVAL = (1000 * 60 * 60 * 24);
- private static final ThreadLocal<ElementTimestampStruct> currentDate =
- ThreadLocal.withInitial(() -> new ElementTimestampStruct("yyyy-MM-dd"));
+ private static final ThreadLocal<ElementTimestampStruct> currentDate = ThreadLocal
+ .withInitial(() -> new ElementTimestampStruct("yyyy-MM-dd"));
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
ElementTimestampStruct eds = currentDate.get();
long millis = eds.currentTimestamp.getTime();
- if (date.getTime() > (millis + INTERVAL -1) ||
- date.getTime() < millis) {
- eds.currentTimestamp.setTime(
- date.getTime() - (date.getTime() % INTERVAL));
- eds.currentTimestampString =
- eds.currentTimestampFormat.format(eds.currentTimestamp);
+ if (date.getTime() > (millis + INTERVAL - 1) || date.getTime() < millis) {
+ eds.currentTimestamp.setTime(date.getTime() - (date.getTime() % INTERVAL));
+ eds.currentTimestampString = eds.currentTimestampFormat.format(eds.currentTimestamp);
}
buf.append(eds.currentTimestampString);
}
@@ -219,20 +193,16 @@ public class ExtendedAccessLogValve extends AccessLogValve {
// Milli-seconds in a second
private static final long INTERVAL = 1000;
- private static final ThreadLocal<ElementTimestampStruct> currentTime =
- ThreadLocal.withInitial(() -> new ElementTimestampStruct("HH:mm:ss"));
+ private static final ThreadLocal<ElementTimestampStruct> currentTime = ThreadLocal
+ .withInitial(() -> new ElementTimestampStruct("HH:mm:ss"));
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
ElementTimestampStruct eds = currentTime.get();
long millis = eds.currentTimestamp.getTime();
- if (date.getTime() > (millis + INTERVAL -1) ||
- date.getTime() < millis) {
- eds.currentTimestamp.setTime(
- date.getTime() - (date.getTime() % INTERVAL));
- eds.currentTimestampString =
- eds.currentTimestampFormat.format(eds.currentTimestamp);
+ if (date.getTime() > (millis + INTERVAL - 1) || date.getTime() < millis) {
+ eds.currentTimestamp.setTime(date.getTime() - (date.getTime() % INTERVAL));
+ eds.currentTimestampString = eds.currentTimestampFormat.format(eds.currentTimestamp);
}
buf.append(eds.currentTimestampString);
}
@@ -244,9 +214,9 @@ public class ExtendedAccessLogValve extends AccessLogValve {
public RequestHeaderElement(String header) {
this.header = header;
}
+
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
buf.append(wrap(request.getHeader(header)));
}
}
@@ -259,8 +229,7 @@ public class ExtendedAccessLogValve extends AccessLogValve {
}
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
buf.append(wrap(response.getHeader(header)));
}
}
@@ -271,11 +240,10 @@ public class ExtendedAccessLogValve extends AccessLogValve {
public ServletContextElement(String attribute) {
this.attribute = attribute;
}
+
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
- buf.append(wrap(request.getContext().getServletContext()
- .getAttribute(attribute)));
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
+ buf.append(wrap(request.getContext().getServletContext().getAttribute(attribute)));
}
}
@@ -285,9 +253,9 @@ public class ExtendedAccessLogValve extends AccessLogValve {
public CookieElement(String name) {
this.name = name;
}
+
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
StringBuilder value = new StringBuilder();
boolean first = true;
Cookie[] c = request.getCookies();
@@ -301,7 +269,7 @@ public class ExtendedAccessLogValve extends AccessLogValve {
value.append(c[i].getValue());
}
}
- if (value.length() == 0 ) {
+ if (value.length() == 0) {
buf.append('-');
} else {
buf.append(wrap(value.toString()));
@@ -320,8 +288,7 @@ public class ExtendedAccessLogValve extends AccessLogValve {
}
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
if (null != response) {
Iterator<String> iter = response.getHeaders(header).iterator();
if (iter.hasNext()) {
@@ -337,7 +304,7 @@ public class ExtendedAccessLogValve extends AccessLogValve {
}
buf.append(wrap(buffer.toString()));
}
- return ;
+ return;
}
buf.append('-');
}
@@ -351,8 +318,7 @@ public class ExtendedAccessLogValve extends AccessLogValve {
}
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
buf.append(wrap(request.getAttribute(attribute)));
}
}
@@ -363,9 +329,9 @@ public class ExtendedAccessLogValve extends AccessLogValve {
public SessionAttributeElement(String attribute) {
this.attribute = attribute;
}
+
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
HttpSession session = null;
if (request != null) {
session = request.getSession(false);
@@ -382,19 +348,19 @@ public class ExtendedAccessLogValve extends AccessLogValve {
public RequestParameterElement(String parameter) {
this.parameter = parameter;
}
+
/**
- * urlEncode the given string. If null or empty, return null.
+ * urlEncode the given string. If null or empty, return null.
*/
private String urlEncode(String value) {
- if (null==value || value.length()==0) {
+ if (null == value || value.length() == 0) {
return null;
}
return URLEncoder.QUERY.encode(value, StandardCharsets.UTF_8);
}
@Override
- public void addElement(CharArrayWriter buf, Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
buf.append(wrap(urlEncode(request.getParameter(parameter))));
}
}
@@ -419,8 +385,8 @@ public class ExtendedAccessLogValve extends AccessLogValve {
}
public String getToken() throws IOException {
- if(ended) {
- return null ;
+ if (ended) {
+ return null;
}
String result = null;
@@ -430,27 +396,27 @@ public class ExtendedAccessLogValve extends AccessLogValve {
int c = sr.read();
while (c != -1) {
switch (c) {
- case ' ':
- result = buf.toString();
- buf.setLength(0);
- buf.append((char) c);
- return result;
- case '-':
- result = buf.toString();
- buf.setLength(0);
- subToken = true;
- return result;
- case '(':
- result = buf.toString();
- buf.setLength(0);
- parameter = true;
- return result;
- case ')':
- result = buf.toString();
- buf.setLength(0);
- break;
- default:
- buf.append((char) c);
+ case ' ':
+ result = buf.toString();
+ buf.setLength(0);
+ buf.append((char) c);
+ return result;
+ case '-':
+ result = buf.toString();
+ buf.setLength(0);
+ subToken = true;
+ return result;
+ case '(':
+ result = buf.toString();
+ buf.setLength(0);
+ parameter = true;
+ return result;
+ case ')':
+ result = buf.toString();
+ buf.setLength(0);
+ break;
+ default:
+ buf.append((char) c);
}
c = sr.read();
}
@@ -462,7 +428,7 @@ public class ExtendedAccessLogValve extends AccessLogValve {
}
}
- public String getParameter()throws IOException {
+ public String getParameter() throws IOException {
String result;
if (!parameter) {
return null;
@@ -482,8 +448,8 @@ public class ExtendedAccessLogValve extends AccessLogValve {
}
public String getWhiteSpaces() throws IOException {
- if(isEnded()) {
- return "" ;
+ if (isEnded()) {
+ return "";
}
StringBuilder whiteSpaces = new StringBuilder();
if (buf.length() > 0) {
@@ -509,7 +475,7 @@ public class ExtendedAccessLogValve extends AccessLogValve {
public String getRemains() throws IOException {
StringBuilder remains = new StringBuilder();
- for(int c = sr.read(); c != -1; c = sr.read()) {
+ for (int c = sr.read(); c != -1; c = sr.read()) {
remains.append((char) c);
}
return remains.toString();
@@ -595,8 +561,8 @@ public class ExtendedAccessLogValve extends AccessLogValve {
} else if ("dns".equals(nextToken)) {
return new AccessLogElement() {
@Override
- public void addElement(CharArrayWriter buf, Date date,
- Request request, Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response,
+ long time) {
String value;
try {
value = InetAddress.getLocalHost().getHostName();
@@ -621,8 +587,7 @@ public class ExtendedAccessLogValve extends AccessLogValve {
return null;
}
- protected AccessLogElement getClientToServerElement(
- PatternTokenizer tokenizer) throws IOException {
+ protected AccessLogElement getClientToServerElement(PatternTokenizer tokenizer) throws IOException {
if (tokenizer.hasSubToken()) {
String token = tokenizer.getToken();
if ("method".equals(token)) {
@@ -635,9 +600,8 @@ public class ExtendedAccessLogValve extends AccessLogValve {
} else if ("query".equals(token)) {
return new AccessLogElement() {
@Override
- public void addElement(CharArrayWriter buf,
- Date date, Request request,
- Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response,
+ long time) {
String query = request.getQueryString();
if (query != null) {
buf.append(query);
@@ -650,8 +614,8 @@ public class ExtendedAccessLogValve extends AccessLogValve {
} else {
return new AccessLogElement() {
@Override
- public void addElement(CharArrayWriter buf, Date date,
- Request request, Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response,
+ long time) {
String query = request.getQueryString();
if (query == null) {
buf.append(request.getRequestURI());
@@ -676,8 +640,7 @@ public class ExtendedAccessLogValve extends AccessLogValve {
return null;
}
- protected AccessLogElement getServerToClientElement(
- PatternTokenizer tokenizer) throws IOException {
+ protected AccessLogElement getServerToClientElement(PatternTokenizer tokenizer) throws IOException {
if (tokenizer.hasSubToken()) {
String token = tokenizer.getToken();
if ("status".equals(token)) {
@@ -697,8 +660,7 @@ public class ExtendedAccessLogValve extends AccessLogValve {
return null;
}
- protected AccessLogElement getProxyElement(PatternTokenizer tokenizer)
- throws IOException {
+ protected AccessLogElement getProxyElement(PatternTokenizer tokenizer) throws IOException {
String token = null;
if (tokenizer.hasSubToken()) {
tokenizer.getToken();
@@ -711,8 +673,7 @@ public class ExtendedAccessLogValve extends AccessLogValve {
return null;
}
- protected AccessLogElement getXParameterElement(PatternTokenizer tokenizer)
- throws IOException {
+ protected AccessLogElement getXParameterElement(PatternTokenizer tokenizer) throws IOException {
if (!tokenizer.hasSubToken()) {
log.error(sm.getString("extendedAccessLogValve.badXParam"));
return null;
@@ -754,89 +715,77 @@ public class ExtendedAccessLogValve extends AccessLogValve {
if ("authType".equals(parameter)) {
return new AccessLogElement() {
@Override
- public void addElement(CharArrayWriter buf, Date date,
- Request request, Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
buf.append(wrap(request.getAuthType()));
}
};
} else if ("remoteUser".equals(parameter)) {
return new AccessLogElement() {
@Override
- public void addElement(CharArrayWriter buf, Date date,
- Request request, Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
buf.append(wrap(request.getRemoteUser()));
}
};
} else if ("requestedSessionId".equals(parameter)) {
return new AccessLogElement() {
@Override
- public void addElement(CharArrayWriter buf, Date date,
- Request request, Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
buf.append(wrap(request.getRequestedSessionId()));
}
};
} else if ("requestedSessionIdFromCookie".equals(parameter)) {
return new AccessLogElement() {
@Override
- public void addElement(CharArrayWriter buf, Date date,
- Request request, Response response, long time) {
- buf.append(wrap(""
- + request.isRequestedSessionIdFromCookie()));
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
+ buf.append(wrap("" + request.isRequestedSessionIdFromCookie()));
}
};
} else if ("requestedSessionIdValid".equals(parameter)) {
return new AccessLogElement() {
@Override
- public void addElement(CharArrayWriter buf, Date date,
- Request request, Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
buf.append(wrap("" + request.isRequestedSessionIdValid()));
}
};
} else if ("contentLength".equals(parameter)) {
return new AccessLogElement() {
@Override
- public void addElement(CharArrayWriter buf, Date date,
- Request request, Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
buf.append(wrap("" + request.getContentLengthLong()));
}
};
} else if ("characterEncoding".equals(parameter)) {
return new AccessLogElement() {
@Override
- public void addElement(CharArrayWriter buf, Date date,
- Request request, Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
buf.append(wrap(request.getCharacterEncoding()));
}
};
} else if ("locale".equals(parameter)) {
return new AccessLogElement() {
@Override
- public void addElement(CharArrayWriter buf, Date date,
- Request request, Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
buf.append(wrap(request.getLocale()));
}
};
} else if ("protocol".equals(parameter)) {
return new AccessLogElement() {
@Override
- public void addElement(CharArrayWriter buf, Date date,
- Request request, Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
buf.append(wrap(request.getProtocol()));
}
};
} else if ("scheme".equals(parameter)) {
return new AccessLogElement() {
@Override
- public void addElement(CharArrayWriter buf, Date date,
- Request request, Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
buf.append(request.getScheme());
}
};
} else if ("secure".equals(parameter)) {
return new AccessLogElement() {
@Override
- public void addElement(CharArrayWriter buf, Date date,
- Request request, Response response, long time) {
+ public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) {
buf.append(wrap("" + request.isSecure()));
}
};
diff --git a/java/org/apache/catalina/valves/HealthCheckValve.java b/java/org/apache/catalina/valves/HealthCheckValve.java
index b932260fc3..dbc9c3bbe8 100644
--- a/java/org/apache/catalina/valves/HealthCheckValve.java
+++ b/java/org/apache/catalina/valves/HealthCheckValve.java
@@ -35,17 +35,9 @@ import org.apache.tomcat.util.buf.MessageBytes;
*/
public class HealthCheckValve extends ValveBase {
- private static final String UP =
- "{\n" +
- " \"status\": \"UP\",\n" +
- " \"checks\": []\n" +
- "}";
-
- private static final String DOWN =
- "{\n" +
- " \"status\": \"DOWN\",\n" +
- " \"checks\": []\n" +
- "}";
+ private static final String UP = "{\n" + " \"status\": \"UP\",\n" + " \"checks\": []\n" + "}";
+
+ private static final String DOWN = "{\n" + " \"status\": \"DOWN\",\n" + " \"checks\": []\n" + "}";
private String path = "/health";
@@ -86,10 +78,8 @@ public class HealthCheckValve extends ValveBase {
}
@Override
- public void invoke(Request request, Response response)
- throws IOException, ServletException {
- MessageBytes urlMB =
- context ? request.getRequestPathMB() : request.getDecodedRequestURIMB();
+ public void invoke(Request request, Response response) throws IOException, ServletException {
+ MessageBytes urlMB = context ? request.getRequestPathMB() : request.getDecodedRequestURIMB();
if (urlMB.equals(path)) {
response.setContentType("application/json");
if (!checkContainersAvailable || isAvailable(getContainer())) {
diff --git a/java/org/apache/catalina/valves/JDBCAccessLogValve.java b/java/org/apache/catalina/valves/JDBCAccessLogValve.java
index 7526962f85..23f664b3ad 100644
--- a/java/org/apache/catalina/valves/JDBCAccessLogValve.java
+++ b/java/org/apache/catalina/valves/JDBCAccessLogValve.java
@@ -36,12 +36,11 @@ import org.apache.tomcat.util.ExceptionUtils;
/**
* <p>
- * This Tomcat extension logs server access directly to a database, and can
- * be used instead of the regular file-based access log implemented in
- * AccessLogValve.
- * To use, copy into the server/classes directory of the Tomcat installation
+ * This Tomcat extension logs server access directly to a database, and can be used instead of the regular file-based
+ * access log implemented in AccessLogValve. To use, copy into the server/classes directory of the Tomcat installation
* and configure in server.xml as:
* </p>
+ *
* <pre>
* <Valve className="org.apache.catalina.valves.JDBCAccessLogValve"
* driverName="<i>your_jdbc_driver</i>"
@@ -50,24 +49,20 @@ import org.apache.tomcat.util.ExceptionUtils;
* />
* </pre>
* <p>
- * Many parameters can be configured, such as the database connection (with
- * <code>driverName</code> and <code>connectionURL</code>),
- * the table name (<code>tableName</code>)
- * and the field names (corresponding to the get/set method names).
- * The same options as AccessLogValve are supported, such as
- * <code>resolveHosts</code> and <code>pattern</code> ("common" or "combined"
- * only).
+ * Many parameters can be configured, such as the database connection (with <code>driverName</code> and
+ * <code>connectionURL</code>), the table name (<code>tableName</code>) and the field names (corresponding to the
+ * get/set method names). The same options as AccessLogValve are supported, such as <code>resolveHosts</code> and
+ * <code>pattern</code> ("common" or "combined" only).
* </p>
* <p>
- * When Tomcat is started, a database connection is created and used for all the
- * log activity. When Tomcat is shutdown, the database connection is closed.
- * This logger can be used at the level of the Engine context (being shared
- * by all the defined hosts) or the Host context (one instance of the logger
- * per host, possibly using different databases).
+ * When Tomcat is started, a database connection is created and used for all the log activity. When Tomcat is shutdown,
+ * the database connection is closed. This logger can be used at the level of the Engine context (being shared by all
+ * the defined hosts) or the Host context (one instance of the logger per host, possibly using different databases).
* </p>
* <p>
* The database table can be created with the following command:
* </p>
+ *
* <pre>
* CREATE TABLE access (
* id INT UNSIGNED AUTO_INCREMENT NOT NULL,
@@ -89,14 +84,13 @@ import org.apache.tomcat.util.ExceptionUtils;
* INDEX (userAgent)
* );
* </pre>
- * <p>Set JDBCAccessLogValve attribute useLongContentLength="true" as you have more then 4GB outputs.
- * Please, use long SQL datatype at access.bytes attribute.
- * The datatype of bytes at oracle is <i>number</i> and other databases use <i>bytes BIGINT NOT NULL</i>.
+ * <p>
+ * Set JDBCAccessLogValve attribute useLongContentLength="true" as you have more then 4GB outputs. Please, use long SQL
+ * datatype at access.bytes attribute. The datatype of bytes at oracle is <i>number</i> and other databases use <i>bytes
+ * BIGINT NOT NULL</i>.
* </p>
- *
* <p>
- * If the table is created as above, its name and the field names don't need
- * to be defined.
+ * If the table is created as above, its name and the field names don't need to be defined.
* </p>
* <p>
* If the request method is "common", only these fields are used:
@@ -116,24 +110,24 @@ public final class JDBCAccessLogValve extends ValveBase implements AccessLog {
/**
- * Class constructor. Initializes the fields with the default values.
- * The defaults are:
+ * Class constructor. Initializes the fields with the default values. The defaults are:
+ *
* <pre>
- * driverName = null;
- * connectionURL = null;
- * tableName = "access";
- * remoteHostField = "remoteHost";
- * userField = "userName";
- * timestampField = "timestamp";
- * virtualHostField = "virtualHost";
- * methodField = "method";
- * queryField = "query";
- * statusField = "status";
- * bytesField = "bytes";
- * refererField = "referer";
- * userAgentField = "userAgent";
- * pattern = "common";
- * resolveHosts = false;
+ * driverName = null;
+ * connectionURL = null;
+ * tableName = "access";
+ * remoteHostField = "remoteHost";
+ * userField = "userName";
+ * timestampField = "timestamp";
+ * virtualHostField = "virtualHost";
+ * methodField = "method";
+ * queryField = "query";
+ * statusField = "status";
+ * bytesField = "bytes";
+ * refererField = "referer";
+ * userAgentField = "userAgent";
+ * pattern = "common";
+ * resolveHosts = false;
* </pre>
*/
public JDBCAccessLogValve() {
@@ -161,13 +155,14 @@ public final class JDBCAccessLogValve extends ValveBase implements AccessLog {
// ----------------------------------------------------- Instance Variables
- /**
- * Use long contentLength as you have more 4 GB output.
- * @since 6.0.15
- */
+ /**
+ * Use long contentLength as you have more 4 GB output.
+ *
+ * @since 6.0.15
+ */
boolean useLongContentLength = false;
- /**
+ /**
* The connection username to use when trying to connect to the database.
*/
String connectionName = null;
@@ -178,7 +173,7 @@ public final class JDBCAccessLogValve extends ValveBase implements AccessLog {
*/
String connectionPassword = null;
- /**
+ /**
* Instance of the JDBC Driver class we use as a connection factory.
*/
Driver driver = null;
@@ -208,9 +203,9 @@ public final class JDBCAccessLogValve extends ValveBase implements AccessLog {
private long currentTimeMillis;
/**
- * Should this valve set request attributes for IP address, hostname,
- * protocol and port used for the request.
+ * Should this valve set request attributes for IP address, hostname, protocol and port used for the request.
* Default is <code>true</code>.
+ *
* @see #setRequestAttributesEnabled(boolean)
*/
boolean requestAttributesEnabled = true;
@@ -219,8 +214,7 @@ public final class JDBCAccessLogValve extends ValveBase implements AccessLog {
// ------------------------------------------------------------- Properties
/**
- * {@inheritDoc}
- * Default is <code>true</code>.
+ * {@inheritDoc} Default is <code>true</code>.
*/
@Override
public void setRequestAttributesEnabled(boolean requestAttributesEnabled) {
@@ -327,8 +321,7 @@ public final class JDBCAccessLogValve extends ValveBase implements AccessLog {
/**
- * Sets the name of the field containing the virtual host information
- * (this is in fact the server name).
+ * Sets the name of the field containing the virtual host information (this is in fact the server name).
*
* @param virtualHostField The name of the virtual host field.
*/
@@ -350,8 +343,7 @@ public final class JDBCAccessLogValve extends ValveBase implements AccessLog {
/**
* Sets the name of the field containing the URL part of the HTTP query.
*
- * @param queryField The name of the field containing the URL part of
- * the HTTP query.
+ * @param queryField The name of the field containing the URL part of the HTTP query.
*/
public void setQueryField(String queryField) {
this.queryField = queryField;
@@ -399,10 +391,11 @@ public final class JDBCAccessLogValve extends ValveBase implements AccessLog {
/**
- * Sets the logging pattern. The patterns supported correspond to the
- * file-based "common" and "combined". These are translated into the use
- * of tables containing either set of fields.
- * <P><I>TO DO: more flexible field choices.</I></P>
+ * Sets the logging pattern. The patterns supported correspond to the file-based "common" and "combined". These are
+ * translated into the use of tables containing either set of fields.
+ * <P>
+ * <I>TO DO: more flexible field choices.</I>
+ * </P>
*
* @param pattern The name of the logging pattern.
*/
@@ -414,16 +407,15 @@ public final class JDBCAccessLogValve extends ValveBase implements AccessLog {
/**
* Determines whether IP host name resolution is done.
*
- * @param resolveHosts "true" or "false", if host IP resolution
- * is desired or not.
+ * @param resolveHosts "true" or "false", if host IP resolution is desired or not.
*/
public void setResolveHosts(String resolveHosts) {
this.resolveHosts = Boolean.parseBoolean(resolveHosts);
}
/**
- * @return <code>true</code> if content length should be considered a long
- * rather than an int, defaults to <code>false</code>
+ * @return <code>true</code> if content length should be considered a long rather than an int, defaults to
+ * <code>false</code>
*/
public boolean getUseLongContentLength() {
return this.useLongContentLength;
@@ -442,16 +434,14 @@ public final class JDBCAccessLogValve extends ValveBase implements AccessLog {
/**
* This method is invoked by Tomcat on each query.
*
- * @param request The Request object.
+ * @param request The Request object.
* @param response The Response object.
*
- * @exception IOException Should not be thrown.
- * @exception ServletException Database SQLException is wrapped
- * in a ServletException.
+ * @exception IOException Should not be thrown.
+ * @exception ServletException Database SQLException is wrapped in a ServletException.
*/
@Override
- public void invoke(Request request, Response response) throws IOException,
- ServletException {
+ public void invoke(Request request, Response response) throws IOException, ServletException {
getNext().invoke(request, response);
}
@@ -462,10 +452,10 @@ public final class JDBCAccessLogValve extends ValveBase implements AccessLog {
return;
}
- final String EMPTY = "" ;
+ final String EMPTY = "";
String remoteHost;
- if(resolveHosts) {
+ if (resolveHosts) {
if (requestAttributesEnabled) {
Object host = request.getAttribute(REMOTE_HOST_ATTRIBUTE);
if (host == null) {
@@ -489,10 +479,10 @@ public final class JDBCAccessLogValve extends ValveBase implements AccessLog {
}
}
String user = request.getRemoteUser();
- String query=request.getRequestURI();
+ String query = request.getRequestURI();
long bytes = response.getBytesWritten(true);
- if(bytes < 0) {
+ if (bytes < 0) {
bytes = 0;
}
int status = response.getStatus();
@@ -508,52 +498,51 @@ public final class JDBCAccessLogValve extends ValveBase implements AccessLog {
userAgent = request.getHeader("user-agent");
}
synchronized (this) {
- int numberOfTries = 2;
- while (numberOfTries>0) {
- try {
- open();
-
- ps.setString(1, remoteHost);
- ps.setString(2, user);
- ps.setTimestamp(3, new Timestamp(getCurrentTimeMillis()));
- ps.setString(4, query);
- ps.setInt(5, status);
-
- if(useLongContentLength) {
- ps.setLong(6, bytes);
- } else {
- if (bytes > Integer.MAX_VALUE) {
- bytes = -1 ;
+ int numberOfTries = 2;
+ while (numberOfTries > 0) {
+ try {
+ open();
+
+ ps.setString(1, remoteHost);
+ ps.setString(2, user);
+ ps.setTimestamp(3, new Timestamp(getCurrentTimeMillis()));
+ ps.setString(4, query);
+ ps.setInt(5, status);
+
+ if (useLongContentLength) {
+ ps.setLong(6, bytes);
+ } else {
+ if (bytes > Integer.MAX_VALUE) {
+ bytes = -1;
+ }
+ ps.setInt(6, (int) bytes);
+ }
+ if (logPattern.equals("combined")) {
+ ps.setString(7, virtualHost);
+ ps.setString(8, method);
+ ps.setString(9, referer);
+ ps.setString(10, userAgent);
+ }
+ ps.executeUpdate();
+ return;
+ } catch (SQLException e) {
+ // Log the problem for posterity
+ container.getLogger().error(sm.getString("jdbcAccessLogValve.exception"), e);
+
+ // Close the connection so that it gets reopened next time
+ if (conn != null) {
+ close();
}
- ps.setInt(6, (int) bytes);
- }
- if (logPattern.equals("combined")) {
- ps.setString(7, virtualHost);
- ps.setString(8, method);
- ps.setString(9, referer);
- ps.setString(10, userAgent);
- }
- ps.executeUpdate();
- return;
- } catch (SQLException e) {
- // Log the problem for posterity
- container.getLogger().error(sm.getString("jdbcAccessLogValve.exception"), e);
-
- // Close the connection so that it gets reopened next time
- if (conn != null) {
- close();
}
- }
- numberOfTries--;
- }
+ numberOfTries--;
+ }
}
}
/**
- * Open (if necessary) and return a database connection for use by
- * this AccessLogValve.
+ * Open (if necessary) and return a database connection for use by this AccessLogValve.
*
* @exception SQLException if a database error occurs
*/
@@ -561,7 +550,7 @@ public final class JDBCAccessLogValve extends ValveBase implements AccessLog {
// Do nothing if there is a database connection already open
if (conn != null) {
- return ;
+ return;
}
// Instantiate our database driver if necessary
@@ -587,21 +576,14 @@ public final class JDBCAccessLogValve extends ValveBase implements AccessLog {
conn.setAutoCommit(true);
String logPattern = pattern;
if (logPattern.equals("common")) {
- ps = conn.prepareStatement
- ("INSERT INTO " + tableName + " ("
- + remoteHostField + ", " + userField + ", "
- + timestampField +", " + queryField + ", "
- + statusField + ", " + bytesField
- + ") VALUES(?, ?, ?, ?, ?, ?)");
+ ps = conn.prepareStatement(
+ "INSERT INTO " + tableName + " (" + remoteHostField + ", " + userField + ", " + timestampField +
+ ", " + queryField + ", " + statusField + ", " + bytesField + ") VALUES(?, ?, ?, ?, ?, ?)");
} else if (logPattern.equals("combined")) {
- ps = conn.prepareStatement
- ("INSERT INTO " + tableName + " ("
- + remoteHostField + ", " + userField + ", "
- + timestampField + ", " + queryField + ", "
- + statusField + ", " + bytesField + ", "
- + virtualHostField + ", " + methodField + ", "
- + refererField + ", " + userAgentField
- + ") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
+ ps = conn.prepareStatement("INSERT INTO " + tableName + " (" + remoteHostField + ", " + userField + ", " +
+ timestampField + ", " + queryField + ", " + statusField + ", " + bytesField + ", " +
+ virtualHostField + ", " + methodField + ", " + refererField + ", " + userAgentField +
+ ") VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
}
}
@@ -624,31 +606,30 @@ public final class JDBCAccessLogValve extends ValveBase implements AccessLog {
this.ps = null;
-
// Close this database connection, and log any errors
try {
conn.close();
} catch (SQLException e) {
container.getLogger().error(sm.getString("jdbcAccessLogValve.close"), e); // Just log it here
} finally {
- this.conn = null;
+ this.conn = null;
}
}
/**
- * Start this component and implement the requirements
- * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
+ * 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 {
try {
- open() ;
+ open();
} catch (SQLException e) {
throw new LifecycleException(e);
}
@@ -658,25 +639,25 @@ public final class JDBCAccessLogValve extends ValveBase implements AccessLog {
/**
- * Stop this component and implement the requirements
- * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
+ * 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 {
setState(LifecycleState.STOPPING);
- close() ;
+ close();
}
public long getCurrentTimeMillis() {
- long systime = System.currentTimeMillis();
+ long systime = System.currentTimeMillis();
if ((systime - currentTimeMillis) > 1000) {
- currentTimeMillis = new java.util.Date(systime).getTime();
+ currentTimeMillis = new java.util.Date(systime).getTime();
}
return currentTimeMillis;
}
diff --git a/java/org/apache/catalina/valves/JsonErrorReportValve.java b/java/org/apache/catalina/valves/JsonErrorReportValve.java
index 1e7719fb51..c698ca3ce5 100644
--- a/java/org/apache/catalina/valves/JsonErrorReportValve.java
+++ b/java/org/apache/catalina/valves/JsonErrorReportValve.java
@@ -28,11 +28,12 @@ import org.apache.tomcat.util.json.JSONFilter;
import org.apache.tomcat.util.res.StringManager;
/**
- * <p>Implementation of a Valve that outputs error jsons.</p>
- *
- * <p>This Valve should be attached at the Host level, although it will work
- * if attached to a Context.</p>
- *
+ * <p>
+ * Implementation of a Valve that outputs error jsons.
+ * </p>
+ * <p>
+ * This Valve should be attached at the Host level, although it will work if attached to a Context.
+ * </p>
*/
public class JsonErrorReportValve extends ErrorReportValve {
@@ -48,7 +49,7 @@ public class JsonErrorReportValve extends ErrorReportValve {
// Do nothing on a 1xx, 2xx and 3xx status
// Do nothing if anything has been written already
// Do nothing if the response hasn't been explicitly marked as in error
- // and that error has not been reported.
+ // and that error has not been reported.
if (statusCode < 400 || response.getContentWritten() > 0 || !response.setErrorReported()) {
return;
}
@@ -82,11 +83,9 @@ public class JsonErrorReportValve extends ErrorReportValve {
description = smClient.getString("errorReportValve.noDescription");
}
}
- String jsonReport = "{\n" +
- " \"type\": \"" + JSONFilter.escape(type) + "\",\n" +
- " \"message\": \"" + JSONFilter.escape(message) + "\",\n" +
- " \"description\": \"" + JSONFilter.escape(description) + "\"\n" +
- "}";
+ String jsonReport = "{\n" + " \"type\": \"" + JSONFilter.escape(type) + "\",\n" + " \"message\": \"" +
+ JSONFilter.escape(message) + "\",\n" + " \"description\": \"" + JSONFilter.escape(description) +
+ "\"\n" + "}";
try {
try {
response.setContentType("application/json");
diff --git a/java/org/apache/catalina/valves/LoadBalancerDrainingValve.java b/java/org/apache/catalina/valves/LoadBalancerDrainingValve.java
index 7ef9386387..45b1ef5555 100644
--- a/java/org/apache/catalina/valves/LoadBalancerDrainingValve.java
+++ b/java/org/apache/catalina/valves/LoadBalancerDrainingValve.java
@@ -28,67 +28,58 @@ import org.apache.catalina.connector.Response;
import org.apache.catalina.util.SessionConfig;
/**
- * <p>A Valve to detect situations where a load-balanced node receiving a
- * request has been deactivated by the load balancer (JK_LB_ACTIVATION=DIS)
- * and the incoming request has no valid session.</p>
+ * <p>
+ * A Valve to detect situations where a load-balanced node receiving a request has been deactivated by the load balancer
+ * (JK_LB_ACTIVATION=DIS) and the incoming request has no valid session.
+ * </p>
+ * <p>
+ * In these cases, the user's session cookie should be removed if it exists, any ";jsessionid" parameter should be
+ * removed from the request URI, and the client should be redirected to the same URI. This will cause the load-balanced
+ * to re-balance the client to another server.
+ * </p>
+ * <p>
+ * All this work is required because when the activation state of a node is DISABLED, the load-balancer will still send
+ * requests to the node if they appear to have a session on that node. Since mod_jk doesn't actually know whether the
+ * session id is valid, it will send the request blindly to the disabled node, which makes it take much longer to drain
+ * the node than strictly necessary.
+ * </p>
+ * <p>
+ * For testing purposes, a special cookie can be configured and used by a client to ignore the normal behavior of this
+ * Valve and allow a client to get a new session on a DISABLED node. See {@link #setIgnoreCookieName} and
+ * {@link #setIgnoreCookieValue} to configure those values.
+ * </p>
+ * <p>
+ * This Valve should be installed earlier in the Valve pipeline than any authentication valves, as the redirection
+ * should take place before an authentication valve would save a request to a protected resource.
+ * </p>
*
- * <p>In these cases, the user's session cookie should be removed if it exists,
- * any ";jsessionid" parameter should be removed from the request URI,
- * and the client should be redirected to the same URI. This will cause the
- * load-balanced to re-balance the client to another server.</p>
- *
- * <p>All this work is required because when the activation state of a node is
- * DISABLED, the load-balancer will still send requests to the node if they
- * appear to have a session on that node. Since mod_jk doesn't actually know
- * whether the session id is valid, it will send the request blindly to
- * the disabled node, which makes it take much longer to drain the node
- * than strictly necessary.</p>
- *
- * <p>For testing purposes, a special cookie can be configured and used
- * by a client to ignore the normal behavior of this Valve and allow
- * a client to get a new session on a DISABLED node. See
- * {@link #setIgnoreCookieName} and {@link #setIgnoreCookieValue}
- * to configure those values.</p>
- *
- * <p>This Valve should be installed earlier in the Valve pipeline than any
- * authentication valves, as the redirection should take place before an
- * authentication valve would save a request to a protected resource.</p>
- *
- * @see <a href="https://tomcat.apache.org/connectors-doc/generic_howto/loadbalancers.html">Load
- * balancer documentation</a>
+ * @see <a href="https://tomcat.apache.org/connectors-doc/generic_howto/loadbalancers.html">Load balancer
+ * documentation</a>
*/
public class LoadBalancerDrainingValve extends ValveBase {
/**
- * The request attribute key where the load-balancer's activation state
- * can be found.
+ * The request attribute key where the load-balancer's activation state can be found.
*/
public static final String ATTRIBUTE_KEY_JK_LB_ACTIVATION = "JK_LB_ACTIVATION";
/**
- * The HTTP response code that will be used to redirect the request
- * back to the load-balancer for re-balancing. Defaults to 307
- * (TEMPORARY_REDIRECT).
- *
- * HTTP status code 305 (USE_PROXY) might be an option, here. too.
+ * The HTTP response code that will be used to redirect the request back to the load-balancer for re-balancing.
+ * Defaults to 307 (TEMPORARY_REDIRECT). HTTP status code 305 (USE_PROXY) might be an option, here. too.
*/
private int _redirectStatusCode = HttpServletResponse.SC_TEMPORARY_REDIRECT;
/**
- * The name of the cookie which can be set to ignore the "draining" action
- * of this Filter. This will allow a client to contact the server without
- * being re-balanced to another server. The expected cookie value can be set
- * in the {@link #_ignoreCookieValue}. The cookie name and value must match
- * to avoid being re-balanced.
+ * The name of the cookie which can be set to ignore the "draining" action of this Filter. This will allow a client
+ * to contact the server without being re-balanced to another server. The expected cookie value can be set in the
+ * {@link #_ignoreCookieValue}. The cookie name and value must match to avoid being re-balanced.
*/
private String _ignoreCookieName;
/**
- * The value of the cookie which can be set to ignore the "draining" action
- * of this Filter. This will allow a client to contact the server without
- * being re-balanced to another server. The expected cookie name can be set
- * in the {@link #_ignoreCookieName}. The cookie name and value must match
- * to avoid being re-balanced.
+ * The value of the cookie which can be set to ignore the "draining" action of this Filter. This will allow a client
+ * to contact the server without being re-balanced to another server. The expected cookie name can be set in the
+ * {@link #_ignoreCookieName}. The cookie name and value must match to avoid being re-balanced.
*/
private String _ignoreCookieValue;
@@ -101,9 +92,8 @@ public class LoadBalancerDrainingValve extends ValveBase {
//
/**
- * Sets the HTTP response code that will be used to redirect the request
- * back to the load-balancer for re-balancing. Defaults to 307
- * (TEMPORARY_REDIRECT).
+ * Sets the HTTP response code that will be used to redirect the request back to the load-balancer for re-balancing.
+ * Defaults to 307 (TEMPORARY_REDIRECT).
*
* @param code The code to use for the redirect
*/
@@ -112,9 +102,8 @@ public class LoadBalancerDrainingValve extends ValveBase {
}
/**
- * Gets the name of the cookie that can be used to override the
- * re-balancing behavior of this Valve when the current node is
- * in the DISABLED activation state.
+ * Gets the name of the cookie that can be used to override the re-balancing behavior of this Valve when the current
+ * node is in the DISABLED activation state.
*
* @return The cookie name used to ignore normal processing rules.
*
@@ -125,15 +114,11 @@ public class LoadBalancerDrainingValve extends ValveBase {
}
/**
- * Sets the name of the cookie that can be used to override the
- * re-balancing behavior of this Valve when the current node is
- * in the DISABLED activation state.
- *
- * There is no default value for this setting: the ability to override
- * the re-balancing behavior of this Valve is <i>disabled</i> by default.
+ * Sets the name of the cookie that can be used to override the re-balancing behavior of this Valve when the current
+ * node is in the DISABLED activation state. There is no default value for this setting: the ability to override the
+ * re-balancing behavior of this Valve is <i>disabled</i> by default.
*
- * @param cookieName The cookie name to use to ignore normal
- * processing rules.
+ * @param cookieName The cookie name to use to ignore normal processing rules.
*
* @see #getIgnoreCookieValue
*/
@@ -142,9 +127,8 @@ public class LoadBalancerDrainingValve extends ValveBase {
}
/**
- * Gets the expected value of the cookie that can be used to override the
- * re-balancing behavior of this Valve when the current node is
- * in the DISABLED activation state.
+ * Gets the expected value of the cookie that can be used to override the re-balancing behavior of this Valve when
+ * the current node is in the DISABLED activation state.
*
* @return The cookie value used to ignore normal processing rules.
*
@@ -155,14 +139,11 @@ public class LoadBalancerDrainingValve extends ValveBase {
}
/**
- * Sets the expected value of the cookie that can be used to override the
- * re-balancing behavior of this Valve when the current node is
- * in the DISABLED activation state. The "ignore" cookie's value
- * <b>must</b> be exactly equal to this value in order to allow
- * the client to override the re-balancing behavior.
+ * Sets the expected value of the cookie that can be used to override the re-balancing behavior of this Valve when
+ * the current node is in the DISABLED activation state. The "ignore" cookie's value <b>must</b> be exactly equal to
+ * this value in order to allow the client to override the re-balancing behavior.
*
- * @param cookieValue The cookie value to use to ignore normal
- * processing rules.
+ * @param cookieValue The cookie value to use to ignore normal processing rules.
*
* @see #getIgnoreCookieValue
*/
@@ -172,7 +153,7 @@ public class LoadBalancerDrainingValve extends ValveBase {
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
- if ("DIS".equals(request.getAttribute(ATTRIBUTE_KEY_JK_LB_ACTIVATION)) &&
+ if ("DIS".equals(request.getAttribute(ATTRIBUTE_KEY_JK_LB_ACTIVATION)) &&
!request.isRequestedSessionIdValid()) {
if (containerLog.isDebugEnabled()) {
@@ -196,10 +177,8 @@ public class LoadBalancerDrainingValve extends ValveBase {
if (sessionCookieName.equals(cookieName) &&
request.getRequestedSessionId().equals(cookie.getValue())) {
sessionCookie = cookie;
- } else if (null != _ignoreCookieName &&
- _ignoreCookieName.equals(cookieName) &&
- null != _ignoreCookieValue &&
- _ignoreCookieValue.equals(cookie.getValue())) {
+ } else if (null != _ignoreCookieName && _ignoreCookieName.equals(cookieName) &&
+ null != _ignoreCookieValue && _ignoreCookieValue.equals(cookie.getValue())) {
// The client presenting a valid ignore-cookie value?
ignoreRebalance = true;
}
@@ -224,7 +203,8 @@ public class LoadBalancerDrainingValve extends ValveBase {
sessionCookie.setMaxAge(0); // Delete
sessionCookie.setValue(""); // Purge the cookie's value
// Replicate logic used to set secure attribute for session cookies
- SessionCookieConfig sessionCookieConfig = request.getContext().getServletContext().getSessionCookieConfig();
+ SessionCookieConfig sessionCookieConfig = request.getContext().getServletContext()
+ .getSessionCookieConfig();
sessionCookie.setSecure(request.isSecure() || sessionCookieConfig.isSecure());
response.addCookie(sessionCookie);
}
diff --git a/java/org/apache/catalina/valves/PersistentValve.java b/java/org/apache/catalina/valves/PersistentValve.java
index bdf11da313..7681786ba1 100644
--- a/java/org/apache/catalina/valves/PersistentValve.java
+++ b/java/org/apache/catalina/valves/PersistentValve.java
@@ -35,13 +35,11 @@ import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
/**
- * Valve that implements per-request session persistence. It is intended to be
- * used with non-sticky load-balancers.
+ * Valve that implements per-request session persistence. It is intended to be used with non-sticky load-balancers.
* <p>
- * <b>USAGE CONSTRAINT</b>: To work correctly it requires a PersistentManager.
+ * <b>USAGE CONSTRAINT</b>: To work correctly it requires a PersistentManager.
* <p>
- * <b>USAGE CONSTRAINT</b>: To work correctly it assumes only one request exists
- * per session at any one time.
+ * <b>USAGE CONSTRAINT</b>: To work correctly it assumes only one request exists per session at any one time.
*
* @author Jean-Frederic Clere
*/
@@ -56,7 +54,7 @@ public class PersistentValve extends ValveBase {
protected Pattern filter = null;
- //------------------------------------------------------ Constructor
+ // ------------------------------------------------------ Constructor
public PersistentValve() {
super(true);
@@ -77,19 +75,17 @@ public class PersistentValve extends ValveBase {
/**
- * Select the appropriate child Context to process this request,
- * based on the specified request URI. If no matching Context can
- * be found, return an appropriate HTTP error.
+ * Select the appropriate child Context to process this request, based on the specified request URI. If no matching
+ * Context can be found, return an appropriate HTTP error.
*
- * @param request Request to be processed
+ * @param request Request to be processed
* @param response Response to be produced
*
- * @exception IOException if an input/output error occurred
+ * @exception IOException if an input/output error occurred
* @exception ServletException if a servlet error occurred
*/
@Override
- public void invoke(Request request, Response response)
- throws IOException, ServletException {
+ public void invoke(Request request, Response response) throws IOException, ServletException {
// request without session
if (isRequestWithoutSession(request.getDecodedRequestURI())) {
@@ -100,8 +96,7 @@ public class PersistentValve extends ValveBase {
// Select the Context to be used for this Request
Context context = request.getContext();
if (context == null) {
- response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
- sm.getString("standardHost.noContext"));
+ response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, sm.getString("standardHost.noContext"));
return;
}
@@ -118,8 +113,7 @@ public class PersistentValve extends ValveBase {
container.getLogger().error("deserializeError");
}
if (session != null) {
- if (!session.isValid() ||
- isSessionStale(session, System.currentTimeMillis())) {
+ if (!session.isValid() || isSessionStale(session, System.currentTimeMillis())) {
if (container.getLogger().isDebugEnabled()) {
container.getLogger().debug("session swapped in is invalid or expired");
}
@@ -154,14 +148,14 @@ public class PersistentValve extends ValveBase {
hsess = null;
}
String newsessionId = null;
- if (hsess!=null) {
+ if (hsess != null) {
newsessionId = hsess.getIdInternal();
}
if (container.getLogger().isDebugEnabled()) {
container.getLogger().debug("newsessionId: " + newsessionId);
}
- if (newsessionId!=null) {
+ if (newsessionId != null) {
try {
bind(context);
@@ -184,15 +178,14 @@ public class PersistentValve extends ValveBase {
if (!stored) {
if (container.getLogger().isDebugEnabled()) {
container.getLogger()
- .debug("newsessionId store: " + store + " session: " + session + " valid: "
- + (session == null ? "N/A" : Boolean.toString(session.isValid()))
- + " stale: " + isSessionStale(session, System.currentTimeMillis()));
+ .debug("newsessionId store: " + store + " session: " + session + " valid: " +
+ (session == null ? "N/A" : Boolean.toString(session.isValid())) +
+ " stale: " + isSessionStale(session, System.currentTimeMillis()));
}
}
} else {
if (container.getLogger().isDebugEnabled()) {
- container.getLogger().debug("newsessionId Manager: " +
- manager);
+ container.getLogger().debug("newsessionId Manager: " + manager);
}
}
} finally {
@@ -204,12 +197,12 @@ public class PersistentValve extends ValveBase {
/**
- * Indicate whether the session has been idle for longer
- * than its expiration date as of the supplied time.
+ * Indicate whether the session has been idle for longer than its expiration date as of the supplied time. FIXME:
+ * Probably belongs in the Session class.
*
- * FIXME: Probably belongs in the Session class.
* @param session The session to check
* @param timeNow The current time to check for
+ *
* @return <code>true</code> if the session is past its expiration
*/
protected boolean isSessionStale(Session session, long timeNow) {
diff --git a/java/org/apache/catalina/valves/ProxyErrorReportValve.java b/java/org/apache/catalina/valves/ProxyErrorReportValve.java
index 0132c83a49..365aa7415a 100644
--- a/java/org/apache/catalina/valves/ProxyErrorReportValve.java
+++ b/java/org/apache/catalina/valves/ProxyErrorReportValve.java
@@ -89,8 +89,7 @@ public class ProxyErrorReportValve extends ErrorReportValve {
}
private String getRedirectUrl(Response response) {
- ResourceBundle resourceBundle = ResourceBundle.getBundle(this.getClass().getSimpleName(),
- response.getLocale());
+ ResourceBundle resourceBundle = ResourceBundle.getBundle(this.getClass().getSimpleName(), response.getLocale());
String redirectUrl = null;
try {
redirectUrl = resourceBundle.getString(Integer.toString(response.getStatus()));
@@ -115,7 +114,7 @@ public class ProxyErrorReportValve extends ErrorReportValve {
// Do nothing on a 1xx, 2xx and 3xx status
// Do nothing if anything has been written already
// Do nothing if the response hasn't been explicitly marked as in error
- // and that error has not been reported.
+ // and that error has not been reported.
if (statusCode < 400 || response.getContentWritten() > 0) {
return;
}
diff --git a/java/org/apache/catalina/valves/RemoteAddrValve.java b/java/org/apache/catalina/valves/RemoteAddrValve.java
index 39e86d86b0..d48fed2b27 100644
--- a/java/org/apache/catalina/valves/RemoteAddrValve.java
+++ b/java/org/apache/catalina/valves/RemoteAddrValve.java
@@ -28,9 +28,8 @@ import org.apache.juli.logging.LogFactory;
/**
- * Concrete implementation of <code>RequestFilterValve</code> that filters
- * based on the string representation of the remote client's IP address
- * optionally combined with the server connector port number.
+ * Concrete implementation of <code>RequestFilterValve</code> that filters based on the string representation of the
+ * remote client's IP address optionally combined with the server connector port number.
*
* @author Craig R. McClanahan
*/
@@ -50,14 +49,12 @@ public final class RemoteAddrValve extends RequestFilterValve {
property = request.getRequest().getRemoteAddr();
}
if (getAddConnectorPort()) {
- property = property + ";" +
- request.getConnector().getPortWithOffset();
+ property = property + ";" + request.getConnector().getPortWithOffset();
}
process(property, request, response);
}
-
@Override
protected Log getLog() {
return log;
diff --git a/java/org/apache/catalina/valves/RemoteCIDRValve.java b/java/org/apache/catalina/valves/RemoteCIDRValve.java
index ea6b1a2a8e..9cd998aefb 100644
--- a/java/org/apache/catalina/valves/RemoteCIDRValve.java
+++ b/java/org/apache/catalina/valves/RemoteCIDRValve.java
@@ -56,8 +56,7 @@ public final class RemoteCIDRValve extends RequestFilterValve {
/**
* 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 ']'
*/
@Override
public String getAllow() {
@@ -66,10 +65,10 @@ public final class RemoteCIDRValve extends RequestFilterValve {
/**
- * 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
*/
@Override
@@ -92,8 +91,7 @@ public final class RemoteCIDRValve extends RequestFilterValve {
/**
* Return a string representation of the {@link NetMask} list in #deny.
*
- * @return the #deny list as a string, without the leading '[' and trailing
- * ']'
+ * @return the #deny list as a string, without the leading '[' and trailing ']'
*/
@Override
public String getDeny() {
@@ -102,10 +100,10 @@ public final class RemoteCIDRValve extends RequestFilterValve {
/**
- * 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
*/
@Override
@@ -134,8 +132,7 @@ public final class RemoteCIDRValve extends RequestFilterValve {
property = request.getRequest().getRemoteAddr();
}
if (getAddConnectorPort()) {
- property = property + ";" +
- request.getConnector().getPortWithOffset();
+ property = property + ";" + request.getConnector().getPortWithOffset();
}
process(property, request, response);
}
@@ -221,11 +218,12 @@ public final class RemoteCIDRValve extends RequestFilterValve {
/**
- * 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)
*/
diff --git a/java/org/apache/catalina/valves/RemoteHostValve.java b/java/org/apache/catalina/valves/RemoteHostValve.java
index 2aec7e4882..58d28a1db8 100644
--- a/java/org/apache/catalina/valves/RemoteHostValve.java
+++ b/java/org/apache/catalina/valves/RemoteHostValve.java
@@ -26,9 +26,8 @@ import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
- * Concrete implementation of <code>RequestFilterValve</code> that filters
- * based on the remote client's host name optionally combined with the
- * server connector port number.
+ * Concrete implementation of <code>RequestFilterValve</code> that filters based on the remote client's host name
+ * optionally combined with the server connector port number.
*
* @author Craig R. McClanahan
*/
@@ -43,8 +42,7 @@ public final class RemoteHostValve extends RequestFilterValve {
public void invoke(Request request, Response response) throws IOException, ServletException {
String property;
if (getAddConnectorPort()) {
- property = request.getRequest().getRemoteHost() + ";" +
- request.getConnector().getPortWithOffset();
+ property = request.getRequest().getRemoteHost() + ";" + request.getConnector().getPortWithOffset();
} else {
property = request.getRequest().getRemoteHost();
}
diff --git a/java/org/apache/catalina/valves/RemoteIpValve.java b/java/org/apache/catalina/valves/RemoteIpValve.java
index eb6346eafc..42ece0d255 100644
--- a/java/org/apache/catalina/valves/RemoteIpValve.java
+++ b/java/org/apache/catalina/valves/RemoteIpValve.java
@@ -38,24 +38,24 @@ import org.apache.tomcat.util.http.parser.Host;
/**
* <p>
- * Tomcat port of <a href="https://httpd.apache.org/docs/trunk/mod/mod_remoteip.html">mod_remoteip</a>, this valve 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").
+ * Tomcat port of <a href="https://httpd.apache.org/docs/trunk/mod/mod_remoteip.html">mod_remoteip</a>, this valve
+ * 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 valve 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 valve 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 valve proceeds as follows:
* </p>
* <p>
- * If the incoming <code>request.getRemoteAddr()</code> matches the valve's list
- * of internal or trusted proxies:
+ * If the incoming <code>request.getRemoteAddr()</code> matches the valve'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>
@@ -63,12 +63,13 @@ import org.apache.tomcat.util.http.parser.Host;
* <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>
@@ -81,51 +82,47 @@ import org.apache.tomcat.util.http.parser.Host;
* </tr>
* <tr>
* <td>remoteIpHeader</td>
- * <td>Name of the Http Header read by this valve that holds the list of traversed IP addresses starting from the requesting client</td>
+ * <td>Name of the Http Header read by this valve 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 ::1 are allowed.</td>
* </tr>
* <tr>
* <td>proxiesHeader</td>
- * <td>Name of the http header created by this valve 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 valve to hold the list of proxies that have been processed in the
+ * incoming <code>remoteIpHeader</code></td>
* <td>proxiesHeader</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> </td>
* </tr>
* <tr>
* <td>protocolHeader</td>
- * <td>Name of the http header read by this valve that holds the flag that this request </td>
+ * <td>Name of the http header read by this valve 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>
@@ -137,14 +134,16 @@ import org.apache.tomcat.util.http.parser.Host;
* </tr>
* <tr>
* <td>httpServerPort</td>
- * <td>Value returned by {@link jakarta.servlet.ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates <code>http</code> protocol</td>
+ * <td>Value returned by {@link jakarta.servlet.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 jakarta.servlet.ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates <code>https</code> protocol</td>
+ * <td>Value returned by {@link jakarta.servlet.ServletRequest#getServerPort()} when the <code>protocolHeader</code>
+ * indicates <code>https</code> protocol</td>
* <td>N/A</td>
* <td>integer</td>
* <td>443</td>
@@ -154,12 +153,12 @@ import org.apache.tomcat.util.http.parser.Host;
* This Valve may be attached to any Container, depending on the granularity of the filtering you wish to perform.
* </p>
* <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 Tomcat 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>,
- * <code>RemoteIpValve</code> uses regular expression to configure <code>internalProxies</code> and <code>trustedProxies</code> in the same
- * fashion as {@link RequestFilterValve} does.
+ * <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 Tomcat 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>,
+ * <code>RemoteIpValve</code> uses regular expression to configure <code>internalProxies</code> and
+ * <code>trustedProxies</code> in the same fashion as {@link RequestFilterValve} does.
* </p>
* <hr>
* <p>
@@ -262,8 +261,9 @@ import org.apache.tomcat.util.http.parser.Host;
* </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>
@@ -304,9 +304,10 @@ import org.apache.tomcat.util.http.parser.Host;
* </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>
@@ -349,8 +350,8 @@ import org.apache.tomcat.util.http.parser.Host;
* <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>
*/
public class RemoteIpValve extends ValveBase {
@@ -367,12 +368,14 @@ public class RemoteIpValve extends ValveBase {
/**
* Convert a given comma delimited String into an array of String
+ *
* @param commaDelimitedStrings The string to convert
+ *
* @return array of String (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);
}
private String hostHeader = null;
@@ -396,15 +399,11 @@ public class RemoteIpValve extends ValveBase {
/**
* @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)
@@ -438,8 +437,7 @@ public class RemoteIpValve extends ValveBase {
/**
- * Default constructor that ensures {@link ValveBase#ValveBase(boolean)} is
- * called with <code>true</code>.
+ * Default constructor that ensures {@link ValveBase#ValveBase(boolean)} is called with <code>true</code>.
*/
public RemoteIpValve() {
// Async requests are supported with this valve
@@ -447,22 +445,20 @@ public class RemoteIpValve extends ValveBase {
}
/**
- * Obtain the name of the HTTP header used to override the value returned
- * by {@link Request#getServerName()} and (optionally depending on {link
- * {@link #isChangeLocalName()} {@link Request#getLocalName()}.
+ * Obtain the name of the HTTP header used to override the value returned by {@link Request#getServerName()} and
+ * (optionally depending on {link {@link #isChangeLocalName()} {@link Request#getLocalName()}.
*
- * @return The HTTP header name
+ * @return The HTTP header name
*/
public String getHostHeader() {
return hostHeader;
}
/**
- * Set the name of the HTTP header used to override the value returned
- * by {@link Request#getServerName()} and (optionally depending on {link
- * {@link #isChangeLocalName()} {@link Request#getLocalName()}.
+ * Set the name of the HTTP header used to override the value returned by {@link Request#getServerName()} and
+ * (optionally depending on {link {@link #isChangeLocalName()} {@link Request#getLocalName()}.
*
- * @param hostHeader The HTTP header name
+ * @param hostHeader The HTTP header name
*/
public void setHostHeader(String hostHeader) {
this.hostHeader = hostHeader;
@@ -485,22 +481,20 @@ public class RemoteIpValve extends ValveBase {
}
/**
- * Obtain the name of the HTTP header used to override the value returned
- * by {@link Request#getServerPort()} and (optionally depending on {link
- * {@link #isChangeLocalPort()} {@link Request#getLocalPort()}.
+ * Obtain the name of the HTTP header used to override the value returned by {@link Request#getServerPort()} and
+ * (optionally depending on {link {@link #isChangeLocalPort()} {@link Request#getLocalPort()}.
*
- * @return The HTTP header name
+ * @return The HTTP header name
*/
public String getPortHeader() {
return portHeader;
}
/**
- * Set the name of the HTTP header used to override the value returned
- * by {@link Request#getServerPort()} and (optionally depending on {link
- * {@link #isChangeLocalPort()} {@link Request#getLocalPort()}.
+ * Set the name of the HTTP header used to override the value returned by {@link Request#getServerPort()} and
+ * (optionally depending on {link {@link #isChangeLocalPort()} {@link Request#getLocalPort()}.
*
- * @param portHeader The HTTP header name
+ * @param portHeader The HTTP header name
*/
public void setPortHeader(String portHeader) {
this.portHeader = portHeader;
@@ -516,6 +510,7 @@ public class RemoteIpValve extends ValveBase {
/**
* @see #setInternalProxies(String)
+ *
* @return Regular expression that defines the internal proxies
*/
public String getInternalProxies() {
@@ -527,6 +522,7 @@ public class RemoteIpValve extends ValveBase {
/**
* @see #setProtocolHeader(String)
+ *
* @return the protocol header (e.g. "X-Forwarded-Proto")
*/
public String getProtocolHeader() {
@@ -535,6 +531,7 @@ public class RemoteIpValve extends ValveBase {
/**
* @see RemoteIpValve#setProtocolHeaderHttpsValue(String)
+ *
* @return the value of the protocol header for incoming https request (e.g. "https")
*/
public String getProtocolHeaderHttpsValue() {
@@ -543,6 +540,7 @@ public class RemoteIpValve extends ValveBase {
/**
* @see #setProxiesHeader(String)
+ *
* @return the proxies header name (e.g. "X-Forwarded-By")
*/
public String getProxiesHeader() {
@@ -551,6 +549,7 @@ public class RemoteIpValve extends ValveBase {
/**
* @see #setRemoteIpHeader(String)
+ *
* @return the remote IP header name (e.g. "X-Forwarded-For")
*/
public String getRemoteIpHeader() {
@@ -559,8 +558,8 @@ public class RemoteIpValve extends ValveBase {
/**
* @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;
@@ -568,6 +567,7 @@ public class RemoteIpValve extends ValveBase {
/**
* @see #setTrustedProxies(String)
+ *
* @return Regular expression that defines the trusted proxies
*/
public String getTrustedProxies() {
@@ -592,11 +592,9 @@ public class RemoteIpValve extends ValveBase {
final int originalLocalPort = request.getLocalPort();
final String originalProxiesHeader = request.getHeader(proxiesHeader);
final String originalRemoteIpHeader = request.getHeader(remoteIpHeader);
- boolean isInternal = internalProxies != null &&
- internalProxies.matcher(originalRemoteAddr).matches();
+ boolean isInternal = internalProxies != null && internalProxies.matcher(originalRemoteAddr).matches();
- if (isInternal || (trustedProxies != null &&
- trustedProxies.matcher(originalRemoteAddr).matches())) {
+ if (isInternal || (trustedProxies != null && trustedProxies.matcher(originalRemoteAddr).matches())) {
String remoteIp = null;
Deque<String> proxiesHeaderValue = new ArrayDeque<>();
StringBuilder concatRemoteIpHeaderValue = new StringBuilder();
@@ -618,10 +616,9 @@ public class RemoteIpValve extends ValveBase {
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
@@ -658,13 +655,15 @@ public class RemoteIpValve extends ValveBase {
request.getCoyoteRequest().getMimeHeaders().removeHeader(proxiesHeader);
} else {
String commaDelimitedListOfProxies = StringUtils.join(proxiesHeaderValue);
- request.getCoyoteRequest().getMimeHeaders().setValue(proxiesHeader).setString(commaDelimitedListOfProxies);
+ request.getCoyoteRequest().getMimeHeaders().setValue(proxiesHeader)
+ .setString(commaDelimitedListOfProxies);
}
if (newRemoteIpHeaderValue.size() == 0) {
request.getCoyoteRequest().getMimeHeaders().removeHeader(remoteIpHeader);
} else {
String commaDelimitedRemoteIpHeaderValue = StringUtils.join(newRemoteIpHeaderValue);
- request.getCoyoteRequest().getMimeHeaders().setValue(remoteIpHeader).setString(commaDelimitedRemoteIpHeaderValue);
+ request.getCoyoteRequest().getMimeHeaders().setValue(remoteIpHeader)
+ .setString(commaDelimitedRemoteIpHeaderValue);
}
}
@@ -708,34 +707,28 @@ public class RemoteIpValve extends ValveBase {
request.setAttribute(Globals.REQUEST_FORWARDED_ATTRIBUTE, Boolean.TRUE);
if (log.isDebugEnabled()) {
- log.debug("Incoming request " + request.getRequestURI() + " with originalRemoteAddr [" + originalRemoteAddr +
- "], originalRemoteHost=[" + originalRemoteHost + "], originalSecure=[" + originalSecure +
- "], originalScheme=[" + originalScheme + "], originalServerName=[" + originalServerName +
- "], originalServerPort=[" + originalServerPort +
- "] will be seen as newRemoteAddr=[" + request.getRemoteAddr() +
- "], newRemoteHost=[" + request.getRemoteHost() + "], newSecure=[" + request.isSecure() +
- "], newScheme=[" + request.getScheme() + "], newServerName=[" + request.getServerName() +
- "], newServerPort=[" + request.getServerPort() + "]");
+ log.debug("Incoming request " + request.getRequestURI() + " with originalRemoteAddr [" +
+ originalRemoteAddr + "], originalRemoteHost=[" + originalRemoteHost + "], originalSecure=[" +
+ originalSecure + "], originalScheme=[" + originalScheme + "], originalServerName=[" +
+ originalServerName + "], originalServerPort=[" + originalServerPort +
+ "] will be seen as newRemoteAddr=[" + request.getRemoteAddr() + "], newRemoteHost=[" +
+ request.getRemoteHost() + "], newSecure=[" + request.isSecure() + "], newScheme=[" +
+ request.getScheme() + "], newServerName=[" + request.getServerName() + "], newServerPort=[" +
+ request.getServerPort() + "]");
}
} else {
if (log.isDebugEnabled()) {
- log.debug("Skip RemoteIpValve for request " + request.getRequestURI() + " with originalRemoteAddr '"
- + request.getRemoteAddr() + "'");
+ log.debug("Skip RemoteIpValve for request " + request.getRequestURI() + " with originalRemoteAddr '" +
+ request.getRemoteAddr() + "'");
}
}
if (requestAttributesEnabled) {
- request.setAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE,
- request.getRemoteAddr());
- request.setAttribute(Globals.REMOTE_ADDR_ATTRIBUTE,
- request.getRemoteAddr());
- request.setAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE,
- request.getRemoteHost());
- request.setAttribute(AccessLog.PROTOCOL_ATTRIBUTE,
- request.getProtocol());
- request.setAttribute(AccessLog.SERVER_NAME_ATTRIBUTE,
- request.getServerName());
- request.setAttribute(AccessLog.SERVER_PORT_ATTRIBUTE,
- Integer.valueOf(request.getServerPort()));
+ request.setAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE, request.getRemoteAddr());
+ request.setAttribute(Globals.REMOTE_ADDR_ATTRIBUTE, request.getRemoteAddr());
+ request.setAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE, request.getRemoteHost());
+ request.setAttribute(AccessLog.PROTOCOL_ATTRIBUTE, request.getProtocol());
+ request.setAttribute(AccessLog.SERVER_NAME_ATTRIBUTE, request.getServerName());
+ request.setAttribute(AccessLog.SERVER_PORT_ATTRIBUTE, Integer.valueOf(request.getServerPort()));
}
try {
getNext().invoke(request, response);
@@ -769,8 +762,7 @@ public class RemoteIpValve extends ValveBase {
}
/*
- * 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(",")) {
@@ -797,9 +789,7 @@ public class RemoteIpValve extends ValveBase {
port = Integer.parseInt(portHeaderValue);
} catch (NumberFormatException nfe) {
if (log.isDebugEnabled()) {
- log.debug(sm.getString(
- "remoteIpValve.invalidPortHeader",
- portHeaderValue, portHeader), nfe);
+ log.debug(sm.getString("remoteIpValve.invalidPortHeader", portHeaderValue, portHeader), nfe);
}
}
}
@@ -817,6 +807,7 @@ public class RemoteIpValve extends ValveBase {
* <p>
* Default value : 80
* </p>
+ *
* @param httpServerPort The server port
*/
public void setHttpServerPort(int httpServerPort) {
@@ -830,6 +821,7 @@ public class RemoteIpValve extends ValveBase {
* <p>
* Default value : 443
* </p>
+ *
* @param httpsServerPort The server port
*/
public void setHttpsServerPort(int httpsServerPort) {
@@ -841,8 +833,10 @@ public class RemoteIpValve extends ValveBase {
* 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 proxy regular expression
*/
public void setInternalProxies(String internalProxies) {
@@ -855,12 +849,13 @@ public class RemoteIpValve extends ValveBase {
/**
* <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) {
@@ -874,6 +869,7 @@ public class RemoteIpValve extends ValveBase {
* <p>
* Default value : <code>https</code>
* </p>
+ *
* @param protocolHeaderHttpsValue The header name
*/
public void setProtocolHeaderHttpsValue(String protocolHeaderHttpsValue) {
@@ -882,9 +878,10 @@ public class RemoteIpValve extends ValveBase {
/**
* <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.
@@ -895,6 +892,7 @@ public class RemoteIpValve extends ValveBase {
* <p>
* Default value : <code>X-Forwarded-By</code>
* </p>
+ *
* @param proxiesHeader The header name
*/
public void setProxiesHeader(String proxiesHeader) {
@@ -919,12 +917,9 @@ public class RemoteIpValve extends ValveBase {
}
/**
- * Should this valve set request attributes for IP address, Hostname,
- * protocol and port used for the request? This are typically used in
- * conjunction with the {@link AccessLog} which will otherwise log the
- * original values. Default is <code>true</code>.
- *
- * The attributes set are:
+ * Should this valve set request attributes for IP address, Hostname, protocol and port used for the request? This
+ * are typically used in conjunction with the {@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>
@@ -933,9 +928,8 @@ public class RemoteIpValve extends ValveBase {
* <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;
@@ -943,12 +937,12 @@ public class RemoteIpValve extends ValveBase {
/**
* <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 regular expression
*/
public void setTrustedProxies(String trustedProxies) {
diff --git a/java/org/apache/catalina/valves/RequestFilterValve.java b/java/org/apache/catalina/valves/RequestFilterValve.java
index 9847b8cd42..5766de0d50 100644
--- a/java/org/apache/catalina/valves/RequestFilterValve.java
+++ b/java/org/apache/catalina/valves/RequestFilterValve.java
@@ -30,43 +30,35 @@ import org.apache.catalina.connector.Response;
import org.apache.juli.logging.Log;
/**
- * Implementation of a Valve 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 Valve.
+ * Implementation of a Valve 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 Valve.
* <p>
- * This valve 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 valve 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 each such expression. If a match is found, this request will be
- * allowed to pass through to the next Valve 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 each such expression. If a match is
+ * found, this request will be allowed to pass through to the next Valve 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>
* <p>
- * As an option the valve can generate an invalid <code>authenticate</code>
- * header instead of denying the request. This can be combined with the
- * context attribute <code>preemptiveAuthentication="true"</code> and an
- * authenticator to force authentication instead of denial.
+ * As an option the valve can generate an invalid <code>authenticate</code> header instead of denying the request. This
+ * can be combined with the context attribute <code>preemptiveAuthentication="true"</code> and an authenticator to force
+ * authentication instead of denial.
* <p>
- * This Valve may be attached to any Container, depending on the granularity
- * of the filtering you wish to perform.
+ * This Valve may be attached to any Container, depending on the granularity of the filtering you wish to perform.
*
* @author Craig R. McClanahan
*/
public abstract class RequestFilterValve extends ValveBase {
- //------------------------------------------------------ Constructor
+ // ------------------------------------------------------ Constructor
public RequestFilterValve() {
super(true);
}
@@ -81,17 +73,14 @@ public abstract class RequestFilterValve extends ValveBase {
/**
- * The current allow configuration value that may or may not compile into a
- * valid {@link Pattern}.
+ * The current allow configuration value that may or may not compile into a valid {@link Pattern}.
*/
protected volatile String allowValue = null;
/**
- * Helper variable to catch configuration errors.
- * It is <code>true</code> by default, but becomes <code>false</code>
- * if there was an attempt to assign an invalid value to the
- * <code>allow</code> pattern.
+ * Helper variable to catch configuration errors. It is <code>true</code> by default, but becomes <code>false</code>
+ * if there was an attempt to assign an invalid value to the <code>allow</code> pattern.
*/
protected volatile boolean allowValid = true;
@@ -103,45 +92,39 @@ public abstract class RequestFilterValve extends ValveBase {
/**
- * The current deny configuration value that may or may not compile into a
- * valid {@link Pattern}.
+ * The current deny configuration value that may or may not compile into a valid {@link Pattern}.
*/
protected volatile String denyValue = null;
/**
- * Helper variable to catch configuration errors.
- * It is <code>true</code> by default, but becomes <code>false</code>
- * if there was an attempt to assign an invalid value to the
- * <code>deny</code> pattern.
+ * Helper variable to catch configuration errors. It is <code>true</code> by default, but becomes <code>false</code>
+ * if there was an attempt to assign an invalid value to the <code>deny</code> pattern.
*/
protected volatile boolean denyValid = true;
/**
- * 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;
/**
- * <p>If <code>invalidAuthenticationWhenDeny</code> is true
- * and the context has <code>preemptiveAuthentication</code>
- * set, set an invalid authorization header to trigger basic auth
- * instead of denying the request..
+ * <p>
+ * If <code>invalidAuthenticationWhenDeny</code> is true and the context has <code>preemptiveAuthentication</code>
+ * set, set an invalid authorization header to trigger basic auth instead of denying the request..
*/
private boolean invalidAuthenticationWhenDeny = false;
/**
- * Flag deciding whether we add the server connector port to the property
- * compared in the filtering method. The port will be appended
- * using a ";" as a separator.
+ * Flag deciding whether we add the server connector port to the property compared in the filtering method. The port
+ * will be appended using a ";" as a separator.
*/
private volatile boolean addConnectorPort = false;
/**
- * Flag deciding whether we use the connection peer address
- * or the remote address. This makes a dfifference when
+ * Flag deciding whether we use the connection peer address or the remote address. This makes a dfifference when
* using AJP or the RemoteIpValve.
*/
private volatile boolean usePeerAddress = false;
@@ -150,8 +133,9 @@ public abstract class RequestFilterValve extends ValveBase {
/**
- * Return the regular expression used to test for allowed requests for this
- * Valve, if any; otherwise, return <code>null</code>.
+ * Return the regular expression used to test for allowed requests for this Valve, if any; otherwise, return
+ * <code>null</code>.
+ *
* @return the regular expression
*/
public String getAllow() {
@@ -160,8 +144,7 @@ public abstract class RequestFilterValve extends ValveBase {
/**
- * Set the regular expression used to test for allowed requests for this
- * Valve, if any.
+ * Set the regular expression used to test for allowed requests for this Valve, if any.
*
* @param allow The new allow expression
*/
@@ -184,8 +167,9 @@ public abstract class RequestFilterValve extends ValveBase {
/**
- * Return the regular expression used to test for denied requests for this
- * Valve, if any; otherwise, return <code>null</code>.
+ * Return the regular expression used to test for denied requests for this Valve, if any; otherwise, return
+ * <code>null</code>.
+ *
* @return the regular expression
*/
public String getDeny() {
@@ -194,8 +178,7 @@ public abstract class RequestFilterValve extends ValveBase {
/**
- * Set the regular expression used to test for denied requests for this
- * Valve, if any.
+ * Set the regular expression used to test for denied requests for this Valve, if any.
*
* @param deny The new deny expression
*/
@@ -218,9 +201,9 @@ public abstract class RequestFilterValve extends ValveBase {
/**
- * Returns {@code false} if the last change to the {@code allow} pattern did
- * not apply successfully. E.g. if the pattern is syntactically
- * invalid.
+ * Returns {@code false} if the last change to the {@code allow} pattern did not apply successfully. E.g. if the
+ * pattern is syntactically invalid.
+ *
* @return <code>false</code> if the current pattern is invalid
*/
public final boolean isAllowValid() {
@@ -229,9 +212,9 @@ public abstract class RequestFilterValve extends ValveBase {
/**
- * Returns {@code false} if the last change to the {@code deny} pattern did
- * not apply successfully. E.g. if the pattern is syntactically
- * invalid.
+ * Returns {@code false} if the last change to the {@code deny} pattern did not apply successfully. E.g. if the
+ * pattern is syntactically invalid.
+ *
* @return <code>false</code> if the current pattern is invalid
*/
public final boolean isDenyValid() {
@@ -249,6 +232,7 @@ public abstract class RequestFilterValve extends ValveBase {
/**
* Set response status code that is used to reject denied request.
+ *
* @param denyStatus The status code
*/
public void setDenyStatus(int denyStatus) {
@@ -266,6 +250,7 @@ public abstract class RequestFilterValve extends ValveBase {
/**
* Set invalidAuthenticationWhenDeny property.
+ *
* @param value <code>true</code> to handle a deny by setting an invalid auth header
*/
public void setInvalidAuthenticationWhenDeny(boolean value) {
@@ -274,9 +259,9 @@ public abstract class RequestFilterValve extends ValveBase {
/**
- * Get the flag deciding whether we add the server connector port to the
- * property compared in the filtering method. The port will be appended
- * using a ";" as a separator.
+ * Get the flag deciding whether we add the server connector port to the property compared in the filtering method.
+ * The port will be appended using a ";" as a separator.
+ *
* @return <code>true</code> to add the connector port
*/
public boolean getAddConnectorPort() {
@@ -285,9 +270,8 @@ public abstract class RequestFilterValve extends ValveBase {
/**
- * Set the flag deciding whether we add the server connector port to the
- * property compared in the filtering method. The port will be appended
- * using a ";" as a separator.
+ * Set the flag deciding whether we add the server connector port to the property compared in the filtering method.
+ * The port will be appended using a ";" as a separator.
*
* @param addConnectorPort The new flag
*/
@@ -297,9 +281,9 @@ public abstract class RequestFilterValve extends ValveBase {
/**
- * Get the flag deciding whether we use the connection peer address
- * or the remote address. This makes a dfifference when
- * using AJP or the RemoteIpValve.
+ * Get the flag deciding whether we use the connection peer address or the remote address. This makes a dfifference
+ * when using AJP or the RemoteIpValve.
+ *
* @return <code>true</code> if we use the connection peer address
*/
public boolean getUsePeerAddress() {
@@ -308,9 +292,8 @@ public abstract class RequestFilterValve extends ValveBase {
/**
- * Set the flag deciding whether we use the connection peer address
- * or the remote address. This makes a dfifference when
- * using AJP or the RemoteIpValve.
+ * Set the flag deciding whether we use the connection peer address or the remote address. This makes a dfifference
+ * when using AJP or the RemoteIpValve.
*
* @param usePeerAddress The new flag
*/
@@ -321,20 +304,18 @@ public abstract class RequestFilterValve extends ValveBase {
// --------------------------------------------------------- Public Methods
/**
- * 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
*
- * @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 invoke(Request request, Response response)
- throws IOException, ServletException;
+ public abstract void invoke(Request request, Response response) throws IOException, ServletException;
// ------------------------------------------------------ Protected Methods
@@ -344,8 +325,7 @@ public abstract class RequestFilterValve extends ValveBase {
protected void initInternal() throws LifecycleException {
super.initInternal();
if (!allowValid || !denyValid) {
- throw new LifecycleException(
- sm.getString("requestFilterValve.configInvalid"));
+ throw new LifecycleException(sm.getString("requestFilterValve.configInvalid"));
}
}
@@ -353,26 +333,23 @@ public abstract class RequestFilterValve extends ValveBase {
@Override
protected synchronized void startInternal() throws LifecycleException {
if (!allowValid || !denyValid) {
- throw new LifecycleException(
- sm.getString("requestFilterValve.configInvalid"));
+ throw new LifecycleException(sm.getString("requestFilterValve.configInvalid"));
}
super.startInternal();
}
/**
- * Perform the filtering that has been configured for this Valve, matching
- * against the specified request property.
+ * Perform the filtering that has been configured for this Valve, 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
*
- * @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, Request request, Response response)
- throws IOException, ServletException {
+ protected void process(String property, Request request, Response response) throws IOException, ServletException {
if (isAllowed(property)) {
getNext().invoke(request, response);
@@ -380,8 +357,7 @@ public abstract class RequestFilterValve extends ValveBase {
}
if (getLog().isDebugEnabled()) {
- getLog().debug(sm.getString("requestFilterValve.deny",
- request.getRequestURI(), property));
+ getLog().debug(sm.getString("requestFilterValve.deny", request.getRequestURI(), property));
}
// Deny this request
@@ -394,17 +370,17 @@ public abstract class RequestFilterValve extends ValveBase {
/**
* Reject the request that was denied by this valve.
- * <p>If <code>invalidAuthenticationWhenDeny</code> is true
- * and the context has <code>preemptiveAuthentication</code>
+ * <p>
+ * If <code>invalidAuthenticationWhenDeny</code> is true and the context has <code>preemptiveAuthentication</code>
* set, set an invalid authorization header to trigger basic auth.
*
- * @param request The servlet request to be processed
+ * @param request The servlet request to be processed
* @param response The servlet response to be processed
- * @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 denyRequest(Request request, Response response)
- throws IOException, ServletException {
+ protected void denyRequest(Request request, Response response) throws IOException, ServletException {
if (invalidAuthenticationWhenDeny) {
Context context = request.getContext();
if (context != null && context.getPreemptiveAuthentication()) {
@@ -420,12 +396,12 @@ public abstract class RequestFilterValve extends ValveBase {
/**
- * Perform the test implemented by this Valve, matching against the
- * specified request property value. This method is public so that it can be
- * called through JMX, e.g. to test whether certain IP address is allowed or
- * denied by the valve configuration.
+ * Perform the test implemented by this Valve, matching against the specified request property value. This method is
+ * public so that it can be called through JMX, e.g. to test whether certain IP address is allowed or denied by the
+ * valve configuration.
*
* @param property The request property value on which to filter
+ *
* @return <code>true</code> if the request is allowed
*/
public boolean isAllowed(String property) {
diff --git a/java/org/apache/catalina/valves/SSLValve.java b/java/org/apache/catalina/valves/SSLValve.java
index 05b60f7cb6..2daeb5e0aa 100644
--- a/java/org/apache/catalina/valves/SSLValve.java
+++ b/java/org/apache/catalina/valves/SSLValve.java
@@ -33,17 +33,16 @@ import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.buf.UDecoder;
/**
- * When using mod_proxy_http, the client SSL information is not included in the
- * protocol (unlike mod_jk and mod_proxy_ajp). To make the client SSL
- * information available to Tomcat, some additional configuration is required.
- * In httpd, mod_headers is used to add the SSL information as HTTP headers. In
- * Tomcat, this valve is used to read the information from the HTTP headers and
- * insert it into the request.<p>
- *
- * <b>Note: Ensure that the headers are always set by httpd for all requests to
- * prevent a client spoofing SSL information by sending fake headers. </b><p>
- *
+ * When using mod_proxy_http, the client SSL information is not included in the protocol (unlike mod_jk and
+ * mod_proxy_ajp). To make the client SSL information available to Tomcat, some additional configuration is required. In
+ * httpd, mod_headers is used to add the SSL information as HTTP headers. In Tomcat, this valve is used to read the
+ * information from the HTTP headers and insert it into the request.
+ * <p>
+ * <b>Note: Ensure that the headers are always set by httpd for all requests to prevent a client spoofing SSL
+ * information by sending fake headers. </b>
+ * <p>
* In httpd.conf add the following:
+ *
* <pre>
* <IfModule ssl_module>
* RequestHeader set SSL_CLIENT_CERT "%{SSL_CLIENT_CERT}s"
@@ -54,6 +53,7 @@ import org.apache.tomcat.util.buf.UDecoder;
* </pre>
*
* In server.xml, configure this valve under the Engine element in server.xml:
+ *
* <pre>
* <Engine ...>
* <Valve className="org.apache.catalina.valves.SSLValve" />
@@ -71,7 +71,7 @@ public class SSLValve extends ValveBase {
private String sslSessionIdHeader = "ssl_session_id";
private String sslCipherUserKeySizeHeader = "ssl_cipher_usekeysize";
- //------------------------------------------------------ Constructor
+ // ------------------------------------------------------ Constructor
public SSLValve() {
super(true);
}
@@ -134,20 +134,15 @@ public class SSLValve extends ValveBase {
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
/*
- * Known behaviours of reverse proxies that are handled by the
- * processing below:
- * - mod_header converts the '\n' into ' '
- * - nginx converts the '\n' into multiple ' '
- * - nginx ssl_client_escaped_cert uses "uri component" escaping,
- * keeping only ALPHA, DIGIT, "-", ".", "_", "~"
+ * Known behaviours of reverse proxies that are handled by the processing below: - mod_header converts the '\n'
+ * into ' ' - nginx converts the '\n' into multiple ' ' - nginx ssl_client_escaped_cert uses "uri component"
+ * escaping, keeping only ALPHA, DIGIT, "-", ".", "_", "~"
*
- * The code assumes that the trimmed header value starts with
- * '-----BEGIN CERTIFICATE-----' and ends with
+ * The code assumes that the trimmed header value starts with '-----BEGIN CERTIFICATE-----' and ends with
* '-----END CERTIFICATE-----'.
*
- * Note: As long as the BEGIN marker and the rest of the content are on
- * separate lines, the CertificateFactory is tolerant of any
- * additional whitespace.
+ * Note: As long as the BEGIN marker and the rest of the content are on separate lines, the CertificateFactory
+ * is tolerant of any additional whitespace.
*/
String headerValue;
String headerEscapedValue = mygetHeader(request, sslClientEscapedCertHeader);
@@ -162,11 +157,9 @@ public class SSLValve extends ValveBase {
String body = headerValue.substring(27);
String header = "-----BEGIN CERTIFICATE-----\n";
String strcerts = header.concat(body);
- ByteArrayInputStream bais = new ByteArrayInputStream(
- strcerts.getBytes(StandardCharsets.ISO_8859_1));
+ ByteArrayInputStream bais = new ByteArrayInputStream(strcerts.getBytes(StandardCharsets.ISO_8859_1));
X509Certificate jsseCerts[] = null;
- String providerName = (String) request.getConnector().getProperty(
- "clientCertProvider");
+ String providerName = (String) request.getConnector().getProperty("clientCertProvider");
try {
CertificateFactory cf;
if (providerName == null) {
@@ -180,8 +173,7 @@ public class SSLValve extends ValveBase {
} catch (java.security.cert.CertificateException e) {
log.warn(sm.getString("sslValve.certError", strcerts), e);
} catch (NoSuchProviderException e) {
- log.error(sm.getString(
- "sslValve.invalidProvider", providerName), e);
+ log.error(sm.getString("sslValve.invalidProvider", providerName), e);
}
request.setAttribute(Globals.CERTIFICATES_ATTR, jsseCerts);
}
diff --git a/java/org/apache/catalina/valves/SemaphoreValve.java b/java/org/apache/catalina/valves/SemaphoreValve.java
index 2f2e6f2413..ebb6bd42d1 100644
--- a/java/org/apache/catalina/valves/SemaphoreValve.java
+++ b/java/org/apache/catalina/valves/SemaphoreValve.java
@@ -28,18 +28,20 @@ import org.apache.catalina.connector.Response;
/**
- * <p>Implementation of a Valve that limits concurrency.</p>
- *
- * <p>This Valve may be attached to any Container, depending on the granularity
- * of the concurrency control you wish to perform. Note that internally, some
- * async requests may require multiple serial requests to complete what - to the
- * user - appears as a single request.</p>
+ * <p>
+ * Implementation of a Valve that limits concurrency.
+ * </p>
+ * <p>
+ * This Valve may be attached to any Container, depending on the granularity of the concurrency control you wish to
+ * perform. Note that internally, some async requests may require multiple serial requests to complete what - to the
+ * user - appears as a single request.
+ * </p>
*
* @author Remy Maucherat
*/
public class SemaphoreValve extends ValveBase {
- //------------------------------------------------------ Constructor
+ // ------------------------------------------------------ Constructor
public SemaphoreValve() {
super(true);
}
@@ -60,40 +62,64 @@ public class SemaphoreValve extends ValveBase {
* Concurrency level of the semaphore.
*/
protected int concurrency = 10;
- public int getConcurrency() { return concurrency; }
- public void setConcurrency(int concurrency) { this.concurrency = concurrency; }
+
+ public int getConcurrency() {
+ return concurrency;
+ }
+
+ public void setConcurrency(int concurrency) {
+ this.concurrency = concurrency;
+ }
/**
* Fairness of the semaphore.
*/
protected boolean fairness = false;
- public boolean getFairness() { return fairness; }
- public void setFairness(boolean fairness) { this.fairness = fairness; }
+
+ public boolean getFairness() {
+ return fairness;
+ }
+
+ public void setFairness(boolean fairness) {
+ this.fairness = fairness;
+ }
/**
* Block until a permit is available.
*/
protected boolean block = true;
- public boolean getBlock() { return block; }
- public void setBlock(boolean block) { this.block = block; }
+
+ public boolean getBlock() {
+ return block;
+ }
+
+ public void setBlock(boolean block) {
+ this.block = block;
+ }
/**
* Block interruptibly until a permit is available.
*/
protected boolean interruptible = false;
- public boolean getInterruptible() { return interruptible; }
- public void setInterruptible(boolean interruptible) { this.interruptible = interruptible; }
+
+ public boolean getInterruptible() {
+ return interruptible;
+ }
+
+ public void setInterruptible(boolean interruptible) {
+ this.interruptible = interruptible;
+ }
/**
- * Start this component and implement the requirements
- * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
+ * 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 {
@@ -105,11 +131,11 @@ public class SemaphoreValve extends ValveBase {
/**
- * Stop this component and implement the requirements
- * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
+ * 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 {
@@ -125,15 +151,14 @@ public class SemaphoreValve extends ValveBase {
/**
* Do concurrency control on the request using the semaphore.
*
- * @param request The servlet request to be processed
+ * @param request The servlet request to be processed
* @param response The servlet response to be created
*
- * @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 {
if (controlConcurrency(request, response)) {
boolean shouldRelease = true;
@@ -172,10 +197,11 @@ public class SemaphoreValve extends ValveBase {
/**
* Subclass friendly method to add conditions.
- * @param request The Servlet request
+ *
+ * @param request The Servlet request
* @param response The Servlet response
- * @return <code>true</code> if the concurrency control should occur
- * on this request
+ *
+ * @return <code>true</code> if the concurrency control should occur on this request
*/
public boolean controlConcurrency(Request request, Response response) {
return true;
@@ -183,15 +209,15 @@ public class SemaphoreValve extends ValveBase {
/**
- * Subclass friendly method to add error handling when a permit isn't
- * granted.
- * @param request The Servlet request
+ * Subclass friendly method to add error handling when a permit isn't granted.
+ *
+ * @param request The Servlet request
* @param response The Servlet response
- * @throws IOException Error writing output
+ *
+ * @throws IOException Error writing output
* @throws ServletException Other error
*/
- public void permitDenied(Request request, Response response)
- throws IOException, ServletException {
+ public void permitDenied(Request request, Response response) throws IOException, ServletException {
// NO-OP by default
}
diff --git a/java/org/apache/catalina/valves/StuckThreadDetectionValve.java b/java/org/apache/catalina/valves/StuckThreadDetectionValve.java
index 9c3ca82510..584379dfa7 100644
--- a/java/org/apache/catalina/valves/StuckThreadDetectionValve.java
+++ b/java/org/apache/catalina/valves/StuckThreadDetectionValve.java
@@ -38,8 +38,8 @@ import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.res.StringManager;
/**
- * This valve allows to detect requests that take a long time to process, which
- * might indicate that the thread that is processing it is stuck.
+ * This valve allows to detect requests that take a long time to process, which might indicate that the thread that is
+ * processing it is stuck.
*/
public class StuckThreadDetectionValve extends ValveBase {
@@ -51,8 +51,7 @@ public class StuckThreadDetectionValve extends ValveBase {
/**
* The string manager for this package.
*/
- private static final StringManager sm =
- StringManager.getManager(Constants.Package);
+ private static final StringManager sm = StringManager.getManager(Constants.Package);
/**
* Keeps count of the number of stuck threads detected
@@ -75,22 +74,19 @@ public class StuckThreadDetectionValve extends ValveBase {
private int interruptThreadThreshold;
/**
- * The only references we keep to actual running Thread objects are in
- * this Map (which is automatically cleaned in invoke()s finally clause).
- * That way, Threads can be GC'ed, even though the Valve still thinks they
- * are stuck (caused by a long monitor interval)
+ * The only references we keep to actual running Thread objects are in this Map (which is automatically cleaned in
+ * invoke()s finally clause). That way, Threads can be GC'ed, even though the Valve still thinks they are stuck
+ * (caused by a long monitor interval)
*/
private final Map<Long, MonitoredThread> activeThreads = new ConcurrentHashMap<>();
- private final Queue<CompletedStuckThread> completedStuckThreadsQueue =
- new ConcurrentLinkedQueue<>();
+ private final Queue<CompletedStuckThread> completedStuckThreadsQueue = new ConcurrentLinkedQueue<>();
/**
- * Specifies the threshold (in seconds) used when checking for stuck threads.
- * If <=0, the detection is disabled. The default is 600 seconds.
+ * Specifies the threshold (in seconds) used when checking for stuck threads. If <=0, the detection is disabled.
+ * The default is 600 seconds.
*
- * @param threshold
- * The new threshold in seconds
+ * @param threshold The new threshold in seconds
*/
public void setThreshold(int threshold) {
this.threshold = threshold;
@@ -98,6 +94,7 @@ public class StuckThreadDetectionValve extends ValveBase {
/**
* @see #setThreshold(int)
+ *
* @return The current threshold in seconds
*/
public int getThreshold() {
@@ -110,12 +107,10 @@ public class StuckThreadDetectionValve extends ValveBase {
}
/**
- * Specifies the threshold (in seconds) before stuck threads are interrupted.
- * If <=0, the interruption is disabled. The default is -1.
- * If >=0, the value must actually be >= threshold.
+ * Specifies the threshold (in seconds) before stuck threads are interrupted. If <=0, the interruption is
+ * disabled. The default is -1. If >=0, the value must actually be >= threshold.
*
- * @param interruptThreadThreshold
- * The new thread interruption threshold in seconds
+ * @param interruptThreadThreshold The new thread interruption threshold in seconds
*/
public void setInterruptThreadThreshold(int interruptThreadThreshold) {
this.interruptThreadThreshold = interruptThreadThreshold;
@@ -134,25 +129,16 @@ public class StuckThreadDetectionValve extends ValveBase {
super.initInternal();
if (log.isDebugEnabled()) {
- log.debug("Monitoring stuck threads with threshold = "
- + threshold
- + " sec");
+ log.debug("Monitoring stuck threads with threshold = " + threshold + " sec");
}
}
- private void notifyStuckThreadDetected(MonitoredThread monitoredThread,
- long activeTime, int numStuckThreads) {
+ private void notifyStuckThreadDetected(MonitoredThread monitoredThread, long activeTime, int numStuckThreads) {
if (log.isWarnEnabled()) {
- String msg = sm.getString(
- "stuckThreadDetectionValve.notifyStuckThreadDetected",
- monitoredThread.getThread().getName(),
- Long.valueOf(activeTime),
- monitoredThread.getStartTime(),
- Integer.valueOf(numStuckThreads),
- monitoredThread.getRequestUri(),
- Integer.valueOf(threshold),
- String.valueOf(monitoredThread.getThread().getId())
- );
+ String msg = sm.getString("stuckThreadDetectionValve.notifyStuckThreadDetected",
+ monitoredThread.getThread().getName(), Long.valueOf(activeTime), monitoredThread.getStartTime(),
+ Integer.valueOf(numStuckThreads), monitoredThread.getRequestUri(), Integer.valueOf(threshold),
+ String.valueOf(monitoredThread.getThread().getId()));
// msg += "\n" + getStackTraceAsString(trace);
Throwable th = new Throwable();
th.setStackTrace(monitoredThread.getThread().getStackTrace());
@@ -160,15 +146,11 @@ public class StuckThreadDetectionValve extends ValveBase {
}
}
- private void notifyStuckThreadCompleted(CompletedStuckThread thread,
- int numStuckThreads) {
+ private void notifyStuckThreadCompleted(CompletedStuckThread thread, int numStuckThreads) {
if (log.isWarnEnabled()) {
- String msg = sm.getString(
- "stuckThreadDetectionValve.notifyStuckThreadCompleted",
- thread.getName(),
- Long.valueOf(thread.getTotalActiveTime()),
- Integer.valueOf(numStuckThreads),
- String.valueOf(thread.getId()));
+ String msg = sm.getString("stuckThreadDetectionValve.notifyStuckThreadCompleted", thread.getName(),
+ Long.valueOf(thread.getTotalActiveTime()), Integer.valueOf(numStuckThreads),
+ String.valueOf(thread.getId()));
// Since the "stuck thread notification" is warn, this should also
// be warn
log.warn(msg);
@@ -179,8 +161,7 @@ public class StuckThreadDetectionValve extends ValveBase {
* {@inheritDoc}
*/
@Override
- public void invoke(Request request, Response response)
- throws IOException, ServletException {
+ public void invoke(Request request, Response response) throws IOException, ServletException {
if (threshold <= 0) {
// short-circuit if not monitoring stuck threads
@@ -194,12 +175,12 @@ public class StuckThreadDetectionValve extends ValveBase {
Long key = Long.valueOf(Thread.currentThread().getId());
StringBuffer requestUrl = request.getRequestURL();
- if(request.getQueryString()!=null) {
+ if (request.getQueryString() != null) {
requestUrl.append('?');
requestUrl.append(request.getQueryString());
}
- MonitoredThread monitoredThread = new MonitoredThread(Thread.currentThread(),
- requestUrl.toString(), interruptThreadThreshold > 0);
+ MonitoredThread monitoredThread = new MonitoredThread(Thread.currentThread(), requestUrl.toString(),
+ interruptThreadThreshold > 0);
activeThreads.put(key, monitoredThread);
try {
@@ -207,12 +188,11 @@ public class StuckThreadDetectionValve extends ValveBase {
} finally {
activeThreads.remove(key);
if (monitoredThread.markAsDone() == MonitoredThreadState.STUCK) {
- if(monitoredThread.wasInterrupted()) {
+ if (monitoredThread.wasInterrupted()) {
interruptedThreadsCount.incrementAndGet();
}
completedStuckThreadsQueue.add(
- new CompletedStuckThread(monitoredThread.getThread(),
- monitoredThread.getActiveTimeInMillis()));
+ new CompletedStuckThread(monitoredThread.getThread(), monitoredThread.getActiveTimeInMillis()));
}
}
}
@@ -232,13 +212,13 @@ public class StuckThreadDetectionValve extends ValveBase {
int numStuckThreads = stuckCount.incrementAndGet();
notifyStuckThreadDetected(monitoredThread, activeTime, numStuckThreads);
}
- if(interruptThreadThreshold > 0 && activeTime >= interruptThreadThreshold*1000L) {
+ if (interruptThreadThreshold > 0 && activeTime >= interruptThreadThreshold * 1000L) {
monitoredThread.interruptIfStuck(interruptThreadThreshold);
}
}
// Check if any threads previously reported as stuck, have finished.
- for (CompletedStuckThread completedStuckThread = completedStuckThreadsQueue.poll();
- completedStuckThread != null; completedStuckThread = completedStuckThreadsQueue.poll()) {
+ for (CompletedStuckThread completedStuckThread = completedStuckThreadsQueue
+ .poll(); completedStuckThread != null; completedStuckThread = completedStuckThreadsQueue.poll()) {
int numStuckThreads = stuckCount.decrementAndGet();
notifyStuckThreadCompleted(completedStuckThread, numStuckThreads);
@@ -287,21 +267,19 @@ public class StuckThreadDetectionValve extends ValveBase {
private final Thread thread;
private final String requestUri;
private final long start;
- private final AtomicInteger state = new AtomicInteger(
- MonitoredThreadState.RUNNING.ordinal());
+ private final AtomicInteger state = new AtomicInteger(MonitoredThreadState.RUNNING.ordinal());
/**
- * Semaphore to synchronize the stuck thread with the background-process
- * thread. It's not used if the interruption feature is not active.
+ * Semaphore to synchronize the stuck thread with the background-process thread. It's not used if the
+ * interruption feature is not active.
*/
private final Semaphore interruptionSemaphore;
/**
- * Set to true after the thread is interrupted. No need to make it
- * volatile since it is accessed right after acquiring the semaphore.
+ * Set to true after the thread is interrupted. No need to make it volatile since it is accessed right after
+ * acquiring the semaphore.
*/
private boolean interrupted;
- MonitoredThread(Thread thread, String requestUri,
- boolean interruptible) {
+ MonitoredThread(Thread thread, String requestUri, boolean interruptible) {
this.thread = thread;
this.requestUri = requestUri;
this.start = System.currentTimeMillis();
@@ -330,15 +308,14 @@ public class StuckThreadDetectionValve extends ValveBase {
public boolean markAsStuckIfStillRunning() {
return this.state.compareAndSet(MonitoredThreadState.RUNNING.ordinal(),
- MonitoredThreadState.STUCK.ordinal());
+ MonitoredThreadState.STUCK.ordinal());
}
public MonitoredThreadState markAsDone() {
int val = this.state.getAndSet(MonitoredThreadState.DONE.ordinal());
MonitoredThreadState threadState = MonitoredThreadState.values()[val];
- if (threadState == MonitoredThreadState.STUCK
- && interruptionSemaphore != null) {
+ if (threadState == MonitoredThreadState.STUCK && interruptionSemaphore != null) {
try {
// use the semaphore to synchronize with the background thread
// which might try to interrupt this current thread.
@@ -346,14 +323,12 @@ public class StuckThreadDetectionValve extends ValveBase {
// going out from here, maybe already serving a new request
this.interruptionSemaphore.acquire();
} catch (InterruptedException e) {
- log.debug(
- "thread interrupted after the request is finished, ignoring",
- e);
+ log.debug("thread interrupted after the request is finished, ignoring", e);
}
// no need to release the semaphore, it will be GCed
}
- //else the request went through before being marked as stuck, no need
- //to sync against the semaphore
+ // else the request went through before being marked as stuck, no need
+ // to sync against the semaphore
return threadState;
}
@@ -362,21 +337,17 @@ public class StuckThreadDetectionValve extends ValveBase {
}
public boolean interruptIfStuck(long interruptThreadThreshold) {
- if (!isMarkedAsStuck() || interruptionSemaphore == null
- || !this.interruptionSemaphore.tryAcquire()) {
+ if (!isMarkedAsStuck() || interruptionSemaphore == null || !this.interruptionSemaphore.tryAcquire()) {
// if the semaphore is already acquired, it means that the
// request thread got unstuck before we interrupted it
return false;
}
try {
if (log.isWarnEnabled()) {
- String msg = sm.getString(
- "stuckThreadDetectionValve.notifyStuckThreadInterrupted",
- this.getThread().getName(),
- Long.valueOf(getActiveTimeInMillis()),
- this.getStartTime(), this.getRequestUri(),
- Long.valueOf(interruptThreadThreshold),
- String.valueOf(this.getThread().getId()));
+ String msg = sm.getString("stuckThreadDetectionValve.notifyStuckThreadInterrupted",
+ this.getThread().getName(), Long.valueOf(getActiveTimeInMillis()), this.getStartTime(),
+ this.getRequestUri(), Long.valueOf(interruptThreadThreshold),
+ String.valueOf(this.getThread().getId()));
Throwable th = new Throwable();
th.setStackTrace(this.getThread().getStackTrace());
log.warn(msg, th);
@@ -420,6 +391,8 @@ public class StuckThreadDetectionValve extends ValveBase {
}
private enum MonitoredThreadState {
- RUNNING, STUCK, DONE
+ RUNNING,
+ STUCK,
+ DONE
}
}
diff --git a/java/org/apache/catalina/valves/ValveBase.java b/java/org/apache/catalina/valves/ValveBase.java
index e19c7491b9..e01b56187a 100644
--- a/java/org/apache/catalina/valves/ValveBase.java
+++ b/java/org/apache/catalina/valves/ValveBase.java
@@ -28,11 +28,9 @@ import org.apache.juli.logging.Log;
import org.apache.tomcat.util.res.StringManager;
/**
- * Convenience base class for implementations of the <b>Valve</b> interface.
- * A subclass <strong>MUST</strong> implement an <code>invoke()</code>
- * method to provide the required functionality, and <strong>MAY</strong>
- * implement the <code>Lifecycle</code> interface to provide configuration
- * management and lifecycle support.
+ * Convenience base class for implementations of the <b>Valve</b> interface. A subclass <strong>MUST</strong> implement
+ * an <code>invoke()</code> method to provide the required functionality, and <strong>MAY</strong> implement the
+ * <code>Lifecycle</code> interface to provide configuration management and lifecycle support.
*
* @author Craig R. McClanahan
*/
@@ -41,7 +39,7 @@ public abstract class ValveBase extends LifecycleMBeanBase implements Contained,
protected static final StringManager sm = StringManager.getManager(ValveBase.class);
- //------------------------------------------------------ Constructor
+ // ------------------------------------------------------ Constructor
public ValveBase() {
this(false);
@@ -53,7 +51,7 @@ public abstract class ValveBase extends LifecycleMBeanBase implements Contained,
}
- //------------------------------------------------------ Instance Variables
+ // ------------------------------------------------------ Instance Variables
/**
* Does this valve support Servlet 3+ async requests?
@@ -79,7 +77,7 @@ public abstract class ValveBase extends LifecycleMBeanBase implements Contained,
protected Valve next = null;
- //-------------------------------------------------------------- Properties
+ // -------------------------------------------------------------- Properties
/**
* Return the Container with which this Valve is associated, if any.
@@ -113,8 +111,7 @@ public abstract class ValveBase extends LifecycleMBeanBase implements Contained,
/**
- * Return the next Valve in this pipeline, or <code>null</code> if this
- * is the last Valve in the pipeline.
+ * Return the next Valve in this pipeline, or <code>null</code> if this is the last Valve in the pipeline.
*/
@Override
public Valve getNext() {
@@ -133,12 +130,11 @@ public abstract class ValveBase extends LifecycleMBeanBase implements Contained,
}
- //---------------------------------------------------------- Public Methods
+ // ---------------------------------------------------------- Public Methods
/**
- * 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() {
@@ -154,11 +150,11 @@ public abstract class ValveBase extends LifecycleMBeanBase implements Contained,
/**
- * Start this component and implement the requirements
- * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
+ * 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 {
@@ -167,11 +163,11 @@ public abstract class ValveBase extends LifecycleMBeanBase implements Contained,
/**
- * Stop this component and implement the requirements
- * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
+ * 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 {
@@ -188,7 +184,7 @@ public abstract class ValveBase extends LifecycleMBeanBase implements Contained,
}
- // -------------------- JMX and Registration --------------------
+ // -------------------- JMX and Registration --------------------
@Override
public String getObjectNameKeyProperties() {
@@ -215,7 +211,7 @@ public abstract class ValveBase extends LifecycleMBeanBase implements Contained,
if (valve.getClass() == this.getClass()) {
// Duplicate valve earlier in pipeline
// increment sequence number
- seq ++;
+ seq++;
}
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org
[tomcat] 02/02: Update clean-up configuration to add removal of redundant modifiers
Posted by ma...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
markt pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit b2ff1076f6cd481cc004ca1ab1d595440ee1bed3
Author: Mark Thomas <ma...@apache.org>
AuthorDate: Wed Feb 15 12:01:56 2023 +0000
Update clean-up configuration to add removal of redundant modifiers
---
res/ide-support/eclipse/clean-up-asf-tomcat.xml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/res/ide-support/eclipse/clean-up-asf-tomcat.xml b/res/ide-support/eclipse/clean-up-asf-tomcat.xml
index 4a5b69aa25..b250c8798a 100644
--- a/res/ide-support/eclipse/clean-up-asf-tomcat.xml
+++ b/res/ide-support/eclipse/clean-up-asf-tomcat.xml
@@ -118,7 +118,7 @@
<setting id="cleanup.convert_to_enhanced_for_loop" value="false"/>
<setting id="cleanup.remove_unused_private_fields" value="true"/>
<setting id="cleanup.never_use_blocks" value="false"/>
- <setting id="cleanup.remove_redundant_modifiers" value="false"/>
+ <setting id="cleanup.remove_redundant_modifiers" value="true"/>
<setting id="cleanup.unreachable_block" value="false"/>
<setting id="cleanup.redundant_falling_through_block_end" value="false"/>
<setting id="cleanup.switch" value="false"/>
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org