This is an automated email from the ASF dual-hosted git repository.
remm pushed a commit to branch 9.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git
The following commit(s) were added to refs/heads/9.0.x by this push:
new 0ac3543bf1 Cleanups
0ac3543bf1 is described below
commit 0ac3543bf112740dc0bfe92f757b67b1d56f7547
Author: remm <[email protected]>
AuthorDate: Sun Mar 16 22:31:21 2025 +0100
Cleanups
---
java/org/apache/catalina/Context.java | 26 +++++++++---------
java/org/apache/catalina/Host.java | 2 +-
java/org/apache/catalina/Pipeline.java | 4 +--
java/org/apache/catalina/Realm.java | 2 +-
java/org/apache/catalina/Server.java | 2 +-
java/org/apache/catalina/Service.java | 2 +-
java/org/apache/catalina/WebResourceRoot.java | 8 +++---
java/org/apache/catalina/Wrapper.java | 2 +-
.../catalina/authenticator/AuthenticatorBase.java | 8 +++---
.../catalina/authenticator/BasicAuthenticator.java | 2 +-
.../authenticator/DigestAuthenticator.java | 14 ++++------
.../catalina/authenticator/FormAuthenticator.java | 10 +++----
.../catalina/authenticator/SSLAuthenticator.java | 4 +--
.../catalina/authenticator/SingleSignOn.java | 12 ++++-----
.../authenticator/SingleSignOnSessionKey.java | 9 +++----
.../authenticator/SpnegoAuthenticator.java | 6 ++---
.../jaspic/AuthConfigFactoryImpl.java | 12 ++++-----
.../authenticator/jaspic/CallbackHandlerImpl.java | 2 +-
.../jaspic/SimpleServerAuthConfig.java | 4 +--
java/org/apache/catalina/core/ContainerBase.java | 2 +-
java/org/apache/catalina/core/StandardContext.java | 26 +++++++++---------
.../apache/catalina/manager/ManagerServlet.java | 2 +-
.../webresources/AbstractArchiveResource.java | 2 +-
.../webresources/AbstractArchiveResourceSet.java | 12 ++++-----
.../webresources/AbstractFileResourceSet.java | 9 +++----
.../catalina/webresources/AbstractResourceSet.java | 2 +-
java/org/apache/catalina/webresources/Cache.java | 16 +++++------
.../catalina/webresources/CachedResource.java | 2 +-
.../catalina/webresources/DirResourceSet.java | 14 +++++-----
.../catalina/webresources/ExtractingRoot.java | 3 +--
.../catalina/webresources/FileResourceSet.java | 4 +--
.../apache/catalina/webresources/StandardRoot.java | 19 ++++++-------
java/org/apache/coyote/AbstractProcessorLight.java | 2 +-
java/org/apache/coyote/AbstractProtocol.java | 12 ++++-----
java/org/apache/coyote/CompressionConfig.java | 23 ++++++++--------
java/org/apache/coyote/Request.java | 11 +++-----
java/org/apache/coyote/Response.java | 8 +++---
.../org/apache/coyote/ajp/AbstractAjpProtocol.java | 5 ++--
java/org/apache/coyote/ajp/AjpMessage.java | 4 +--
java/org/apache/coyote/ajp/AjpProcessor.java | 19 +++++++------
.../coyote/http11/AbstractHttp11Protocol.java | 11 ++++----
.../apache/coyote/http11/Http11InputBuffer.java | 31 ++++++----------------
java/org/apache/coyote/http11/Http11Processor.java | 28 ++++++++-----------
.../coyote/http11/filters/BufferedInputFilter.java | 2 +-
.../coyote/http11/filters/ChunkedInputFilter.java | 10 +++----
.../coyote/http11/filters/IdentityInputFilter.java | 4 ++-
.../http11/filters/IdentityOutputFilter.java | 2 +-
.../http11/filters/SavedRequestInputFilter.java | 2 +-
.../coyote/http11/upgrade/UpgradeGroupInfo.java | 8 +++---
.../http11/upgrade/UpgradeServletOutputStream.java | 8 ++----
java/org/apache/coyote/http2/HPackHuffman.java | 18 +++++--------
java/org/apache/coyote/http2/HpackDecoder.java | 2 +-
.../coyote/http2/Http2AsyncUpgradeHandler.java | 6 ++---
java/org/apache/coyote/http2/Http2Protocol.java | 16 ++++-------
.../apache/coyote/http2/Http2UpgradeHandler.java | 13 +++------
java/org/apache/coyote/http2/Stream.java | 23 ++++++----------
56 files changed, 222 insertions(+), 290 deletions(-)
diff --git a/java/org/apache/catalina/Context.java
b/java/org/apache/catalina/Context.java
index 52f1f1779f..ccf32c3024 100644
--- a/java/org/apache/catalina/Context.java
+++ b/java/org/apache/catalina/Context.java
@@ -132,7 +132,7 @@ public interface Context extends Container, ContextBind {
*
* @param listeners The set of instantiated listener objects.
*/
- void setApplicationEventListeners(Object listeners[]);
+ void setApplicationEventListeners(Object[] listeners);
/**
@@ -150,7 +150,7 @@ public interface Context extends Container, ContextBind {
*
* @param listeners The set of instantiated listener objects.
*/
- void setApplicationLifecycleListeners(Object listeners[]);
+ void setApplicationLifecycleListeners(Object[] listeners);
/**
@@ -920,19 +920,19 @@ public interface Context extends Container, ContextBind {
/**
- * @return the set of application listener class names configured for this
application.
+ * @return the array of application listener class names configured for
this application.
*/
String[] findApplicationListeners();
/**
- * @return the set of application parameters for this application.
+ * @return the array of application parameters for this application.
*/
ApplicationParameter[] findApplicationParameters();
/**
- * @return the set of security constraints for this web application. If
there are none, a zero-length array is
+ * @return the array of security constraints for this web application. If
there are none, a zero-length array is
* returned.
*/
SecurityConstraint[] findConstraints();
@@ -970,7 +970,7 @@ public interface Context extends Container, ContextBind {
/**
- * @return the set of defined error pages for all specified error codes
and exception types.
+ * @return the array of defined error pages for all specified error codes
and exception types.
*/
ErrorPage[] findErrorPages();
@@ -984,13 +984,13 @@ public interface Context extends Container, ContextBind {
/**
- * @return the set of defined filters for this Context.
+ * @return the array of defined filters for this Context.
*/
FilterDef[] findFilterDefs();
/**
- * @return the set of filter mappings for this Context.
+ * @return the array of filter mappings for this Context.
*/
FilterMap[] findFilterMaps();
@@ -1105,7 +1105,8 @@ public interface Context extends Container, ContextBind {
/**
- * @return the set of watched resources for this Context. If none are
defined, a zero length array will be returned.
+ * @return the array of watched resources for this Context. If none are
defined, a zero length array will be
+ * returned.
*/
String[] findWatchedResources();
@@ -1120,19 +1121,20 @@ public interface Context extends Container, ContextBind
{
/**
- * @return the set of welcome files defined for this Context. If none are
defined, a zero-length array is returned.
+ * @return the array of welcome files defined for this Context. If none
are defined, a zero-length array is
+ * returned.
*/
String[] findWelcomeFiles();
/**
- * @return the set of LifecycleListener classes that will be added to
newly created Wrappers automatically.
+ * @return the array of LifecycleListener classes that will be added to
newly created Wrappers automatically.
*/
String[] findWrapperLifecycles();
/**
- * @return the set of ContainerListener classes that will be added to
newly created Wrappers automatically.
+ * @return the array of ContainerListener classes that will be added to
newly created Wrappers automatically.
*/
String[] findWrapperListeners();
diff --git a/java/org/apache/catalina/Host.java
b/java/org/apache/catalina/Host.java
index 06d6599808..a8b8a05f93 100644
--- a/java/org/apache/catalina/Host.java
+++ b/java/org/apache/catalina/Host.java
@@ -220,7 +220,7 @@ public interface Host extends Container {
/**
- * @return the set of alias names for this Host. If none are defined, a
zero length array is returned.
+ * @return the array of alias names for this Host. If none are defined, a
zero length array is returned.
*/
String[] findAliases();
diff --git a/java/org/apache/catalina/Pipeline.java
b/java/org/apache/catalina/Pipeline.java
index 57afd26ac8..9036fca7a9 100644
--- a/java/org/apache/catalina/Pipeline.java
+++ b/java/org/apache/catalina/Pipeline.java
@@ -80,8 +80,8 @@ public interface Pipeline extends Contained {
/**
- * @return the set of Valves in the pipeline associated with this
Container, including the basic Valve (if any). If
- * there are no such Valves, a zero-length array is returned.
+ * @return the array of Valves in the pipeline associated with this
Container, including the basic Valve (if any).
+ * If there are no such Valves, a zero-length array is returned.
*/
Valve[] getValves();
diff --git a/java/org/apache/catalina/Realm.java
b/java/org/apache/catalina/Realm.java
index 94ecace28d..9d060af44d 100644
--- a/java/org/apache/catalina/Realm.java
+++ b/java/org/apache/catalina/Realm.java
@@ -167,7 +167,7 @@ public interface Realm extends Contained {
*
* @return the associated principal, or {@code null} if there is none
*/
- Principal authenticate(X509Certificate certs[]);
+ Principal authenticate(X509Certificate[] certs);
/**
diff --git a/java/org/apache/catalina/Server.java
b/java/org/apache/catalina/Server.java
index 3c3a248ec6..dd64b019bf 100644
--- a/java/org/apache/catalina/Server.java
+++ b/java/org/apache/catalina/Server.java
@@ -231,7 +231,7 @@ public interface Server extends Lifecycle {
/**
- * @return the set of Services defined within this Server.
+ * @return the array of Services defined within this Server.
*/
Service[] findServices();
diff --git a/java/org/apache/catalina/Service.java
b/java/org/apache/catalina/Service.java
index 04a2e594fa..8eb1888581 100644
--- a/java/org/apache/catalina/Service.java
+++ b/java/org/apache/catalina/Service.java
@@ -101,7 +101,7 @@ public interface Service extends Lifecycle {
/**
* Find and return the set of Connectors associated with this Service.
*
- * @return the set of associated Connectors
+ * @return the array of associated Connectors
*/
Connector[] findConnectors();
diff --git a/java/org/apache/catalina/WebResourceRoot.java
b/java/org/apache/catalina/WebResourceRoot.java
index b99874ee3f..d2a9a34423 100644
--- a/java/org/apache/catalina/WebResourceRoot.java
+++ b/java/org/apache/catalina/WebResourceRoot.java
@@ -205,7 +205,7 @@ public interface WebResourceRoot extends Lifecycle {
void addPreResources(WebResourceSet webResourceSet);
/**
- * @return the list of WebResourceSet configured to this web application
as a 'Pre' resource.
+ * @return the array of WebResourceSet configured to this web application
as a 'Pre' resource.
*/
WebResourceSet[] getPreResources();
@@ -217,7 +217,7 @@ public interface WebResourceRoot extends Lifecycle {
void addJarResources(WebResourceSet webResourceSet);
/**
- * @return the list of WebResourceSet configured to this web application
as a 'Jar' resource.
+ * @return the array of WebResourceSet configured to this web application
as a 'Jar' resource.
*/
WebResourceSet[] getJarResources();
@@ -229,7 +229,7 @@ public interface WebResourceRoot extends Lifecycle {
void addPostResources(WebResourceSet webResourceSet);
/**
- * @return the list of WebResourceSet configured to this web application
as a 'Post' resource.
+ * @return the array of WebResourceSet configured to this web application
as a 'Post' resource.
*/
WebResourceSet[] getPostResources();
@@ -380,7 +380,7 @@ public interface WebResourceRoot extends Lifecycle {
void deregisterTrackedResource(TrackedWebResource trackedResource);
/**
- * @return the set of {@link WebResourceSet#getBaseUrl()} for all {@link
WebResourceSet}s used by this root.
+ * @return the list of {@link WebResourceSet#getBaseUrl()} for all {@link
WebResourceSet}s used by this root.
*/
List<URL> getBaseUrls();
diff --git a/java/org/apache/catalina/Wrapper.java
b/java/org/apache/catalina/Wrapper.java
index 2c268eb16c..77515def2a 100644
--- a/java/org/apache/catalina/Wrapper.java
+++ b/java/org/apache/catalina/Wrapper.java
@@ -231,7 +231,7 @@ public interface Wrapper extends Container {
/**
- * @return the set of security role reference names associated with this
servlet, if any; otherwise return a
+ * @return the array of security role reference names associated with this
servlet, if any; otherwise return a
* zero-length array.
*/
String[] findSecurityReferences();
diff --git a/java/org/apache/catalina/authenticator/AuthenticatorBase.java
b/java/org/apache/catalina/authenticator/AuthenticatorBase.java
index 4388cd2e9e..8a506ccaf8 100644
--- a/java/org/apache/catalina/authenticator/AuthenticatorBase.java
+++ b/java/org/apache/catalina/authenticator/AuthenticatorBase.java
@@ -720,7 +720,7 @@ public abstract class AuthenticatorBase extends ValveBase
implements Authenticat
private CallbackHandler createCallbackHandler() {
- CallbackHandler callbackHandler = null;
+ CallbackHandler callbackHandler;
Class<?> clazz = null;
try {
@@ -821,7 +821,7 @@ public abstract class AuthenticatorBase extends ValveBase
implements Authenticat
if (requirePrincipal) {
return false;
}
- } else if (cachedAuth == false ||
!principal.getUserPrincipal().equals(request.getUserPrincipal())) {
+ } else if (!cachedAuth ||
!principal.getUserPrincipal().equals(request.getUserPrincipal())) {
// Skip registration if authentication credentials were
// cached and the Principal did not change.
@@ -935,7 +935,7 @@ public abstract class AuthenticatorBase extends ValveBase
implements Authenticat
authorized = new GenericPrincipal(username, null, null);
}
String authType = request.getAuthType();
- if (authType == null || authType.length() == 0) {
+ if (authType == null || authType.isEmpty()) {
authType = getAuthMethod();
}
register(request, response, authorized, authType, username,
null);
@@ -1203,7 +1203,7 @@ public abstract class AuthenticatorBase extends ValveBase
implements Authenticat
// path, if there is one
Container parent = context.getParent();
while ((sso == null) && (parent != null)) {
- Valve valves[] = parent.getPipeline().getValves();
+ Valve[] valves = parent.getPipeline().getValves();
for (Valve valve : valves) {
if (valve instanceof SingleSignOn) {
sso = (SingleSignOn) valve;
diff --git a/java/org/apache/catalina/authenticator/BasicAuthenticator.java
b/java/org/apache/catalina/authenticator/BasicAuthenticator.java
index 784698a58a..0a1f08d3f5 100644
--- a/java/org/apache/catalina/authenticator/BasicAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/BasicAuthenticator.java
@@ -103,7 +103,7 @@ public class BasicAuthenticator extends AuthenticatorBase {
if (authorization != null) {
authorization.toBytes();
ByteChunk authorizationBC = authorization.getByteChunk();
- BasicCredentials credentials = null;
+ BasicCredentials credentials;
try {
credentials = new BasicCredentials(authorizationBC, charset,
getTrimCredentials());
String username = credentials.getUsername();
diff --git a/java/org/apache/catalina/authenticator/DigestAuthenticator.java
b/java/org/apache/catalina/authenticator/DigestAuthenticator.java
index d2e9cc8d03..88b222eb49 100644
--- a/java/org/apache/catalina/authenticator/DigestAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/DigestAuthenticator.java
@@ -208,7 +208,7 @@ public class DigestAuthenticator extends AuthenticatorBase {
public String getAlgorithms() {
StringBuilder result = new StringBuilder();
- StringUtils.join(algorithms, ',', (x) -> x.getRfcName(), result);
+ StringUtils.join(algorithms, ',', AuthDigest::getRfcName, result);
return result.toString();
}
@@ -498,7 +498,7 @@ public class DigestAuthenticator extends AuthenticatorBase {
private final long nonceValidity;
private final String key;
private final Map<String,NonceInfo> nonces;
- private boolean validateUri = true;
+ private final boolean validateUri;
private String userName = null;
private String method = null;
@@ -597,7 +597,7 @@ public class DigestAuthenticator extends AuthenticatorBase {
absolute.append("://");
absolute.append(host);
absolute.append(uriQuery);
- if (!uri.equals(absolute.toString())) {
+ if (!uri.contentEquals(absolute)) {
return false;
}
} else {
@@ -687,11 +687,7 @@ public class DigestAuthenticator extends AuthenticatorBase
{
}
// Validate algorithm is one of the algorithms configured for the
authenticator
- if (!algorithms.contains(algorithm)) {
- return false;
- }
-
- return true;
+ return algorithms.contains(algorithm);
}
public boolean isNonceStale() {
@@ -713,7 +709,7 @@ public class DigestAuthenticator extends AuthenticatorBase {
public static class NonceInfo {
private final long timestamp;
- private final boolean seen[];
+ private final boolean[] seen;
private final int offset;
private int count = 0;
diff --git a/java/org/apache/catalina/authenticator/FormAuthenticator.java
b/java/org/apache/catalina/authenticator/FormAuthenticator.java
index 1deb9de083..1e9fae3c02 100644
--- a/java/org/apache/catalina/authenticator/FormAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/FormAuthenticator.java
@@ -161,7 +161,7 @@ public class FormAuthenticator extends AuthenticatorBase {
// References to objects we will need later
Session session = null;
- Principal principal = null;
+ Principal principal;
// Have we authenticated this user before but have caching disabled?
if (!cache) {
@@ -229,7 +229,7 @@ public class FormAuthenticator extends AuthenticatorBase {
// If this request was to the root of the context without a
trailing
// '/', need to redirect to add it else the submit of the login
form
// may not go to the correct web application
- if (request.getServletPath().length() == 0 &&
request.getPathInfo() == null) {
+ if (request.getServletPath().isEmpty() && request.getPathInfo() ==
null) {
StringBuilder location = new StringBuilder(requestURI);
location.append('/');
if (request.getQueryString() != null) {
@@ -429,7 +429,7 @@ public class FormAuthenticator extends AuthenticatorBase {
}
String loginPage = config.getLoginPage();
- if (loginPage == null || loginPage.length() == 0) {
+ if (loginPage == null || loginPage.isEmpty()) {
String msg = sm.getString("formAuthenticator.noLoginPage",
context.getName());
log.warn(msg);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
msg);
@@ -485,7 +485,7 @@ public class FormAuthenticator extends AuthenticatorBase {
throws IOException {
String errorPage = config.getErrorPage();
- if (errorPage == null || errorPage.length() == 0) {
+ if (errorPage == null || errorPage.isEmpty()) {
String msg = sm.getString("formAuthenticator.noErrorPage",
context.getName());
log.warn(msg);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
msg);
@@ -668,7 +668,7 @@ public class FormAuthenticator extends AuthenticatorBase {
// Create and populate a SavedRequest object for this request
SavedRequest saved = new SavedRequest();
- Cookie cookies[] = request.getCookies();
+ Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
saved.addCookie(cookie);
diff --git a/java/org/apache/catalina/authenticator/SSLAuthenticator.java
b/java/org/apache/catalina/authenticator/SSLAuthenticator.java
index bb47775eff..0c26c05c63 100644
--- a/java/org/apache/catalina/authenticator/SSLAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/SSLAuthenticator.java
@@ -77,7 +77,7 @@ public class SSLAuthenticator extends AuthenticatorBase {
containerLog.trace(" Looking up certificates");
}
- X509Certificate certs[] = getRequestCertificates(request);
+ X509Certificate[] certs = getRequestCertificates(request);
if ((certs == null) || (certs.length < 1)) {
if (containerLog.isDebugEnabled()) {
@@ -128,7 +128,7 @@ public class SSLAuthenticator extends AuthenticatorBase {
*/
protected X509Certificate[] getRequestCertificates(final Request request)
throws IllegalStateException {
- X509Certificate certs[] = (X509Certificate[])
request.getAttribute(Globals.CERTIFICATES_ATTR);
+ X509Certificate[] certs = (X509Certificate[])
request.getAttribute(Globals.CERTIFICATES_ATTR);
if ((certs == null) || (certs.length < 1)) {
try {
diff --git a/java/org/apache/catalina/authenticator/SingleSignOn.java
b/java/org/apache/catalina/authenticator/SingleSignOn.java
index fe68b1dd63..db7617b315 100644
--- a/java/org/apache/catalina/authenticator/SingleSignOn.java
+++ b/java/org/apache/catalina/authenticator/SingleSignOn.java
@@ -112,7 +112,7 @@ public class SingleSignOn extends ValveBase {
* @param cookieDomain cookie domain name
*/
public void setCookieDomain(String cookieDomain) {
- if (cookieDomain != null && cookieDomain.trim().length() == 0) {
+ if (cookieDomain != null && cookieDomain.trim().isEmpty()) {
this.cookieDomain = null;
} else {
this.cookieDomain = cookieDomain;
@@ -225,7 +225,7 @@ public class SingleSignOn extends ValveBase {
containerLog.trace(sm.getString("singleSignOn.debug.cookieCheck"));
}
Cookie cookie = null;
- Cookie cookies[] = request.getCookies();
+ Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie value : cookies) {
if (cookieName.equals(value.getName())) {
@@ -310,7 +310,7 @@ public class SingleSignOn extends ValveBase {
// session was logged out, we'll log out of all session associated with
// the SSO.
if (((session.getMaxInactiveInterval() > 0) &&
- (session.getIdleTimeInternal() >=
session.getMaxInactiveInterval() * 1000)) ||
+ (session.getIdleTimeInternal() >=
session.getMaxInactiveInterval() * 1000L)) ||
(!session.getManager().getContext().getState().isAvailable()))
{
if (containerLog.isDebugEnabled()) {
containerLog.debug(sm.getString("singleSignOn.debug.sessionTimeout", ssoId,
session));
@@ -381,7 +381,7 @@ public class SingleSignOn extends ValveBase {
// Expire any associated sessions
Set<SingleSignOnSessionKey> ssoKeys = sso.findSessions();
- if (ssoKeys.size() == 0) {
+ if (ssoKeys.isEmpty()) {
if (containerLog.isDebugEnabled()) {
containerLog.debug(sm.getString("singleSignOn.debug.deregisterNone", ssoId));
}
@@ -420,7 +420,7 @@ public class SingleSignOn extends ValveBase {
containerLog.warn(sm.getString("singleSignOn.sessionExpire.managerNotFound",
key));
return;
}
- Session session = null;
+ Session session;
try {
session = manager.findSession(key.getSessionId());
} catch (IOException e) {
@@ -555,7 +555,7 @@ public class SingleSignOn extends ValveBase {
// If there are not sessions left in the SingleSignOnEntry,
// deregister the entry.
- if (entry.findSessions().size() == 0) {
+ if (entry.findSessions().isEmpty()) {
deregister(ssoId);
}
}
diff --git a/java/org/apache/catalina/authenticator/SingleSignOnSessionKey.java
b/java/org/apache/catalina/authenticator/SingleSignOnSessionKey.java
index 521f404781..b740594a71 100644
--- a/java/org/apache/catalina/authenticator/SingleSignOnSessionKey.java
+++ b/java/org/apache/catalina/authenticator/SingleSignOnSessionKey.java
@@ -90,13 +90,10 @@ public class SingleSignOnSessionKey implements Serializable
{
return false;
}
if (hostName == null) {
- if (other.hostName != null) {
- return false;
- }
- } else if (!hostName.equals(other.hostName)) {
- return false;
+ return other.hostName == null;
+ } else {
+ return hostName.equals(other.hostName);
}
- return true;
}
@Override
diff --git a/java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
b/java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
index 354fda014c..c34c5628a8 100644
--- a/java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
+++ b/java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
@@ -85,7 +85,7 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
}
public void setNoKeepAliveUserAgents(String noKeepAliveUserAgents) {
- if (noKeepAliveUserAgents == null || noKeepAliveUserAgents.length() ==
0) {
+ if (noKeepAliveUserAgents == null || noKeepAliveUserAgents.isEmpty()) {
this.noKeepAliveUserAgents = null;
} else {
this.noKeepAliveUserAgents =
Pattern.compile(noKeepAliveUserAgents);
@@ -183,8 +183,8 @@ public class SpnegoAuthenticator extends AuthenticatorBase {
LoginContext lc = null;
GSSContext gssContext = null;
- byte[] outToken = null;
- Principal principal = null;
+ byte[] outToken;
+ Principal principal;
try {
try {
lc = new LoginContext(getLoginConfigName());
diff --git
a/java/org/apache/catalina/authenticator/jaspic/AuthConfigFactoryImpl.java
b/java/org/apache/catalina/authenticator/jaspic/AuthConfigFactoryImpl.java
index 10a7edb391..70d4313943 100644
--- a/java/org/apache/catalina/authenticator/jaspic/AuthConfigFactoryImpl.java
+++ b/java/org/apache/catalina/authenticator/jaspic/AuthConfigFactoryImpl.java
@@ -49,7 +49,7 @@ public class AuthConfigFactoryImpl extends AuthConfigFactory {
private static final String[] EMPTY_STRING_ARRAY = new String[0];
- private static String DEFAULT_REGISTRATION_ID = getRegistrationID(null,
null);
+ private static final String DEFAULT_REGISTRATION_ID =
getRegistrationID(null, null);
private final Map<String,RegistrationContextImpl>
layerAppContextRegistrations = new ConcurrentHashMap<>();
private final Map<String,RegistrationContextImpl> appContextRegistrations
= new ConcurrentHashMap<>();
@@ -110,7 +110,7 @@ public class AuthConfigFactoryImpl extends
AuthConfigFactory {
private AuthConfigProvider createAuthConfigProvider(String className,
@SuppressWarnings("rawtypes") Map properties)
throws SecurityException {
Class<?> clazz = null;
- AuthConfigProvider provider = null;
+ AuthConfigProvider provider;
try {
clazz = Class.forName(className, true,
Thread.currentThread().getContextClassLoader());
} catch (ClassNotFoundException e) {
@@ -146,14 +146,14 @@ public class AuthConfigFactoryImpl extends
AuthConfigFactory {
private void addRegistrationContextImpl(String layer, String appContext,
String registrationID,
RegistrationContextImpl registrationContextImpl) {
- RegistrationContextImpl previous = null;
+ RegistrationContextImpl previous;
// Add the registration, noting any registration it replaces
if (layer != null && appContext != null) {
previous = layerAppContextRegistrations.put(registrationID,
registrationContextImpl);
} else if (layer == null && appContext != null) {
previous = appContextRegistrations.put(registrationID,
registrationContextImpl);
- } else if (layer != null && appContext == null) {
+ } else if (layer != null) {
previous = layerRegistrations.put(registrationID,
registrationContextImpl);
} else {
previous = defaultRegistration.put(registrationID,
registrationContextImpl);
@@ -307,10 +307,10 @@ public class AuthConfigFactoryImpl extends
AuthConfigFactory {
private static String getRegistrationID(String layer, String appContext) {
- if (layer != null && layer.length() == 0) {
+ if (layer != null && layer.isEmpty()) {
throw new
IllegalArgumentException(sm.getString("authConfigFactoryImpl.zeroLengthMessageLayer"));
}
- if (appContext != null && appContext.length() == 0) {
+ if (appContext != null && appContext.isEmpty()) {
throw new
IllegalArgumentException(sm.getString("authConfigFactoryImpl.zeroLengthAppContext"));
}
return (layer == null ? "" : layer) + ":" + (appContext == null ? "" :
appContext);
diff --git
a/java/org/apache/catalina/authenticator/jaspic/CallbackHandlerImpl.java
b/java/org/apache/catalina/authenticator/jaspic/CallbackHandlerImpl.java
index d9eedd3735..9b11b55b97 100644
--- a/java/org/apache/catalina/authenticator/jaspic/CallbackHandlerImpl.java
+++ b/java/org/apache/catalina/authenticator/jaspic/CallbackHandlerImpl.java
@@ -125,7 +125,7 @@ public class CallbackHandlerImpl implements
CallbackHandler, Contained {
mergedRoles.addAll(Arrays.asList(groups));
}
- if (mergedRoles.size() == 0) {
+ if (mergedRoles.isEmpty()) {
mergedRoles = Collections.emptyList();
}
diff --git
a/java/org/apache/catalina/authenticator/jaspic/SimpleServerAuthConfig.java
b/java/org/apache/catalina/authenticator/jaspic/SimpleServerAuthConfig.java
index 289b6f83af..0eb4c19c42 100644
--- a/java/org/apache/catalina/authenticator/jaspic/SimpleServerAuthConfig.java
+++ b/java/org/apache/catalina/authenticator/jaspic/SimpleServerAuthConfig.java
@@ -38,7 +38,7 @@ import org.apache.tomcat.util.res.StringManager;
*/
public class SimpleServerAuthConfig implements ServerAuthConfig {
- private static StringManager sm =
StringManager.getManager(SimpleServerAuthConfig.class);
+ private static final StringManager sm =
StringManager.getManager(SimpleServerAuthConfig.class);
private static final String SERVER_AUTH_MODULE_KEY_PREFIX =
"org.apache.catalina.authenticator.jaspic.ServerAuthModule.";
@@ -127,7 +127,7 @@ public class SimpleServerAuthConfig implements
ServerAuthConfig {
moduleClassName = mergedProperties.get(key);
}
- if (modules.size() == 0) {
+ if (modules.isEmpty()) {
throw new
AuthException(sm.getString("simpleServerAuthConfig.noModules"));
}
diff --git a/java/org/apache/catalina/core/ContainerBase.java
b/java/org/apache/catalina/core/ContainerBase.java
index 0cb0e3d240..460e4b6749 100644
--- a/java/org/apache/catalina/core/ContainerBase.java
+++ b/java/org/apache/catalina/core/ContainerBase.java
@@ -1049,7 +1049,7 @@ public abstract class ContainerBase extends
LifecycleMBeanBase implements Contai
} else if (c == null) {
// May happen in unit testing and/or some embedding scenarios
keyProperties.append(",container");
- keyProperties.append(containerCount++);
+ keyProperties.append(containerCount);
keyProperties.append("=null");
break;
} else {
diff --git a/java/org/apache/catalina/core/StandardContext.java
b/java/org/apache/catalina/core/StandardContext.java
index f482556746..786ba54879 100644
--- a/java/org/apache/catalina/core/StandardContext.java
+++ b/java/org/apache/catalina/core/StandardContext.java
@@ -3908,9 +3908,9 @@ public class StandardContext extends ContainerBase
implements Context, Notificat
ApplicationFilterConfig filterConfig = new
ApplicationFilterConfig(this, entry.getValue());
filterConfigs.put(name, filterConfig);
} catch (Throwable t) {
- t = ExceptionUtils.unwrapInvocationTargetException(t);
- ExceptionUtils.handleThrowable(t);
-
getLogger().error(sm.getString("standardContext.filterStart", name), t);
+ Throwable throwable =
ExceptionUtils.unwrapInvocationTargetException(t);
+ ExceptionUtils.handleThrowable(throwable);
+
getLogger().error(sm.getString("standardContext.filterStart", name), throwable);
ok = false;
}
}
@@ -3985,9 +3985,9 @@ public class StandardContext extends ContainerBase
implements Context, Notificat
String listener = listeners[i];
results[i] = getInstanceManager().newInstance(listener);
} catch (Throwable t) {
- t = ExceptionUtils.unwrapInvocationTargetException(t);
- ExceptionUtils.handleThrowable(t);
-
getLogger().error(sm.getString("standardContext.applicationListener",
listeners[i]), t);
+ Throwable throwable =
ExceptionUtils.unwrapInvocationTargetException(t);
+ ExceptionUtils.handleThrowable(throwable);
+
getLogger().error(sm.getString("standardContext.applicationListener",
listeners[i]), throwable);
ok = false;
}
}
@@ -4118,10 +4118,10 @@ public class StandardContext extends ContainerBase
implements Context, Notificat
getInstanceManager().destroyInstance(listeners[j]);
}
} catch (Throwable t) {
- t = ExceptionUtils.unwrapInvocationTargetException(t);
- ExceptionUtils.handleThrowable(t);
+ Throwable throwable =
ExceptionUtils.unwrapInvocationTargetException(t);
+ ExceptionUtils.handleThrowable(throwable);
getLogger().error(sm.getString("standardContext.listenerStop",
listeners[j].getClass().getName()),
- t);
+ throwable);
ok = false;
}
}
@@ -4140,10 +4140,10 @@ public class StandardContext extends ContainerBase
implements Context, Notificat
getInstanceManager().destroyInstance(listeners[j]);
}
} catch (Throwable t) {
- t = ExceptionUtils.unwrapInvocationTargetException(t);
- ExceptionUtils.handleThrowable(t);
+ Throwable throwable =
ExceptionUtils.unwrapInvocationTargetException(t);
+ ExceptionUtils.handleThrowable(throwable);
getLogger().error(sm.getString("standardContext.listenerStop",
listeners[j].getClass().getName()),
- t);
+ throwable);
ok = false;
}
}
@@ -5372,7 +5372,7 @@ public class StandardContext extends ContainerBase
implements Context, Notificat
// Create this directory if necessary
File dir = new File(workDir);
if (!dir.isAbsolute()) {
- String catalinaHomePath = null;
+ String catalinaHomePath;
try {
catalinaHomePath = getCatalinaBase().getCanonicalPath();
dir = new File(catalinaHomePath, workDir);
diff --git a/java/org/apache/catalina/manager/ManagerServlet.java
b/java/org/apache/catalina/manager/ManagerServlet.java
index c1f3935906..47a773368e 100644
--- a/java/org/apache/catalina/manager/ManagerServlet.java
+++ b/java/org/apache/catalina/manager/ManagerServlet.java
@@ -975,7 +975,7 @@ public class ManagerServlet extends HttpServlet implements
ContainerServlet {
if (displayPath.isEmpty()) {
displayPath = "/";
}
- List<String> parts = null;
+ List<String> parts;
if (context.getState().isAvailable()) {
parts = Arrays.asList(displayPath, "running", "" +
context.getManager().findSessions().length,
context.getDocBase());
diff --git a/java/org/apache/catalina/webresources/AbstractArchiveResource.java
b/java/org/apache/catalina/webresources/AbstractArchiveResource.java
index d4f2e1c4a1..18788275b5 100644
--- a/java/org/apache/catalina/webresources/AbstractArchiveResource.java
+++ b/java/org/apache/catalina/webresources/AbstractArchiveResource.java
@@ -53,7 +53,7 @@ public abstract class AbstractArchiveResource extends
AbstractResource {
resourceName = resourceName.substring(0, resourceName.length() -
1);
}
String internalPath = archiveResourceSet.getInternalPath();
- if (internalPath.length() > 0 &&
resourceName.equals(internalPath.subSequence(1, internalPath.length()))) {
+ if (!internalPath.isEmpty() &&
resourceName.contentEquals(internalPath.subSequence(1, internalPath.length())))
{
name = "";
} else {
int index = resourceName.lastIndexOf('/');
diff --git
a/java/org/apache/catalina/webresources/AbstractArchiveResourceSet.java
b/java/org/apache/catalina/webresources/AbstractArchiveResourceSet.java
index 52ec4e9dbf..b055c157fe 100644
--- a/java/org/apache/catalina/webresources/AbstractArchiveResourceSet.java
+++ b/java/org/apache/catalina/webresources/AbstractArchiveResourceSet.java
@@ -71,7 +71,7 @@ public abstract class AbstractArchiveResourceSet extends
AbstractResourceSet {
if (path.startsWith(webAppMount)) {
String pathInJar = getInternalPath() +
path.substring(webAppMount.length());
// Always strip off the leading '/' to get the JAR path
- if (pathInJar.length() > 0 && pathInJar.charAt(0) == '/') {
+ if (!pathInJar.isEmpty() && pathInJar.charAt(0) == '/') {
pathInJar = pathInJar.substring(1);
}
for (String name : getArchiveEntries(false).keySet()) {
@@ -81,13 +81,13 @@ public abstract class AbstractArchiveResourceSet extends
AbstractResourceSet {
} else {
name = name.substring(pathInJar.length());
}
- if (name.length() == 0) {
+ if (name.isEmpty()) {
continue;
}
if (name.charAt(0) == '/') {
name = name.substring(1);
}
- if (name.length() > 0 && name.lastIndexOf('/') == -1) {
+ if (!name.isEmpty() && name.lastIndexOf('/') == -1) {
result.add(name);
}
}
@@ -118,7 +118,7 @@ public abstract class AbstractArchiveResourceSet extends
AbstractResourceSet {
String pathInJar = getInternalPath() +
path.substring(webAppMount.length());
// Always strip off the leading '/' to get the JAR path and make
// sure it ends in '/'
- if (pathInJar.length() > 0) {
+ if (!pathInJar.isEmpty()) {
if (pathInJar.charAt(pathInJar.length() - 1) != '/') {
pathInJar = pathInJar.substring(1) + '/';
}
@@ -228,10 +228,10 @@ public abstract class AbstractArchiveResourceSet extends
AbstractResourceSet {
if (path.startsWith(webAppMount)) {
String pathInJar = getInternalPath() +
path.substring(webAppMount.length());
// Always strip off the leading '/' to get the JAR path
- if (pathInJar.length() > 0 && pathInJar.charAt(0) == '/') {
+ if (!pathInJar.isEmpty() && pathInJar.charAt(0) == '/') {
pathInJar = pathInJar.substring(1);
}
- if (pathInJar.equals("")) {
+ if (pathInJar.isEmpty()) {
// Special case
// This is a directory resource so the path must end with /
if (!path.endsWith("/")) {
diff --git a/java/org/apache/catalina/webresources/AbstractFileResourceSet.java
b/java/org/apache/catalina/webresources/AbstractFileResourceSet.java
index f3b4fd85c1..0cabb4d14e 100644
--- a/java/org/apache/catalina/webresources/AbstractFileResourceSet.java
+++ b/java/org/apache/catalina/webresources/AbstractFileResourceSet.java
@@ -117,7 +117,7 @@ public abstract class AbstractFileResourceSet extends
AbstractResourceSet {
canPath = canPath.substring(canonicalBase.length());
// The remaining request path must start with '/' if it has non-zero
length
- if (canPath.length() > 0 && canPath.charAt(0) != File.separatorChar) {
+ if (!canPath.isEmpty() && canPath.charAt(0) != File.separatorChar) {
return null;
}
@@ -132,7 +132,7 @@ public abstract class AbstractFileResourceSet extends
AbstractResourceSet {
//
// absPath is normalized so canPath needs to be normalized as well
// Can't normalize canPath earlier as canonicalBase is not normalized
- if (canPath.length() > 0) {
+ if (!canPath.isEmpty()) {
canPath = normalize(canPath);
}
if (!canPath.equals(absPath)) {
@@ -182,10 +182,7 @@ public abstract class AbstractFileResourceSet extends
AbstractResourceSet {
// level APIs are used to create the files that bypass various checks.
// File names that end in ' ' are known to cause problems when using
// File#getCanonicalPath().
- if (name.charAt(len - 1) == ' ') {
- return true;
- }
- return false;
+ return name.charAt(len - 1) == ' ';
}
diff --git a/java/org/apache/catalina/webresources/AbstractResourceSet.java
b/java/org/apache/catalina/webresources/AbstractResourceSet.java
index f139339848..bd7d0c55e7 100644
--- a/java/org/apache/catalina/webresources/AbstractResourceSet.java
+++ b/java/org/apache/catalina/webresources/AbstractResourceSet.java
@@ -40,7 +40,7 @@ public abstract class AbstractResourceSet extends
LifecycleBase implements WebRe
protected final void checkPath(String path) {
- if (path == null || path.length() == 0 || path.charAt(0) != '/') {
+ if (path == null || path.isEmpty() || path.charAt(0) != '/') {
throw new
IllegalArgumentException(sm.getString("abstractResourceSet.checkPath", path));
}
}
diff --git a/java/org/apache/catalina/webresources/Cache.java
b/java/org/apache/catalina/webresources/Cache.java
index ad41aaa983..ae85288fe8 100644
--- a/java/org/apache/catalina/webresources/Cache.java
+++ b/java/org/apache/catalina/webresources/Cache.java
@@ -49,8 +49,8 @@ public class Cache {
private int objectMaxSize = (int) maxSize / OBJECT_MAX_SIZE_FACTOR;
private CacheStrategy cacheStrategy;
- private LongAdder lookupCount = new LongAdder();
- private LongAdder hitCount = new LongAdder();
+ private final LongAdder lookupCount = new LongAdder();
+ private final LongAdder hitCount = new LongAdder();
private final ConcurrentMap<String,CachedResource> resourceCache = new
ConcurrentHashMap<>();
@@ -233,11 +233,8 @@ public class Cache {
private boolean noCache(String path) {
// Don't cache classes. The class loader handles this.
// Don't cache JARs. The ResourceSet handles this.
- if ((path.endsWith(".class") && (path.startsWith("/WEB-INF/classes/")
|| path.startsWith("/WEB-INF/lib/"))) ||
- (path.startsWith("/WEB-INF/lib/") && path.endsWith(".jar"))) {
- return true;
- }
- return false;
+ return (path.endsWith(".class") &&
(path.startsWith("/WEB-INF/classes/") || path.startsWith("/WEB-INF/lib/"))) ||
+ (path.startsWith("/WEB-INF/lib/") && path.endsWith(".jar"));
}
private long evict(long targetSize, Iterator<CachedResource> iter) {
@@ -315,9 +312,10 @@ public class Cache {
if (objectMaxSize * 1024L > Integer.MAX_VALUE) {
log.warn(sm.getString("cache.objectMaxSizeTooBigBytes",
Integer.valueOf(objectMaxSize)));
this.objectMaxSize = Integer.MAX_VALUE;
+ } else {
+ // Internally bytes, externally kilobytes
+ this.objectMaxSize = objectMaxSize * 1024;
}
- // Internally bytes, externally kilobytes
- this.objectMaxSize = objectMaxSize * 1024;
}
public int getObjectMaxSize() {
diff --git a/java/org/apache/catalina/webresources/CachedResource.java
b/java/org/apache/catalina/webresources/CachedResource.java
index 0087699f6f..f42c1bfa7b 100644
--- a/java/org/apache/catalina/webresources/CachedResource.java
+++ b/java/org/apache/catalina/webresources/CachedResource.java
@@ -421,7 +421,7 @@ public class CachedResource implements WebResource {
// Longer paths use a noticeable amount of memory so account for this
in
// the cache size. The fixed component of a String instance's memory
// usage is accounted for in the 500 bytes above.
- result += getWebappPath().length() * 2;
+ result += getWebappPath().length() * 2L;
if (getContentLength() <= objectMaxSizeBytes) {
result += getContentLength();
}
diff --git a/java/org/apache/catalina/webresources/DirResourceSet.java
b/java/org/apache/catalina/webresources/DirResourceSet.java
index 3e9676bdd3..6259b81f7e 100644
--- a/java/org/apache/catalina/webresources/DirResourceSet.java
+++ b/java/org/apache/catalina/webresources/DirResourceSet.java
@@ -46,8 +46,8 @@ public class DirResourceSet extends AbstractFileResourceSet
implements WebResour
private static final Log log = LogFactory.getLog(DirResourceSet.class);
- private Map<String,ResourceLock> resourceLocksByPath = new HashMap<>();
- private Object resourceLocksByPathLock = new Object();
+ private final Map<String,ResourceLock> resourceLocksByPath = new
HashMap<>();
+ private final Object resourceLocksByPathLock = new Object();
/**
@@ -276,7 +276,7 @@ public class DirResourceSet extends AbstractFileResourceSet
implements WebResour
return false;
}
- File dest = null;
+ File dest;
/*
* Lock the path for writing until the write is complete. The lock
prevents concurrent reads and writes (e.g.
* HTTP GET and PUT / DELETE) for the same path causing corruption of
the FileResource where some of the fields
@@ -311,7 +311,7 @@ public class DirResourceSet extends AbstractFileResourceSet
implements WebResour
@Override
protected void checkType(File file) {
- if (file.isDirectory() == false) {
+ if (!file.isDirectory()) {
throw new IllegalArgumentException(
sm.getString("dirResourceSet.notDirectory", getBase(),
File.separator, getInternalPath()));
}
@@ -322,7 +322,7 @@ public class DirResourceSet extends AbstractFileResourceSet
implements WebResour
protected void initInternal() throws LifecycleException {
super.initInternal();
// Is this an exploded web application?
- if (getWebAppMount().equals("")) {
+ if (getWebAppMount().isEmpty()) {
// Look for a manifest
File mf = file("META-INF/MANIFEST.MF", true);
if (mf != null && mf.isFile()) {
@@ -376,7 +376,7 @@ public class DirResourceSet extends AbstractFileResourceSet
implements WebResour
@Override
public ResourceLock lockForRead(String path) {
String key = getLockKey(path);
- ResourceLock resourceLock = null;
+ ResourceLock resourceLock;
synchronized (resourceLocksByPathLock) {
/*
* Obtain the ResourceLock and increment the usage count inside
the sync to ensure that that map always has
@@ -414,7 +414,7 @@ public class DirResourceSet extends AbstractFileResourceSet
implements WebResour
@Override
public ResourceLock lockForWrite(String path) {
String key = getLockKey(path);
- ResourceLock resourceLock = null;
+ ResourceLock resourceLock;
synchronized (resourceLocksByPathLock) {
/*
* Obtain the ResourceLock and increment the usage count inside
the sync to ensure that that map always has
diff --git a/java/org/apache/catalina/webresources/ExtractingRoot.java
b/java/org/apache/catalina/webresources/ExtractingRoot.java
index 8d28381aa5..17cda81914 100644
--- a/java/org/apache/catalina/webresources/ExtractingRoot.java
+++ b/java/org/apache/catalina/webresources/ExtractingRoot.java
@@ -79,8 +79,7 @@ public class ExtractingRoot extends StandardRoot {
private File getExpansionTarget() {
File tmpDir = (File)
getContext().getServletContext().getAttribute(ServletContext.TEMPDIR);
- File expansionTarget = new File(tmpDir, APPLICATION_JARS_DIR);
- return expansionTarget;
+ return new File(tmpDir, APPLICATION_JARS_DIR);
}
diff --git a/java/org/apache/catalina/webresources/FileResourceSet.java
b/java/org/apache/catalina/webresources/FileResourceSet.java
index 035e2f7a4e..93f0aab504 100644
--- a/java/org/apache/catalina/webresources/FileResourceSet.java
+++ b/java/org/apache/catalina/webresources/FileResourceSet.java
@@ -86,7 +86,7 @@ public class FileResourceSet extends AbstractFileResourceSet {
if (webAppMount.startsWith(path)) {
String name = path.substring(0, path.length() - 1);
name = name.substring(name.lastIndexOf('/') + 1);
- if (name.length() > 0) {
+ if (!name.isEmpty()) {
return new VirtualResource(root, path, name);
}
}
@@ -160,7 +160,7 @@ public class FileResourceSet extends
AbstractFileResourceSet {
@Override
protected void checkType(File file) {
- if (file.isFile() == false) {
+ if (!file.isFile()) {
throw new IllegalArgumentException(
sm.getString("fileResourceSet.notFile", getBase(),
File.separator, getInternalPath()));
}
diff --git a/java/org/apache/catalina/webresources/StandardRoot.java
b/java/org/apache/catalina/webresources/StandardRoot.java
index 7c5c08dbea..1d95214393 100644
--- a/java/org/apache/catalina/webresources/StandardRoot.java
+++ b/java/org/apache/catalina/webresources/StandardRoot.java
@@ -147,7 +147,7 @@ public class StandardRoot extends LifecycleMBeanBase
implements WebResourceRoot
}
}
}
- if (result.size() == 0) {
+ if (result.isEmpty()) {
return null;
}
return result;
@@ -241,7 +241,7 @@ public class StandardRoot extends LifecycleMBeanBase
implements WebResourceRoot
throw new
IllegalStateException(sm.getString("standardRoot.checkStateNotStarted"));
}
- if (path == null || path.length() == 0 || !path.startsWith("/")) {
+ if (path == null || !path.startsWith("/")) {
throw new
IllegalArgumentException(sm.getString("standardRoot.invalidPath", path));
}
@@ -255,7 +255,7 @@ public class StandardRoot extends LifecycleMBeanBase
implements WebResourceRoot
// convert it to '/'
result = RequestUtil.normalize(path, false);
}
- if (result == null || result.length() == 0 || !result.startsWith("/"))
{
+ if (result == null || !result.startsWith("/")) {
throw new
IllegalArgumentException(sm.getString("standardRoot.invalidPathNormal", path,
result));
}
@@ -263,7 +263,7 @@ public class StandardRoot extends LifecycleMBeanBase
implements WebResourceRoot
}
protected final WebResource getResourceInternal(String path, boolean
useClassLoaderResources) {
- WebResource result = null;
+ WebResource result;
WebResource virtual = null;
WebResource mainEmpty = null;
for (List<WebResourceSet> list : allResources) {
@@ -322,7 +322,7 @@ public class StandardRoot extends LifecycleMBeanBase
implements WebResourceRoot
}
}
- if (result.size() == 0) {
+ if (result.isEmpty()) {
result.add(main.getResource(path));
}
@@ -676,10 +676,7 @@ public class StandardRoot extends LifecycleMBeanBase
implements WebResourceRoot
@Override
protected String getObjectNameKeyProperties() {
- StringBuilder keyProperties = new
StringBuilder("type=WebResourceRoot");
- keyProperties.append(context.getMBeanKeyProperties());
-
- return keyProperties.toString();
+ return "type=WebResourceRoot" + context.getMBeanKeyProperties();
}
// ---------------------------------------------------------------
Lifecycle
@@ -823,11 +820,11 @@ public class StandardRoot extends LifecycleMBeanBase
implements WebResourceRoot
private final String archivePath;
BaseLocation(URL url) {
- File f = null;
+ File f;
if ("jar".equals(url.getProtocol()) ||
"war".equals(url.getProtocol())) {
String jarUrl = url.toString();
- int endOfFileUrl = -1;
+ int endOfFileUrl;
if ("jar".equals(url.getProtocol())) {
endOfFileUrl = jarUrl.indexOf("!/");
} else {
diff --git a/java/org/apache/coyote/AbstractProcessorLight.java
b/java/org/apache/coyote/AbstractProcessorLight.java
index 5ff9c5f79b..bd952cedeb 100644
--- a/java/org/apache/coyote/AbstractProcessorLight.java
+++ b/java/org/apache/coyote/AbstractProcessorLight.java
@@ -33,7 +33,7 @@ import org.apache.tomcat.util.net.SocketWrapperBase;
*/
public abstract class AbstractProcessorLight implements Processor {
- private Set<DispatchType> dispatches = new CopyOnWriteArraySet<>();
+ private final Set<DispatchType> dispatches = new CopyOnWriteArraySet<>();
@Override
diff --git a/java/org/apache/coyote/AbstractProtocol.java
b/java/org/apache/coyote/AbstractProtocol.java
index bfb269da65..a500cfcb4b 100644
--- a/java/org/apache/coyote/AbstractProtocol.java
+++ b/java/org/apache/coyote/AbstractProtocol.java
@@ -672,9 +672,7 @@ public abstract class AbstractProtocol<S> implements
ProtocolHandler, MBeanRegis
}
endpoint.start();
- monitorFuture = getUtilityExecutor().scheduleWithFixedDelay(() -> {
- startAsyncTimeout();
- }, 0, 60, TimeUnit.SECONDS);
+ monitorFuture =
getUtilityExecutor().scheduleWithFixedDelay(this::startAsyncTimeout, 0, 60,
TimeUnit.SECONDS);
}
@@ -884,7 +882,7 @@ public abstract class AbstractProtocol<S> implements
ProtocolHandler, MBeanRegis
String negotiatedProtocol =
wrapper.getNegotiatedProtocol();
// OpenSSL typically returns null whereas JSSE typically
// returns "" when no protocol is negotiated
- if (negotiatedProtocol != null &&
negotiatedProtocol.length() > 0) {
+ if (negotiatedProtocol != null &&
!negotiatedProtocol.isEmpty()) {
UpgradeProtocol upgradeProtocol =
getProtocol().getNegotiatedProtocol(negotiatedProtocol);
if (upgradeProtocol != null) {
processor = upgradeProtocol.getProcessor(wrapper,
getProtocol().getAdapter());
@@ -932,7 +930,7 @@ public abstract class AbstractProtocol<S> implements
ProtocolHandler, MBeanRegis
// Can switch to non-deprecated version in Tomcat 10.1.x
processor.setSslSupport(wrapper.getSslSupport(getProtocol().getClientCertProvider()));
- SocketState state = SocketState.CLOSED;
+ SocketState state;
do {
state = processor.process(wrapper, status);
@@ -1038,7 +1036,7 @@ public abstract class AbstractProtocol<S> implements
ProtocolHandler, MBeanRegis
// Connection closed. OK to recycle the processor.
// Processors handling upgrades require additional clean-up
// before release.
- if (processor != null && processor.isUpgrade()) {
+ if (processor.isUpgrade()) {
UpgradeToken upgradeToken =
processor.getUpgradeToken();
HttpUpgradeHandler httpUpgradeHandler =
upgradeToken.getHttpUpgradeHandler();
InstanceManager instanceManager =
upgradeToken.getInstanceManager();
@@ -1246,7 +1244,7 @@ public abstract class AbstractProtocol<S> implements
ProtocolHandler, MBeanRegis
@Override
public boolean push(Processor processor) {
int cacheSize = handler.getProtocol().getProcessorCache();
- boolean offer = cacheSize == -1 ? true : size.get() < cacheSize;
+ boolean offer = cacheSize == -1 || size.get() < cacheSize;
// avoid over growing our cache or add after we have stopped
boolean result = false;
if (offer) {
diff --git a/java/org/apache/coyote/CompressionConfig.java
b/java/org/apache/coyote/CompressionConfig.java
index 1ef26d93b5..0308075ae0 100644
--- a/java/org/apache/coyote/CompressionConfig.java
+++ b/java/org/apache/coyote/CompressionConfig.java
@@ -126,7 +126,7 @@ public class CompressionConfig {
* applied
*/
public void setNoCompressionUserAgents(String noCompressionUserAgents) {
- if (noCompressionUserAgents == null ||
noCompressionUserAgents.length() == 0) {
+ if (noCompressionUserAgents == null ||
noCompressionUserAgents.isEmpty()) {
this.noCompressionUserAgents = null;
} else {
this.noCompressionUserAgents =
Pattern.compile(noCompressionUserAgents);
@@ -154,7 +154,7 @@ public class CompressionConfig {
StringTokenizer tokens = new StringTokenizer(compressibleMimeType,
",");
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken().trim();
- if (token.length() > 0) {
+ if (!token.isEmpty()) {
values.add(token);
}
}
@@ -220,8 +220,8 @@ public class CompressionConfig {
return false;
}
- boolean useTE = false;
- boolean useCE = true;
+ boolean useTransferEncoding = false;
+ boolean useContentEncoding = true;
MimeHeaders responseHeaders = response.getMimeHeaders();
@@ -241,7 +241,7 @@ public class CompressionConfig {
}
if (tokens.contains("identity")) {
// If identity, do not do content modifications
- useCE = false;
+ useContentEncoding = false;
} else if (tokens.contains("br") || tokens.contains("compress") ||
tokens.contains("dcb")
|| tokens.contains("dcz") || tokens.contains("deflate") ||
tokens.contains("gzip")
|| tokens.contains("pack200-gzip") ||
tokens.contains("zstd")) {
@@ -280,7 +280,7 @@ public class CompressionConfig {
boolean foundGzip = false;
// TE and accept-encoding seem to have equivalent syntax
while (!foundGzip && headerValues.hasMoreElements()) {
- List<TE> tes = null;
+ List<TE> tes;
try {
tes = TE.parse(new StringReader(headerValues.nextElement()));
} catch (IOException ioe) {
@@ -290,14 +290,14 @@ public class CompressionConfig {
for (TE te : tes) {
if ("gzip".equalsIgnoreCase(te.getEncoding())) {
- useTE = true;
+ useTransferEncoding = true;
foundGzip = true;
break;
}
}
}
- if (useCE && !useTE) {
+ if (useContentEncoding && !useTransferEncoding) {
// If processing reaches this far, the response might be
compressed.
// Therefore, set the Vary header to keep proxies happy
ResponseUtil.addVaryFieldName(responseHeaders, "accept-encoding");
@@ -306,9 +306,8 @@ public class CompressionConfig {
// Only interested in whether gzip encoding is supported. Other
// encodings and weights can be ignored.
headerValues = request.getMimeHeaders().values("accept-encoding");
- foundGzip = false;
while (!foundGzip && headerValues.hasMoreElements()) {
- List<AcceptEncoding> acceptEncodings = null;
+ List<AcceptEncoding> acceptEncodings;
try {
acceptEncodings = AcceptEncoding.parse(new
StringReader(headerValues.nextElement()));
} catch (IOException ioe) {
@@ -348,7 +347,7 @@ public class CompressionConfig {
// Compressed content length is unknown so mark it as such.
response.setContentLength(-1);
- if (useTE) {
+ if (useTransferEncoding) {
// Configure the transfer encoding for compressed content
responseHeaders.addValue("Transfer-Encoding").setString("gzip");
} else {
@@ -366,7 +365,7 @@ public class CompressionConfig {
* @param sArray the StringArray
* @param value string
*/
- private static boolean startsWithStringArray(String sArray[], String
value) {
+ private static boolean startsWithStringArray(String[] sArray, String
value) {
if (value == null) {
return false;
}
diff --git a/java/org/apache/coyote/Request.java
b/java/org/apache/coyote/Request.java
index 3b6f34262a..ebbfd9d7f3 100644
--- a/java/org/apache/coyote/Request.java
+++ b/java/org/apache/coyote/Request.java
@@ -104,7 +104,7 @@ public final class Request {
/**
* Notes.
*/
- private final Object notes[] = new Object[Constants.MAX_NOTES];
+ private final Object[] notes = new Object[Constants.MAX_NOTES];
/**
@@ -220,7 +220,7 @@ public final class Request {
public boolean isReady() {
// Assume read is not possible
- boolean ready = false;
+ boolean ready;
synchronized (nonBlockingStateLock) {
if (registeredForRead) {
fireListener = true;
@@ -495,7 +495,7 @@ public final class Request {
response.setRequest(this);
}
- protected void setHook(ActionHook hook) {
+ void setHook(ActionHook hook) {
this.hook = hook;
}
@@ -587,10 +587,7 @@ public final class Request {
}
public boolean getSupportsRelativeRedirects() {
- if (protocol().equals("") || protocol().equals("HTTP/1.0")) {
- return false;
- }
- return true;
+ return !protocol().equals("") && !protocol().equals("HTTP/1.0");
}
diff --git a/java/org/apache/coyote/Response.java
b/java/org/apache/coyote/Response.java
index 94fe9dea2c..6f2a856f01 100644
--- a/java/org/apache/coyote/Response.java
+++ b/java/org/apache/coyote/Response.java
@@ -92,7 +92,7 @@ public final class Response {
/**
* Notes.
*/
- final Object notes[] = new Object[Constants.MAX_NOTES];
+ final Object[] notes = new Object[Constants.MAX_NOTES];
/**
@@ -182,7 +182,7 @@ public final class Response {
}
- protected void setHook(ActionHook hook) {
+ void setHook(ActionHook hook) {
this.hook = hook;
}
@@ -566,7 +566,7 @@ public final class Response {
// There is a charset so have to rebuild content-type without it
this.contentType = m.toStringNoCharset();
charsetValue = charsetValue.trim();
- if (charsetValue.length() > 0) {
+ if (!charsetValue.isEmpty()) {
try {
charset = B2CConverter.getCharset(charsetValue);
} catch (UnsupportedEncodingException e) {
@@ -757,7 +757,7 @@ public final class Response {
return false;
}
// Assume write is not possible
- boolean ready = false;
+ boolean ready;
synchronized (nonBlockingStateLock) {
if (registeredForWrite) {
fireListener = true;
diff --git a/java/org/apache/coyote/ajp/AbstractAjpProtocol.java
b/java/org/apache/coyote/ajp/AbstractAjpProtocol.java
index 7e785affaa..3d60357e17 100644
--- a/java/org/apache/coyote/ajp/AbstractAjpProtocol.java
+++ b/java/org/apache/coyote/ajp/AbstractAjpProtocol.java
@@ -257,8 +257,7 @@ public abstract class AbstractAjpProtocol<S> extends
AbstractProtocol<S> {
@Override
protected Processor createProcessor() {
- AjpProcessor processor = new AjpProcessor(this, getAdapter());
- return processor;
+ return new AjpProcessor(this, getAdapter());
}
@@ -273,7 +272,7 @@ public abstract class AbstractAjpProtocol<S> extends
AbstractProtocol<S> {
public void start() throws Exception {
if (getSecretRequired()) {
String secret = getSecret();
- if (secret == null || secret.length() == 0) {
+ if (secret == null || secret.isEmpty()) {
throw new
IllegalArgumentException(sm.getString("ajpprotocol.noSecret"));
}
}
diff --git a/java/org/apache/coyote/ajp/AjpMessage.java
b/java/org/apache/coyote/ajp/AjpMessage.java
index 04e99aab9f..86ecdd73db 100644
--- a/java/org/apache/coyote/ajp/AjpMessage.java
+++ b/java/org/apache/coyote/ajp/AjpMessage.java
@@ -61,7 +61,7 @@ public class AjpMessage {
/**
* Fixed size buffer.
*/
- protected final byte buf[];
+ protected final byte[] buf;
/**
@@ -373,7 +373,7 @@ public class AjpMessage {
// ------------------------------------------------------ Protected Methods
- protected static String hexLine(byte buf[], int start, int len) {
+ protected static String hexLine(byte[] buf, int start, int len) {
StringBuilder sb = new StringBuilder();
for (int i = start; i < start + 16; i++) {
if (i < len + 4) {
diff --git a/java/org/apache/coyote/ajp/AjpProcessor.java
b/java/org/apache/coyote/ajp/AjpProcessor.java
index e80b34ad52..b284f5356f 100644
--- a/java/org/apache/coyote/ajp/AjpProcessor.java
+++ b/java/org/apache/coyote/ajp/AjpProcessor.java
@@ -671,7 +671,7 @@ public class AjpProcessor extends AbstractProcessor {
boolean contentLengthSet = false;
int hCount = requestHeaderMessage.getInt();
for (int i = 0; i < hCount; i++) {
- String hName = null;
+ String hName;
// Header names are encoded as either an integer code starting
// with 0xA0, or as a normal string (in which case the first
@@ -679,7 +679,7 @@ public class AjpProcessor extends AbstractProcessor {
int isc = requestHeaderMessage.peekInt();
int hId = isc & 0xFF;
- MessageBytes vMB = null;
+ MessageBytes vMB;
isc &= 0xFF00;
if (0xA000 == isc) {
requestHeaderMessage.getInt(); // To advance the read position
@@ -768,12 +768,12 @@ public class AjpProcessor extends AbstractProcessor {
case Constants.SC_A_CONTEXT:
requestHeaderMessage.getBytes(tmpMB);
- // nothing
+ // nothing
break;
case Constants.SC_A_SERVLET_PATH:
requestHeaderMessage.getBytes(tmpMB);
- // nothing
+ // nothing
break;
case Constants.SC_A_REMOTE_USER:
@@ -804,7 +804,7 @@ public class AjpProcessor extends AbstractProcessor {
case Constants.SC_A_JVM_ROUTE:
requestHeaderMessage.getBytes(tmpMB);
- // nothing
+ // nothing
break;
case Constants.SC_A_SSL_CERT:
@@ -832,7 +832,7 @@ public class AjpProcessor extends AbstractProcessor {
case Constants.SC_A_SECRET:
requestHeaderMessage.getBytes(tmpMB);
- if (secret != null && secret.length() > 0) {
+ if (secret != null && !secret.isEmpty()) {
secretPresentInRequest = true;
if (!tmpMB.equals(secret)) {
response.setStatus(403);
@@ -842,7 +842,7 @@ public class AjpProcessor extends AbstractProcessor {
break;
default:
- // Ignore unknown attribute for backward compatibility
+ // Ignore unknown attribute for backward compatibility
break;
}
@@ -850,7 +850,7 @@ public class AjpProcessor extends AbstractProcessor {
}
// Check if secret was submitted if required
- if (secret != null && secret.length() > 0 && !secretPresentInRequest) {
+ if (secret != null && !secret.isEmpty() && !secretPresentInRequest) {
response.setStatus(403);
setErrorState(ErrorState.CLOSE_CLEAN, null);
}
@@ -861,10 +861,9 @@ public class AjpProcessor extends AbstractProcessor {
int pos = uriBC.indexOf("://", 0, 3, 4);
int uriBCStart = uriBC.getStart();
- int slashPos = -1;
if (pos != -1) {
byte[] uriB = uriBC.getBytes();
- slashPos = uriBC.indexOf('/', pos + 3);
+ int slashPos = uriBC.indexOf('/', pos + 3);
if (slashPos == -1) {
slashPos = uriBC.getLength();
// Set URI as "/"
diff --git a/java/org/apache/coyote/http11/AbstractHttp11Protocol.java
b/java/org/apache/coyote/http11/AbstractHttp11Protocol.java
index 10e1f0e0fb..d8fd06ade9 100644
--- a/java/org/apache/coyote/http11/AbstractHttp11Protocol.java
+++ b/java/org/apache/coyote/http11/AbstractHttp11Protocol.java
@@ -471,7 +471,7 @@ public abstract class AbstractHttp11Protocol<S> extends
AbstractProtocol<S> {
* "gorilla|desesplorer|tigrus"
*/
public void setRestrictedUserAgents(String restrictedUserAgents) {
- if (restrictedUserAgents == null || restrictedUserAgents.length() ==
0) {
+ if (restrictedUserAgents == null || restrictedUserAgents.isEmpty()) {
this.restrictedUserAgents = null;
} else {
this.restrictedUserAgents = Pattern.compile(restrictedUserAgents);
@@ -573,7 +573,7 @@ public abstract class AbstractHttp11Protocol<S> extends
AbstractProtocol<S> {
* The names of headers that are allowed to be sent via a trailer when
using chunked encoding. They are stored in
* lower case.
*/
- private Set<String> allowedTrailerHeaders = ConcurrentHashMap.newKeySet();
+ private final Set<String> allowedTrailerHeaders =
ConcurrentHashMap.newKeySet();
public void setAllowedTrailerHeaders(String commaSeparatedHeaders) {
// Jump through some hoops so we don't end up with an empty set while
@@ -646,7 +646,7 @@ public abstract class AbstractHttp11Protocol<S> extends
AbstractProtocol<S> {
// HTTP Upgrade
String httpUpgradeName =
upgradeProtocol.getHttpUpgradeName(getEndpoint().isSSLEnabled());
boolean httpUpgradeConfigured = false;
- if (httpUpgradeName != null && httpUpgradeName.length() > 0) {
+ if (httpUpgradeName != null && !httpUpgradeName.isEmpty()) {
httpUpgradeProtocols.put(httpUpgradeName, upgradeProtocol);
httpUpgradeConfigured = true;
getLog().info(sm.getString("abstractHttp11Protocol.httpUpgradeConfigured",
getName(), httpUpgradeName));
@@ -655,7 +655,7 @@ public abstract class AbstractHttp11Protocol<S> extends
AbstractProtocol<S> {
// ALPN
String alpnName = upgradeProtocol.getAlpnName();
- if (alpnName != null && alpnName.length() > 0) {
+ if (alpnName != null && !alpnName.isEmpty()) {
if (getEndpoint().isAlpnSupported()) {
negotiatedProtocols.put(alpnName, upgradeProtocol);
getEndpoint().addNegotiatedProtocol(alpnName);
@@ -1366,8 +1366,7 @@ public abstract class AbstractHttp11Protocol<S> extends
AbstractProtocol<S> {
@Override
protected Processor createProcessor() {
- Http11Processor processor = new Http11Processor(this, adapter);
- return processor;
+ return new Http11Processor(this, adapter);
}
diff --git a/java/org/apache/coyote/http11/Http11InputBuffer.java
b/java/org/apache/coyote/http11/Http11InputBuffer.java
index 6ac98ad88d..8a11c81e0f 100644
--- a/java/org/apache/coyote/http11/Http11InputBuffer.java
+++ b/java/org/apache/coyote/http11/Http11InputBuffer.java
@@ -127,10 +127,10 @@ public class Http11InputBuffer implements InputBuffer,
ApplicationBufferHandler
private byte prevChr = 0;
private byte chr = 0;
private volatile boolean parsingRequestLine;
- private int parsingRequestLinePhase = 0;
- private boolean parsingRequestLineEol = false;
- private int parsingRequestLineStart = 0;
- private int parsingRequestLineQPos = -1;
+ private int parsingRequestLinePhase;
+ private boolean parsingRequestLineEol;
+ private int parsingRequestLineStart;
+ private int parsingRequestLineQPos;
private HeaderParsePosition headerParsePos;
private final HeaderParseData headerData = new HeaderParseData();
private final HttpParser httpParser;
@@ -140,12 +140,6 @@ public class Http11InputBuffer implements InputBuffer,
ApplicationBufferHandler
*/
private final int headerBufferSize;
- /**
- * Known size of the NioChannel read buffer.
- */
- private int socketReadBufferSize;
-
-
// ----------------------------------------------------------- Constructors
public Http11InputBuffer(Request request, int headerBufferSize, boolean
rejectIllegalHeader,
@@ -590,20 +584,12 @@ public class Http11InputBuffer implements InputBuffer,
ApplicationBufferHandler
throw new
IllegalStateException(sm.getString("iib.parseheaders.ise.error"));
}
- HeaderParseStatus status = HeaderParseStatus.HAVE_MORE_HEADERS;
+ HeaderParseStatus status;
do {
status = parseHeader();
- // Checking that
- // (1) Headers plus request line size does not exceed its limit
- // (2) There are enough bytes to avoid expanding the buffer when
- // reading body
- // Technically, (2) is technical limitation, (1) is logical
- // limitation to enforce the meaning of headerBufferSize
- // From the way how buf is allocated and how blank lines are being
- // read, it should be enough to check (1) only.
- if (byteBuffer.position() > headerBufferSize ||
- byteBuffer.capacity() - byteBuffer.position() <
socketReadBufferSize) {
+ // Checking that headers plus request line size does not exceed
its limit
+ if (byteBuffer.position() > headerBufferSize) {
throw new
IllegalArgumentException(sm.getString("iib.requestheadertoolarge.error"));
}
} while (status == HeaderParseStatus.HAVE_MORE_HEADERS);
@@ -784,7 +770,7 @@ public class Http11InputBuffer implements InputBuffer,
ApplicationBufferHandler
byteBuffer.limit(end).position(end);
}
- int nRead = -1;
+ int nRead;
int mark = byteBuffer.position();
try {
if (byteBuffer.position() < byteBuffer.limit()) {
@@ -1243,6 +1229,5 @@ public class Http11InputBuffer implements InputBuffer,
ApplicationBufferHandler
temp.put(byteBuffer);
byteBuffer = temp;
byteBuffer.mark();
- temp = null;
}
}
diff --git a/java/org/apache/coyote/http11/Http11Processor.java
b/java/org/apache/coyote/http11/Http11Processor.java
index 45042578ea..5750f71f7b 100644
--- a/java/org/apache/coyote/http11/Http11Processor.java
+++ b/java/org/apache/coyote/http11/Http11Processor.java
@@ -22,6 +22,7 @@ import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
+import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;
@@ -95,7 +96,7 @@ public class Http11Processor extends AbstractProcessor {
* Tracks how many internal filters are in the filter library so they are
skipped when looking for pluggable
* filters.
*/
- private int pluggableFilterIndex = Integer.MAX_VALUE;
+ private final int pluggableFilterIndex;
/**
@@ -453,11 +454,7 @@ public class Http11Processor extends AbstractProcessor {
if (!protocol.getDisableUploadTimeout()) {
int connectionTimeout = protocol.getConnectionTimeout();
- if (connectionTimeout > 0) {
- socketWrapper.setReadTimeout(connectionTimeout);
- } else {
- socketWrapper.setReadTimeout(0);
- }
+ socketWrapper.setReadTimeout(Math.max(connectionTimeout, 0));
}
rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE);
@@ -882,7 +879,7 @@ public class Http11Processor extends AbstractProcessor {
OutputFilter[] outputFilters = outputBuffer.getFilters();
- if (http09 == true) {
+ if (http09) {
// HTTP/0.9
outputBuffer.addActiveFilter(outputFilters[Constants.IDENTITY_FILTER]);
outputBuffer.commit();
@@ -1423,17 +1420,14 @@ public class Http11Processor extends AbstractProcessor {
sendfileData.keepAliveState = SendfileKeepAliveState.NONE;
}
result = socketWrapper.processSendfile(sendfileData);
- switch (result) {
- case ERROR:
- // Write failed
- if (log.isDebugEnabled()) {
-
log.debug(sm.getString("http11processor.sendfile.error"));
- }
- setErrorState(ErrorState.CLOSE_CONNECTION_NOW, null);
- //$FALL-THROUGH$
- default:
- sendfileData = null;
+ if (Objects.requireNonNull(result) == SendfileState.ERROR) {
+ // Write failed
+ if (log.isDebugEnabled()) {
+ log.debug(sm.getString("http11processor.sendfile.error"));
+ }
+ setErrorState(ErrorState.CLOSE_CONNECTION_NOW, null);
}
+ sendfileData = null;
}
return result;
}
diff --git a/java/org/apache/coyote/http11/filters/BufferedInputFilter.java
b/java/org/apache/coyote/http11/filters/BufferedInputFilter.java
index 455ffb882a..dfd54adb53 100644
--- a/java/org/apache/coyote/http11/filters/BufferedInputFilter.java
+++ b/java/org/apache/coyote/http11/filters/BufferedInputFilter.java
@@ -88,7 +88,7 @@ public class BufferedInputFilter implements InputFilter,
ApplicationBufferHandle
if (buffered.getLimit() == 0) {
// Special case - ignore (swallow) body. Do so within a limit.
long swallowed = 0;
- int read = 0;
+ int read;
while ((read = buffer.doRead(this)) >= 0) {
swallowed += read;
if (maxSwallowSize > -1 && swallowed > maxSwallowSize) {
diff --git a/java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
b/java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
index 429f1e2586..1be7215e76 100644
--- a/java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
+++ b/java/org/apache/coyote/http11/filters/ChunkedInputFilter.java
@@ -175,7 +175,7 @@ public class ChunkedInputFilter implements InputFilter,
ApplicationBufferHandler
@Override
public long end() throws IOException {
long swallowed = 0;
- int read = 0;
+ int read;
// Consume extra bytes : parse the stream until the end chunk is found
while ((read = doRead(this)) >= 0) {
swallowed += read;
@@ -325,8 +325,8 @@ public class ChunkedInputFilter implements InputFilter,
ApplicationBufferHandler
if (read < 0) {
// Unexpected end of stream
throwBadRequestException(sm.getString("chunkedInputFilter.invalidHeader"));
- } else if (read == 0) {
- return false;
+ } else {
+ return read != 0;
}
}
return true;
@@ -473,7 +473,7 @@ public class ChunkedInputFilter implements InputFilter,
ApplicationBufferHandler
private int parseChunkBody(ApplicationBufferHandler handler) throws
IOException {
- int result = 0;
+ int result;
if (!fill()) {
return 0;
@@ -584,7 +584,7 @@ public class ChunkedInputFilter implements InputFilter,
ApplicationBufferHandler
*/
private boolean parseTrailerFields() throws IOException {
// Handle optional trailer headers
- HeaderParseStatus status = HeaderParseStatus.HAVE_MORE_HEADERS;
+ HeaderParseStatus status;
do {
try {
status = httpHeaderParser.parseHeader();
diff --git a/java/org/apache/coyote/http11/filters/IdentityInputFilter.java
b/java/org/apache/coyote/http11/filters/IdentityInputFilter.java
index e396360a81..2a4ff3d481 100644
--- a/java/org/apache/coyote/http11/filters/IdentityInputFilter.java
+++ b/java/org/apache/coyote/http11/filters/IdentityInputFilter.java
@@ -89,7 +89,7 @@ public class IdentityInputFilter implements InputFilter,
ApplicationBufferHandle
@Override
public int doRead(ApplicationBufferHandler handler) throws IOException {
- int result = -1;
+ int result;
if (contentLength >= 0) {
if (remaining > 0) {
@@ -114,6 +114,8 @@ public class IdentityInputFilter implements InputFilter,
ApplicationBufferHandle
}
result = -1;
}
+ } else {
+ result = -1;
}
return result;
diff --git a/java/org/apache/coyote/http11/filters/IdentityOutputFilter.java
b/java/org/apache/coyote/http11/filters/IdentityOutputFilter.java
index 8c44d8552a..e83c37fd18 100644
--- a/java/org/apache/coyote/http11/filters/IdentityOutputFilter.java
+++ b/java/org/apache/coyote/http11/filters/IdentityOutputFilter.java
@@ -55,7 +55,7 @@ public class IdentityOutputFilter implements OutputFilter {
@Override
public int doWrite(ByteBuffer chunk) throws IOException {
- int result = -1;
+ int result;
if (contentLength >= 0) {
if (remaining > 0) {
diff --git a/java/org/apache/coyote/http11/filters/SavedRequestInputFilter.java
b/java/org/apache/coyote/http11/filters/SavedRequestInputFilter.java
index 9bead7331e..8e02af182d 100644
--- a/java/org/apache/coyote/http11/filters/SavedRequestInputFilter.java
+++ b/java/org/apache/coyote/http11/filters/SavedRequestInputFilter.java
@@ -32,7 +32,7 @@ public class SavedRequestInputFilter implements InputFilter {
/**
* The original request body.
*/
- protected ByteChunk input = null;
+ protected ByteChunk input;
/**
* Create a new SavedRequestInputFilter.
diff --git a/java/org/apache/coyote/http11/upgrade/UpgradeGroupInfo.java
b/java/org/apache/coyote/http11/upgrade/UpgradeGroupInfo.java
index fe64cbfea5..f05d30051b 100644
--- a/java/org/apache/coyote/http11/upgrade/UpgradeGroupInfo.java
+++ b/java/org/apache/coyote/http11/upgrade/UpgradeGroupInfo.java
@@ -29,10 +29,10 @@ public class UpgradeGroupInfo extends BaseModelMBean {
private final Set<UpgradeInfo> upgradeInfos = (new
ConcurrentHashMap<UpgradeInfo,Boolean>()).keySet(Boolean.TRUE);
- private LongAdder deadBytesReceived = new LongAdder();
- private LongAdder deadBytesSent = new LongAdder();
- private LongAdder deadMsgsReceived = new LongAdder();
- private LongAdder deadMsgsSent = new LongAdder();
+ private final LongAdder deadBytesReceived = new LongAdder();
+ private final LongAdder deadBytesSent = new LongAdder();
+ private final LongAdder deadMsgsReceived = new LongAdder();
+ private final LongAdder deadMsgsSent = new LongAdder();
public void addUpgradeInfo(UpgradeInfo ui) {
diff --git
a/java/org/apache/coyote/http11/upgrade/UpgradeServletOutputStream.java
b/java/org/apache/coyote/http11/upgrade/UpgradeServletOutputStream.java
index c41aecf624..2e44119f21 100644
--- a/java/org/apache/coyote/http11/upgrade/UpgradeServletOutputStream.java
+++ b/java/org/apache/coyote/http11/upgrade/UpgradeServletOutputStream.java
@@ -202,12 +202,8 @@ public class UpgradeServletOutputStream extends
ServletOutputStream {
* Must hold writeLock to call this method.
*/
private void writeInternal(byte[] b, int off, int len) throws IOException {
- if (listener == null) {
- // Simple case - blocking IO
- socketWrapper.write(true, b, off, len);
- } else {
- socketWrapper.write(false, b, off, len);
- }
+ // Blocking IO if no listener
+ socketWrapper.write(listener == null, b, off, len);
upgradeInfo.addBytesSent(len);
}
diff --git a/java/org/apache/coyote/http2/HPackHuffman.java
b/java/org/apache/coyote/http2/HPackHuffman.java
index e5ce4826ba..6ca431c3ae 100644
--- a/java/org/apache/coyote/http2/HPackHuffman.java
+++ b/java/org/apache/coyote/http2/HPackHuffman.java
@@ -324,11 +324,11 @@ public class HPackHuffman {
int newLength = length + 1;
HuffmanCode high = new HuffmanCode(code << 1 | 1, newLength);
HuffmanCode low = new HuffmanCode(code << 1, newLength);
- int newVal = 0;
+ int newVal;
boolean highTerminal = allCodes.remove(high);
if (highTerminal) {
// bah, linear search
- int i = 0;
+ int i;
for (i = 0; i < codes.length; ++i) {
if (codes[i].equals(high)) {
break;
@@ -344,7 +344,7 @@ public class HPackHuffman {
boolean lowTerminal = allCodes.remove(low);
if (lowTerminal) {
// bah, linear search
- int i = 0;
+ int i;
for (i = 0; i < codes.length; ++i) {
if (codes[i].equals(low)) {
break;
@@ -470,7 +470,7 @@ public class HPackHuffman {
HuffmanCode code = HUFFMAN_CODES[c];
if (code.length + bytePos <= 8) {
// it fits in the current byte
- currentBufferByte |= ((code.value & 0xFF) << 8 - (code.length
+ bytePos));
+ currentBufferByte |= (byte) ((code.value & 0xFF) << 8 -
(code.length + bytePos));
bytePos += code.length;
} else {
// it does not fit, it may need up to 4 bytes
@@ -483,9 +483,9 @@ public class HPackHuffman {
}
int remainingInByte = 8 - bytePos;
if (rem > remainingInByte) {
- currentBufferByte |= (val >> (rem - remainingInByte));
+ currentBufferByte |= (byte) (val >> (rem -
remainingInByte));
} else {
- currentBufferByte |= (val << (remainingInByte - rem));
+ currentBufferByte |= (byte) (val << (remainingInByte -
rem));
}
if (rem > remainingInByte) {
buffer.put(currentBufferByte);
@@ -563,11 +563,7 @@ public class HPackHuffman {
if (length != that.length) {
return false;
}
- if (value != that.value) {
- return false;
- }
-
- return true;
+ return value == that.value;
}
@Override
diff --git a/java/org/apache/coyote/http2/HpackDecoder.java
b/java/org/apache/coyote/http2/HpackDecoder.java
index 5257802285..6804f9efb1 100644
--- a/java/org/apache/coyote/http2/HpackDecoder.java
+++ b/java/org/apache/coyote/http2/HpackDecoder.java
@@ -61,7 +61,7 @@ public class HpackDecoder {
/**
* The maximum allowed memory size set by the container.
*/
- private int maxMemorySizeHard;
+ private final int maxMemorySizeHard;
/**
* The maximum memory size currently in use. May be less than the hard
limit.
*/
diff --git a/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java
b/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java
index bedc8788d9..e436fa6938 100644
--- a/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java
+++ b/java/org/apache/coyote/http2/Http2AsyncUpgradeHandler.java
@@ -401,8 +401,8 @@ public class Http2AsyncUpgradeHandler extends
Http2UpgradeHandler {
}
return;
}
- sendfile.streamReservation -= bytesWritten;
- sendfile.connectionReservation -= bytesWritten;
+ sendfile.streamReservation -= (int) bytesWritten;
+ sendfile.connectionReservation -= (int) bytesWritten;
sendfile.pos += bytesWritten;
try {
if (sendfile.connectionReservation == 0) {
@@ -496,7 +496,7 @@ public class Http2AsyncUpgradeHandler extends
Http2UpgradeHandler {
@Override
public void receivePing(byte[] payload, boolean ack) throws
IOException {
if (ack) {
- super.receivePing(payload, ack);
+ super.receivePing(payload, true);
} else {
// Client originated ping. Echo it back.
socketWrapper.write(BlockingMode.SEMI_BLOCK,
protocol.getWriteTimeout(), TimeUnit.MILLISECONDS, null,
diff --git a/java/org/apache/coyote/http2/Http2Protocol.java
b/java/org/apache/coyote/http2/Http2Protocol.java
index 10108cf9f0..ad06943084 100644
--- a/java/org/apache/coyote/http2/Http2Protocol.java
+++ b/java/org/apache/coyote/http2/Http2Protocol.java
@@ -113,7 +113,7 @@ public class Http2Protocol implements UpgradeProtocol {
// Reference to HTTP/1.1 protocol that this instance is configured under
private AbstractHttp11Protocol<?> http11Protocol = null;
- private RequestGroupInfo global = new RequestGroupInfo();
+ private final RequestGroupInfo global = new RequestGroupInfo();
/*
* Setting discardRequestsAndResponses can have a significant performance
impact. The magnitude of the impact is
@@ -148,11 +148,9 @@ public class Http2Protocol implements UpgradeProtocol {
@Override
public Processor getProcessor(SocketWrapperBase<?> socketWrapper, Adapter
adapter) {
- String upgradeProtocol = getUpgradeProtocolName();
- UpgradeProcessorInternal processor = new
UpgradeProcessorInternal(socketWrapper,
- new UpgradeToken(getInternalUpgradeHandler(socketWrapper,
adapter, null), null, null, upgradeProtocol),
- null);
- return processor;
+ return new UpgradeProcessorInternal(socketWrapper,
+ new UpgradeToken(getInternalUpgradeHandler(socketWrapper,
adapter, null), null,
+ null, getUpgradeProtocolName()),null);
}
@@ -366,11 +364,7 @@ public class Http2Protocol implements UpgradeProtocol {
public void setOverheadResetFactor(int overheadResetFactor) {
- if (overheadResetFactor < 0) {
- this.overheadResetFactor = 0;
- } else {
- this.overheadResetFactor = overheadResetFactor;
- }
+ this.overheadResetFactor = Math.max(overheadResetFactor, 0);
}
diff --git a/java/org/apache/coyote/http2/Http2UpgradeHandler.java
b/java/org/apache/coyote/http2/Http2UpgradeHandler.java
index 581319cb75..54e119b3f3 100644
--- a/java/org/apache/coyote/http2/Http2UpgradeHandler.java
+++ b/java/org/apache/coyote/http2/Http2UpgradeHandler.java
@@ -101,7 +101,7 @@ class Http2UpgradeHandler extends AbstractStream implements
InternalHttpUpgradeH
private volatile Http2Parser parser;
// Simple state machine (sequence of states)
- private AtomicReference<ConnectionState> connectionState = new
AtomicReference<>(ConnectionState.NEW);
+ private final AtomicReference<ConnectionState> connectionState = new
AtomicReference<>(ConnectionState.NEW);
private volatile long pausedNanoTime = Long.MAX_VALUE;
/**
@@ -152,7 +152,7 @@ class Http2UpgradeHandler extends AbstractStream implements
InternalHttpUpgradeH
// Over time the count should be a slowly decreasing negative number.
// Therefore, the longer a connection is 'well-behaved', the greater
// tolerance it will have for a period of 'bad' behaviour.
- overheadCount = new AtomicLong(-10 *
protocol.getOverheadCountFactor());
+ overheadCount = new AtomicLong(-10L *
protocol.getOverheadCountFactor());
lastNonFinalDataPayload = protocol.getOverheadDataThreshold() * 2;
lastWindowUpdate = protocol.getOverheadWindowUpdateThreshold() * 2;
@@ -1200,12 +1200,7 @@ class Http2UpgradeHandler extends AbstractStream
implements InternalHttpUpgradeH
int leftToAllocate = allocation;
if (stream.getConnectionAllocationRequested() > 0) {
- int allocatedThisTime;
- if (allocation >= stream.getConnectionAllocationRequested()) {
- allocatedThisTime =
stream.getConnectionAllocationRequested();
- } else {
- allocatedThisTime = allocation;
- }
+ int allocatedThisTime = Math.min(allocation,
stream.getConnectionAllocationRequested());
stream.setConnectionAllocationRequested(stream.getConnectionAllocationRequested()
- allocatedThisTime);
stream.setConnectionAllocationMade(stream.getConnectionAllocationMade() +
allocatedThisTime);
leftToAllocate = leftToAllocate - allocatedThisTime;
@@ -1462,7 +1457,7 @@ class Http2UpgradeHandler extends AbstractStream
implements InternalHttpUpgradeH
int len = length;
int pos = offset;
boolean nextReadBlock = block;
- int thisRead = 0;
+ int thisRead;
while (len > 0) {
// Blocking reads use the protocol level read timeout. Non-blocking
diff --git a/java/org/apache/coyote/http2/Stream.java
b/java/org/apache/coyote/http2/Stream.java
index 88cbf6d8c5..e8f0d9481c 100644
--- a/java/org/apache/coyote/http2/Stream.java
+++ b/java/org/apache/coyote/http2/Stream.java
@@ -104,7 +104,7 @@ class Stream extends AbstractNonZeroStream implements
HeaderEmitter {
private volatile StringBuilder cookieHeader = null;
private volatile boolean hostHeaderSeen = false;
- private Object pendingWindowUpdateForStreamLock = new Object();
+ private final Object pendingWindowUpdateForStreamLock = new Object();
private int pendingWindowUpdateForStream = 0;
private volatile int urgency = Priority.DEFAULT_URGENCY;
@@ -351,7 +351,7 @@ class Stream extends AbstractNonZeroStream implements
HeaderEmitter {
return;
}
- if (name.length() == 0) {
+ if (name.isEmpty()) {
throw new HpackException(sm.getString("stream.header.empty",
getConnectionId(), getIdAsString()));
}
@@ -393,7 +393,7 @@ class Stream extends AbstractNonZeroStream implements
HeaderEmitter {
throw new HpackException(
sm.getString("stream.header.duplicate",
getConnectionId(), getIdAsString(), ":path"));
}
- if (value.length() == 0) {
+ if (value.isEmpty()) {
throw new
HpackException(sm.getString("stream.header.noPath", getConnectionId(),
getIdAsString()));
}
int queryStart = value.indexOf('?');
@@ -696,10 +696,7 @@ class Stream extends AbstractNonZeroStream implements
HeaderEmitter {
final boolean isContentLengthInconsistent() {
long contentLengthHeader = coyoteRequest.getContentLengthLong();
- if (contentLengthHeader > -1 && contentLengthReceived !=
contentLengthHeader) {
- return true;
- }
- return false;
+ return contentLengthHeader > -1 && contentLengthReceived !=
contentLengthHeader;
}
@@ -1145,12 +1142,8 @@ class Stream extends AbstractNonZeroStream implements
HeaderEmitter {
// Bug 63682
// Only want to return false if the window size is zero AND we
are
// already waiting for an allocation.
- if (getWindowSize() > 0 &&
allocationManager.isWaitingForStream() ||
- handler.getWindowSize() > 0 &&
allocationManager.isWaitingForConnection() || dataLeft) {
- return false;
- } else {
- return true;
- }
+ return (getWindowSize() <= 0 ||
!allocationManager.isWaitingForStream()) &&
+ (handler.getWindowSize() <= 0 ||
!allocationManager.isWaitingForConnection()) && !dataLeft;
} finally {
writeLock.unlock();
}
@@ -1281,7 +1274,7 @@ class Stream extends AbstractNonZeroStream implements
HeaderEmitter {
ensureBuffersExist();
- int written = -1;
+ int written;
// It is still possible that the stream has been closed and
inBuffer
// set to null between the call to ensureBuffersExist() above and
@@ -1547,7 +1540,7 @@ class Stream extends AbstractNonZeroStream implements
HeaderEmitter {
readStateLock.unlock();
}
if (inBuffer != null) {
- int unreadByteCount = 0;
+ int unreadByteCount;
synchronized (inBuffer) {
unreadByteCount = inBuffer.position();
if (log.isTraceEnabled()) {
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]