This is an automated email from the ASF dual-hosted git repository. remm pushed a commit to branch main in repository https://gitbox.apache.org/repos/asf/tomcat.git
The following commit(s) were added to refs/heads/main by this push: new 61565f283b Code cleanup, no functional change 61565f283b is described below commit 61565f283b11a7db6636e13391ec2f6c0ae3f916 Author: remm <r...@apache.org> AuthorDate: Thu Mar 13 11:42:31 2025 +0100 Code cleanup, no functional change --- java/org/apache/catalina/connector/Connector.java | 4 +- java/org/apache/catalina/connector/Request.java | 15 +- java/org/apache/catalina/connector/Response.java | 14 +- .../org/apache/catalina/core/AccessLogAdapter.java | 2 +- .../apache/catalina/core/ApplicationContext.java | 22 +- .../catalina/core/ApplicationContextFacade.java | 46 +-- .../catalina/core/ApplicationDispatcher.java | 35 +-- .../catalina/core/ApplicationFilterConfig.java | 14 +- .../catalina/core/ApplicationFilterFactory.java | 4 +- .../catalina/core/ApplicationHttpRequest.java | 24 +- .../apache/catalina/core/ApplicationRequest.java | 2 +- .../core/ApplicationSessionCookieConfig.java | 2 +- .../apache/catalina/core/AprLifecycleListener.java | 4 +- .../org/apache/catalina/core/AsyncContextImpl.java | 8 +- java/org/apache/catalina/core/ContainerBase.java | 14 +- .../catalina/core/DefaultInstanceManager.java | 38 +-- .../catalina/core/NamingContextListener.java | 308 +++++++++++---------- java/org/apache/catalina/core/StandardContext.java | 155 +++++------ java/org/apache/catalina/core/StandardHost.java | 20 +- .../apache/catalina/core/StandardHostValve.java | 7 +- .../org/apache/catalina/core/StandardPipeline.java | 2 +- java/org/apache/catalina/core/StandardServer.java | 6 +- java/org/apache/catalina/core/StandardService.java | 15 +- java/org/apache/catalina/core/StandardWrapper.java | 38 +-- .../apache/catalina/core/StandardWrapperValve.java | 4 +- 25 files changed, 365 insertions(+), 438 deletions(-) diff --git a/java/org/apache/catalina/connector/Connector.java b/java/org/apache/catalina/connector/Connector.java index 7947cf0e06..05a43a12e6 100644 --- a/java/org/apache/catalina/connector/Connector.java +++ b/java/org/apache/catalina/connector/Connector.java @@ -661,7 +661,7 @@ public class Connector extends LifecycleMBeanBase { */ public void setProxyName(String proxyName) { - if (proxyName != null && proxyName.length() > 0) { + if (proxyName != null && !proxyName.isEmpty()) { this.proxyName = proxyName; } else { this.proxyName = null; @@ -975,7 +975,7 @@ public class Connector extends LifecycleMBeanBase { } else if (addressObj != null) { address = addressObj.toString(); } - if (address.length() > 0) { + if (!address.isEmpty()) { sb.append(",address="); sb.append(ObjectName.quote(address)); } diff --git a/java/org/apache/catalina/connector/Request.java b/java/org/apache/catalina/connector/Request.java index ee7817d962..a53f7bc719 100644 --- a/java/org/apache/catalina/connector/Request.java +++ b/java/org/apache/catalina/connector/Request.java @@ -35,6 +35,7 @@ import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; @@ -1034,7 +1035,7 @@ public class Request implements HttpServletRequest { parseLocales(); } - if (locales.size() > 0) { + if (!locales.isEmpty()) { return locales.get(0); } @@ -1049,7 +1050,7 @@ public class Request implements HttpServletRequest { parseLocales(); } - if (locales.size() > 0) { + if (!locales.isEmpty()) { return Collections.enumeration(locales); } ArrayList<Locale> results = new ArrayList<>(); @@ -1582,11 +1583,7 @@ public class Request implements HttpServletRequest { @Override public DispatcherType getDispatcherType() { - if (internalDispatcherType == null) { - return DispatcherType.REQUEST; - } - - return this.internalDispatcherType; + return Objects.requireNonNullElse(internalDispatcherType, DispatcherType.REQUEST); } @@ -2315,7 +2312,7 @@ public class Request implements HttpServletRequest { public void changeSessionId(String newSessionId) { // This should only ever be called if there was an old session ID but // double check to be sure - if (requestedSessionId != null && requestedSessionId.length() > 0) { + if (requestedSessionId != null && !requestedSessionId.isEmpty()) { requestedSessionId = newSessionId; } @@ -2454,7 +2451,7 @@ public class Request implements HttpServletRequest { File location; String locationStr = mce.getLocation(); - if (locationStr == null || locationStr.length() == 0) { + if (locationStr == null || locationStr.isEmpty()) { location = ((File) context.getServletContext().getAttribute(ServletContext.TEMPDIR)); } else { // If relative, it is relative to TEMPDIR diff --git a/java/org/apache/catalina/connector/Response.java b/java/org/apache/catalina/connector/Response.java index 23369f0f7c..2ec1d12adc 100644 --- a/java/org/apache/catalina/connector/Response.java +++ b/java/org/apache/catalina/connector/Response.java @@ -854,7 +854,7 @@ public class Response implements HttpServletResponse { @Override public void addDateHeader(String name, long value) { - if (name == null || name.length() == 0) { + if (name == null || name.isEmpty()) { return; } @@ -879,7 +879,7 @@ public class Response implements HttpServletResponse { private void addHeader(String name, String value, Charset charset) { - if (name == null || name.length() == 0 || value == null) { + if (name == null || name.isEmpty() || value == null) { return; } @@ -922,7 +922,7 @@ public class Response implements HttpServletResponse { @Override public void addIntHeader(String name, int value) { - if (name == null || name.length() == 0) { + if (name == null || name.isEmpty()) { return; } @@ -1149,7 +1149,7 @@ public class Response implements HttpServletResponse { @Override public void setDateHeader(String name, long value) { - if (name == null || name.length() == 0) { + if (name == null || name.isEmpty()) { return; } @@ -1169,7 +1169,7 @@ public class Response implements HttpServletResponse { @Override public void setHeader(String name, String value) { - if (name == null || name.length() == 0) { + if (name == null || name.isEmpty()) { return; } @@ -1196,7 +1196,7 @@ public class Response implements HttpServletResponse { @Override public void setIntHeader(String name, int value) { - if (name == null || name.length() == 0) { + if (name == null || name.isEmpty()) { return; } @@ -1535,7 +1535,7 @@ public class Response implements HttpServletResponse { path = path.substring(0, pound); } StringBuilder sb = new StringBuilder(path); - if (sb.length() > 0) { // jsessionid can't be first. + if (!sb.isEmpty()) { // jsessionid can't be first. sb.append(';'); sb.append(SessionConfig.getSessionUriParamName(request.getContext())); sb.append('='); diff --git a/java/org/apache/catalina/core/AccessLogAdapter.java b/java/org/apache/catalina/core/AccessLogAdapter.java index 8a107a4409..666b058fd8 100644 --- a/java/org/apache/catalina/core/AccessLogAdapter.java +++ b/java/org/apache/catalina/core/AccessLogAdapter.java @@ -37,7 +37,7 @@ public class AccessLogAdapter implements AccessLog { public void add(AccessLog log) { Objects.requireNonNull(log); - AccessLog newArray[] = Arrays.copyOf(logs, logs.length + 1); + AccessLog[] newArray = Arrays.copyOf(logs, logs.length + 1); newArray[newArray.length - 1] = log; logs = newArray; } diff --git a/java/org/apache/catalina/core/ApplicationContext.java b/java/org/apache/catalina/core/ApplicationContext.java index 5fc0ea14e0..247f861af9 100644 --- a/java/org/apache/catalina/core/ApplicationContext.java +++ b/java/org/apache/catalina/core/ApplicationContext.java @@ -161,7 +161,7 @@ public class ApplicationContext implements ServletContext { /** * Session Cookie config */ - private SessionCookieConfig sessionCookieConfig; + private final SessionCookieConfig sessionCookieConfig; /** * Session tracking modes @@ -200,7 +200,7 @@ public class ApplicationContext implements ServletContext { return null; } - Context child = null; + Context child; try { // Look for an exact match Container host = context.getParent(); @@ -464,7 +464,7 @@ public class ApplicationContext implements ServletContext { if (nextSemiColon < 0) { nextSemiColon = limit; } - sb.append(input.substring(pos, nextSemiColon)); + sb.append(input, pos, nextSemiColon); int followingSlash = input.indexOf('/', nextSemiColon); if (followingSlash < 0) { pos = limit; @@ -580,20 +580,18 @@ public class ApplicationContext implements ServletContext { @Override public void removeAttribute(String name) { - Object value = null; - // Remove the specified attribute // Check for read only attribute if (readOnlyAttributes.containsKey(name)) { return; } - value = attributes.remove(name); + Object value = attributes.remove(name); if (value == null) { return; } // Notify interested application event listeners - Object listeners[] = context.getApplicationEventListeners(); + Object[] listeners = context.getApplicationEventListeners(); if (listeners == null || listeners.length == 0) { return; } @@ -639,11 +637,11 @@ public class ApplicationContext implements ServletContext { boolean replaced = oldValue != null; // Notify interested application event listeners - Object listeners[] = context.getApplicationEventListeners(); + Object[] listeners = context.getApplicationEventListeners(); if (listeners == null || listeners.length == 0) { return; } - ServletContextAttributeEvent event = null; + ServletContextAttributeEvent event; if (replaced) { event = new ServletContextAttributeEvent(context.getServletContext(), name, oldValue); } else { @@ -699,7 +697,7 @@ public class ApplicationContext implements ServletContext { private FilterRegistration.Dynamic addFilter(String filterName, String filterClass, Filter filter) throws IllegalStateException { - if (filterName == null || filterName.equals("")) { + if (filterName == null || filterName.isEmpty()) { throw new IllegalArgumentException(sm.getString("applicationContext.invalidFilterName", filterName)); } @@ -782,11 +780,11 @@ public class ApplicationContext implements ServletContext { throw new IllegalArgumentException(sm.getString("applicationContext.addJspFile.iae", jspFile)); } - String jspServletClassName = null; Map<String,String> jspFileInitParams = new HashMap<>(); Wrapper jspServlet = (Wrapper) context.findChild("jsp"); + String jspServletClassName; if (jspServlet == null) { // No JSP servlet currently defined. // Use default JSP Servlet class name @@ -812,7 +810,7 @@ public class ApplicationContext implements ServletContext { private ServletRegistration.Dynamic addServlet(String servletName, String servletClass, Servlet servlet, Map<String,String> initParams) throws IllegalStateException { - if (servletName == null || servletName.equals("")) { + if (servletName == null || servletName.isEmpty()) { throw new IllegalArgumentException(sm.getString("applicationContext.invalidServletName", servletName)); } diff --git a/java/org/apache/catalina/core/ApplicationContextFacade.java b/java/org/apache/catalina/core/ApplicationContextFacade.java index 24678d8782..e8c6f5208d 100644 --- a/java/org/apache/catalina/core/ApplicationContextFacade.java +++ b/java/org/apache/catalina/core/ApplicationContextFacade.java @@ -22,7 +22,6 @@ import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import java.util.EventListener; -import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -46,12 +45,6 @@ import jakarta.servlet.descriptor.JspConfigDescriptor; */ public class ApplicationContextFacade implements ServletContext { - // ---------------------------------------------------------- Attributes - /** - * Cache Class object used for reflection. - */ - private final Map<String,Class<?>[]> classCache; - // ----------------------------------------------------------- Constructors @@ -63,43 +56,6 @@ public class ApplicationContextFacade implements ServletContext { public ApplicationContextFacade(ApplicationContext context) { super(); this.context = context; - - classCache = new HashMap<>(); - initClassCache(); - } - - - private void initClassCache() { - Class<?>[] clazz = new Class[] { String.class }; - classCache.put("getContext", clazz); - classCache.put("getMimeType", clazz); - classCache.put("getResourcePaths", clazz); - classCache.put("getResource", clazz); - classCache.put("getResourceAsStream", clazz); - classCache.put("getRequestDispatcher", clazz); - classCache.put("getNamedDispatcher", clazz); - classCache.put("getServlet", clazz); - classCache.put("setInitParameter", new Class[] { String.class, String.class }); - classCache.put("createServlet", new Class[] { Class.class }); - classCache.put("addServlet", new Class[] { String.class, String.class }); - classCache.put("createFilter", new Class[] { Class.class }); - classCache.put("addFilter", new Class[] { String.class, String.class }); - classCache.put("createListener", new Class[] { Class.class }); - classCache.put("addListener", clazz); - classCache.put("getFilterRegistration", clazz); - classCache.put("getServletRegistration", clazz); - classCache.put("getInitParameter", clazz); - classCache.put("setAttribute", new Class[] { String.class, Object.class }); - classCache.put("removeAttribute", clazz); - classCache.put("getRealPath", clazz); - classCache.put("getAttribute", clazz); - classCache.put("log", clazz); - classCache.put("setSessionTrackingModes", new Class[] { Set.class }); - classCache.put("addJspFile", new Class[] { String.class, String.class }); - classCache.put("declareRoles", new Class[] { String[].class }); - classCache.put("setSessionTimeout", new Class[] { int.class }); - classCache.put("setRequestCharacterEncoding", new Class[] { String.class }); - classCache.put("setResponseCharacterEncoding", new Class[] { String.class }); } @@ -118,7 +74,7 @@ public class ApplicationContextFacade implements ServletContext { @Override public ServletContext getContext(String uripath) { ServletContext theContext = context.getContext(uripath); - if ((theContext != null) && (theContext instanceof ApplicationContext)) { + if ((theContext instanceof ApplicationContext)) { theContext = ((ApplicationContext) theContext).getFacade(); } return theContext; diff --git a/java/org/apache/catalina/core/ApplicationDispatcher.java b/java/org/apache/catalina/core/ApplicationDispatcher.java index 7bd141bcfd..ea2c3ecf8e 100644 --- a/java/org/apache/catalina/core/ApplicationDispatcher.java +++ b/java/org/apache/catalina/core/ApplicationDispatcher.java @@ -72,13 +72,13 @@ final class ApplicationDispatcher implements AsyncDispatcher, RequestDispatcher /** * The outermost request that will be passed on to the invoked servlet. */ - ServletRequest outerRequest = null; + ServletRequest outerRequest; /** * The outermost response that will be passed on to the invoked servlet. */ - ServletResponse outerResponse = null; + ServletResponse outerResponse; /** * The request wrapper we have created and installed (if any). @@ -94,7 +94,7 @@ final class ApplicationDispatcher implements AsyncDispatcher, RequestDispatcher /** * Are we performing an include() instead of a forward()? */ - boolean including = false; + boolean including; /** * Outermost HttpServletRequest in the chain @@ -205,11 +205,7 @@ final class ApplicationDispatcher implements AsyncDispatcher, RequestDispatcher if (response.isCommitted()) { throw new IllegalStateException(sm.getString("applicationDispatcher.forward.ise")); } - try { - response.resetBuffer(); - } catch (IllegalStateException e) { - throw e; - } + response.resetBuffer(); // Set up to handle the specified request and response State state = new State(request, response, false); @@ -340,13 +336,7 @@ final class ApplicationDispatcher implements AsyncDispatcher, RequestDispatcher DispatcherType disInt = (DispatcherType) request.getAttribute(Globals.DISPATCHER_TYPE_ATTR); if (disInt != null) { - boolean doInvoke = true; - - if (context.getFireRequestListenersOnForwards() && !context.fireRequestInitEvent(request)) { - doInvoke = false; - } - - if (doInvoke) { + if (!context.getFireRequestListenersOnForwards() || context.fireRequestInitEvent(request)) { if (disInt != DispatcherType.ERROR) { state.outerRequest.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR, getCombinedPath()); state.outerRequest.setAttribute(Globals.DISPATCHER_TYPE_ATTR, DispatcherType.FORWARD); @@ -526,7 +516,7 @@ final class ApplicationDispatcher implements AsyncDispatcher, RequestDispatcher wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); servletException = new ServletException(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e); - servlet = null; + // servlet = null; is already done so no need to do it explicitly } // Get the FilterChain Here @@ -716,14 +706,12 @@ final class ApplicationDispatcher implements AsyncDispatcher, RequestDispatcher } // Instantiate a new wrapper at this point and insert it in the chain - ServletRequest wrapper = null; - if (current instanceof ApplicationHttpRequest || current instanceof Request || - current instanceof HttpServletRequest) { + ServletRequest wrapper; + if (current instanceof HttpServletRequest) { // Compute a crossContext flag HttpServletRequest hcurrent = (HttpServletRequest) current; boolean crossContext = false; - if (state.outerRequest instanceof ApplicationHttpRequest || state.outerRequest instanceof Request || - state.outerRequest instanceof HttpServletRequest) { + if (state.outerRequest instanceof HttpServletRequest) { HttpServletRequest houterRequest = (HttpServletRequest) state.outerRequest; Object contextPath = houterRequest.getAttribute(INCLUDE_CONTEXT_PATH); if (contextPath == null) { @@ -776,9 +764,8 @@ final class ApplicationDispatcher implements AsyncDispatcher, RequestDispatcher } // Instantiate a new wrapper at this point and insert it in the chain - ServletResponse wrapper = null; - if (current instanceof ApplicationHttpResponse || current instanceof Response || - current instanceof HttpServletResponse) { + ServletResponse wrapper; + if (current instanceof HttpServletResponse) { wrapper = new ApplicationHttpResponse((HttpServletResponse) current, state.including); } else { wrapper = new ApplicationResponse(current, state.including); diff --git a/java/org/apache/catalina/core/ApplicationFilterConfig.java b/java/org/apache/catalina/core/ApplicationFilterConfig.java index a9daf99055..11bf17c12e 100644 --- a/java/org/apache/catalina/core/ApplicationFilterConfig.java +++ b/java/org/apache/catalina/core/ApplicationFilterConfig.java @@ -176,13 +176,11 @@ public final class ApplicationFilterConfig implements FilterConfig, Serializable @Override public String toString() { - StringBuilder sb = new StringBuilder("ApplicationFilterConfig["); - sb.append("name="); - sb.append(filterDef.getFilterName()); - sb.append(", filterClass="); - sb.append(filterDef.getFilterClass()); - sb.append(']'); - return sb.toString(); + return "ApplicationFilterConfig[" + "name=" + + filterDef.getFilterName() + + ", filterClass=" + + filterDef.getFilterClass() + + ']'; } // --------------------------------------------------------- Public Methods @@ -298,7 +296,7 @@ public final class ApplicationFilterConfig implements FilterConfig, Serializable String domain = context.getParent().getParent().getName(); String webMod = "//" + hostName + parentName; - String onameStr = null; + String onameStr; String filterName = filterDef.getFilterName(); if (Util.objectNameValueNeedsQuote(filterName)) { filterName = ObjectName.quote(filterName); diff --git a/java/org/apache/catalina/core/ApplicationFilterFactory.java b/java/org/apache/catalina/core/ApplicationFilterFactory.java index 052717e4e1..1dab020978 100644 --- a/java/org/apache/catalina/core/ApplicationFilterFactory.java +++ b/java/org/apache/catalina/core/ApplicationFilterFactory.java @@ -62,7 +62,7 @@ public final class ApplicationFilterFactory { } // Create and initialize a filter chain object - ApplicationFilterChain filterChain = null; + ApplicationFilterChain filterChain; if (request instanceof Request) { Request req = (Request) request; filterChain = (ApplicationFilterChain) req.getFilterChain(); @@ -81,7 +81,7 @@ public final class ApplicationFilterFactory { // Acquire the filter mappings for this Context StandardContext context = (StandardContext) wrapper.getParent(); filterChain.setDispatcherWrapsSameObject(context.getDispatcherWrapsSameObject()); - FilterMap filterMaps[] = context.findFilterMaps(); + FilterMap[] filterMaps = context.findFilterMaps(); // If there are no filter mappings, we are done if (filterMaps == null || filterMaps.length == 0) { diff --git a/java/org/apache/catalina/core/ApplicationHttpRequest.java b/java/org/apache/catalina/core/ApplicationHttpRequest.java index ce3baffd17..7bf411cc2f 100644 --- a/java/org/apache/catalina/core/ApplicationHttpRequest.java +++ b/java/org/apache/catalina/core/ApplicationHttpRequest.java @@ -70,7 +70,7 @@ class ApplicationHttpRequest extends HttpServletRequestWrapper { /** * The set of attribute names that are special for request dispatchers. */ - protected static final String specials[] = + protected static final String[] specials = { RequestDispatcher.INCLUDE_REQUEST_URI, RequestDispatcher.INCLUDE_CONTEXT_PATH, RequestDispatcher.INCLUDE_SERVLET_PATH, RequestDispatcher.INCLUDE_PATH_INFO, RequestDispatcher.INCLUDE_QUERY_STRING, RequestDispatcher.INCLUDE_MAPPING, @@ -89,7 +89,7 @@ class ApplicationHttpRequest extends HttpServletRequestWrapper { } private static final int shortestSpecialNameLength = - specialsMap.keySet().stream().mapToInt(s -> s.length()).min().getAsInt(); + specialsMap.keySet().stream().mapToInt(String::length).min().getAsInt(); private static final int SPECIALS_FIRST_FORWARD_INDEX = 6; @@ -346,7 +346,7 @@ class ApplicationHttpRequest extends HttpServletRequestWrapper { // Add the path info, if there is any String pathInfo = getPathInfo(); - String requestPath = null; + String requestPath; if (pathInfo == null) { requestPath = servletPath; @@ -355,7 +355,7 @@ class ApplicationHttpRequest extends HttpServletRequestWrapper { } int pos = requestPath.lastIndexOf('/'); - String relative = null; + String relative; if (context.getDispatchersUseEncodedPaths()) { if (pos >= 0) { relative = URLEncoder.DEFAULT.encode(requestPath.substring(0, pos + 1), StandardCharsets.UTF_8) + path; @@ -605,11 +605,7 @@ class ApplicationHttpRequest extends HttpServletRequestWrapper { } catch (IOException e) { // Ignore } - if ((session != null) && session.isValid()) { - return true; - } else { - return false; - } + return (session != null) && session.isValid(); } else { return super.isRequestedSessionIdValid(); @@ -833,17 +829,13 @@ class ApplicationHttpRequest extends HttpServletRequestWrapper { */ private String[] mergeValues(String[] values1, String[] values2) { - List<Object> results = new ArrayList<>(); + List<String> results = new ArrayList<>(); - if (values1 == null) { - // Skip - nothing to merge - } else { + if (values1 != null) { results.addAll(Arrays.asList(values1)); } - if (values2 == null) { - // Skip - nothing to merge - } else { + if (values2 != null) { results.addAll(Arrays.asList(values2)); } diff --git a/java/org/apache/catalina/core/ApplicationRequest.java b/java/org/apache/catalina/core/ApplicationRequest.java index 80d9a8b19c..db4ecfe870 100644 --- a/java/org/apache/catalina/core/ApplicationRequest.java +++ b/java/org/apache/catalina/core/ApplicationRequest.java @@ -50,7 +50,7 @@ class ApplicationRequest extends ServletRequestWrapper { RequestDispatcher.FORWARD_QUERY_STRING, RequestDispatcher.FORWARD_MAPPING)); private static final int shortestSpecialNameLength = - specialsSet.stream().mapToInt(s -> s.length()).min().getAsInt(); + specialsSet.stream().mapToInt(String::length).min().getAsInt(); /** diff --git a/java/org/apache/catalina/core/ApplicationSessionCookieConfig.java b/java/org/apache/catalina/core/ApplicationSessionCookieConfig.java index 732e843d20..f0fd66cb5a 100644 --- a/java/org/apache/catalina/core/ApplicationSessionCookieConfig.java +++ b/java/org/apache/catalina/core/ApplicationSessionCookieConfig.java @@ -43,7 +43,7 @@ public class ApplicationSessionCookieConfig implements SessionCookieConfig { private final Map<String,String> attributes = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); private String name; - private StandardContext context; + private final StandardContext context; public ApplicationSessionCookieConfig(StandardContext context) { this.context = context; diff --git a/java/org/apache/catalina/core/AprLifecycleListener.java b/java/org/apache/catalina/core/AprLifecycleListener.java index 665d15ff6a..3841001ca2 100644 --- a/java/org/apache/catalina/core/AprLifecycleListener.java +++ b/java/org/apache/catalina/core/AprLifecycleListener.java @@ -276,9 +276,9 @@ public class AprLifecycleListener implements LifecycleListener { sslInitialized = true; String methodName = "randSet"; - Class<?> paramTypes[] = new Class[1]; + Class<?>[] paramTypes = new Class[1]; paramTypes[0] = String.class; - Object paramValues[] = new Object[1]; + Object[] paramValues = new Object[1]; paramValues[0] = SSLRandomSeed; Class<?> clazz = Class.forName("org.apache.tomcat.jni.SSL"); Method method = clazz.getMethod(methodName, paramTypes); diff --git a/java/org/apache/catalina/core/AsyncContextImpl.java b/java/org/apache/catalina/core/AsyncContextImpl.java index ffae5e77b6..893c362a8c 100644 --- a/java/org/apache/catalina/core/AsyncContextImpl.java +++ b/java/org/apache/catalina/core/AsyncContextImpl.java @@ -255,16 +255,14 @@ public class AsyncContextImpl implements AsyncContext, AsyncContextCallback { @Override public <T extends AsyncListener> T createListener(Class<T> clazz) throws ServletException { check(); - T listener = null; + T listener; try { listener = (T) context.getInstanceManager().newInstance(clazz.getName(), clazz.getClassLoader()); } catch (ReflectiveOperationException | NamingException e) { - ServletException se = new ServletException(e); - throw se; + throw new ServletException(e); } catch (Exception e) { ExceptionUtils.handleThrowable(e.getCause()); - ServletException se = new ServletException(e); - throw se; + throw new ServletException(e); } return listener; } diff --git a/java/org/apache/catalina/core/ContainerBase.java b/java/org/apache/catalina/core/ContainerBase.java index 1a3220f52c..6711a60e01 100644 --- a/java/org/apache/catalina/core/ContainerBase.java +++ b/java/org/apache/catalina/core/ContainerBase.java @@ -289,7 +289,7 @@ public abstract class ContainerBase extends LifecycleMBeanBase implements Contai Container current = this; while (current != null) { String name = current.getName(); - if ((name == null) || (name.equals(""))) { + if ((name == null) || (name.isEmpty())) { name = "/"; } else if (name.startsWith("##")) { name = "/" + name; @@ -340,7 +340,7 @@ public abstract class ContainerBase extends LifecycleMBeanBase implements Contai @Override public void setCluster(Cluster cluster) { - Cluster oldCluster = null; + Cluster oldCluster; Lock writeLock = clusterLock.writeLock(); writeLock.lock(); try { @@ -495,7 +495,7 @@ public abstract class ContainerBase extends LifecycleMBeanBase implements Contai @Override public void setRealm(Realm realm) { - Realm oldRealm = null; + Realm oldRealm; Lock l = realmLock.writeLock(); l.lock(); try { @@ -968,7 +968,7 @@ public abstract class ContainerBase extends LifecycleMBeanBase implements Contai @Override public void fireContainerEvent(String type, Object data) { - if (listeners.size() < 1) { + if (listeners.isEmpty()) { return; } @@ -1089,7 +1089,7 @@ public abstract class ContainerBase extends LifecycleMBeanBase implements Contai StringBuilder sb = new StringBuilder(); Container parent = getParent(); if (parent != null) { - sb.append(parent.toString()); + sb.append(parent); sb.append('.'); } sb.append(this.getClass().getSimpleName()); @@ -1159,7 +1159,7 @@ public abstract class ContainerBase extends LifecycleMBeanBase implements Contai private static class StartChild implements Callable<Void> { - private Container child; + private final Container child; StartChild(Container child) { this.child = child; @@ -1174,7 +1174,7 @@ public abstract class ContainerBase extends LifecycleMBeanBase implements Contai private static class StopChild implements Callable<Void> { - private Container child; + private final Container child; StopChild(Container child) { this.child = child; diff --git a/java/org/apache/catalina/core/DefaultInstanceManager.java b/java/org/apache/catalina/core/DefaultInstanceManager.java index c0fe2c6f73..f99fe2400a 100644 --- a/java/org/apache/catalina/core/DefaultInstanceManager.java +++ b/java/org/apache/catalina/core/DefaultInstanceManager.java @@ -166,7 +166,7 @@ public class DefaultInstanceManager implements InstanceManager { private Map<String,String> assembleInjectionsFromClassHierarchy(Class<?> clazz) { Map<String,String> injections = new HashMap<>(); - Map<String,String> currentInjections = null; + Map<String,String> currentInjections; while (clazz != null) { currentInjections = this.injectionMap.get(clazz.getName()); if (currentInjections != null) { @@ -308,30 +308,30 @@ public class DefaultInstanceManager implements InstanceManager { } if (!metadataComplete) { Resource resourceAnnotation; - Annotation ejbAnnotation; - Annotation webServiceRefAnnotation; - Annotation persistenceContextAnnotation; - Annotation persistenceUnitAnnotation; + EJB ejbAnnotation; + WebServiceRef webServiceRefAnnotation; + PersistenceContext persistenceContextAnnotation; + PersistenceUnit persistenceUnitAnnotation; if ((resourceAnnotation = method.getAnnotation(Resource.class)) != null) { annotations.add(new AnnotationCacheEntry(method.getName(), method.getParameterTypes(), resourceAnnotation.name(), AnnotationCacheEntryType.SETTER)); } else if (EJB_PRESENT && (ejbAnnotation = method.getAnnotation(EJB.class)) != null) { annotations.add(new AnnotationCacheEntry(method.getName(), method.getParameterTypes(), - ((EJB) ejbAnnotation).name(), AnnotationCacheEntryType.SETTER)); + ejbAnnotation.name(), AnnotationCacheEntryType.SETTER)); } else if (WS_PRESENT && (webServiceRefAnnotation = method.getAnnotation(WebServiceRef.class)) != null) { annotations.add(new AnnotationCacheEntry(method.getName(), method.getParameterTypes(), - ((WebServiceRef) webServiceRefAnnotation).name(), + webServiceRefAnnotation.name(), AnnotationCacheEntryType.SETTER)); } else if (JPA_PRESENT && (persistenceContextAnnotation = method.getAnnotation(PersistenceContext.class)) != null) { annotations.add(new AnnotationCacheEntry(method.getName(), method.getParameterTypes(), - ((PersistenceContext) persistenceContextAnnotation).name(), + persistenceContextAnnotation.name(), AnnotationCacheEntryType.SETTER)); } else if (JPA_PRESENT && (persistenceUnitAnnotation = method.getAnnotation(PersistenceUnit.class)) != null) { annotations.add(new AnnotationCacheEntry(method.getName(), method.getParameterTypes(), - ((PersistenceUnit) persistenceUnitAnnotation).name(), + persistenceUnitAnnotation.name(), AnnotationCacheEntryType.SETTER)); } } @@ -363,10 +363,10 @@ public class DefaultInstanceManager implements InstanceManager { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { Resource resourceAnnotation; - Annotation ejbAnnotation; - Annotation webServiceRefAnnotation; - Annotation persistenceContextAnnotation; - Annotation persistenceUnitAnnotation; + EJB ejbAnnotation; + WebServiceRef webServiceRefAnnotation; + PersistenceContext persistenceContextAnnotation; + PersistenceUnit persistenceUnitAnnotation; String fieldName = field.getName(); if (injections != null && injections.containsKey(fieldName) && !injectionsMatchedToSetter.contains(fieldName)) { @@ -377,22 +377,22 @@ public class DefaultInstanceManager implements InstanceManager { annotations.add(new AnnotationCacheEntry(fieldName, null, resourceAnnotation.name(), AnnotationCacheEntryType.FIELD)); } else if (EJB_PRESENT && (ejbAnnotation = field.getAnnotation(EJB.class)) != null) { - annotations.add(new AnnotationCacheEntry(fieldName, null, ((EJB) ejbAnnotation).name(), + annotations.add(new AnnotationCacheEntry(fieldName, null, ejbAnnotation.name(), AnnotationCacheEntryType.FIELD)); } else if (WS_PRESENT && (webServiceRefAnnotation = field.getAnnotation(WebServiceRef.class)) != null) { annotations.add(new AnnotationCacheEntry(fieldName, null, - ((WebServiceRef) webServiceRefAnnotation).name(), + webServiceRefAnnotation.name(), AnnotationCacheEntryType.FIELD)); } else if (JPA_PRESENT && (persistenceContextAnnotation = field.getAnnotation(PersistenceContext.class)) != null) { annotations.add(new AnnotationCacheEntry(fieldName, null, - ((PersistenceContext) persistenceContextAnnotation).name(), + persistenceContextAnnotation.name(), AnnotationCacheEntryType.FIELD)); } else if (JPA_PRESENT && (persistenceUnitAnnotation = field.getAnnotation(PersistenceUnit.class)) != null) { annotations.add(new AnnotationCacheEntry(fieldName, null, - ((PersistenceUnit) persistenceUnitAnnotation).name(), + persistenceUnitAnnotation.name(), AnnotationCacheEntryType.FIELD)); } } @@ -514,7 +514,7 @@ public class DefaultInstanceManager implements InstanceManager { String normalizedName = normalize(name); - if ((normalizedName != null) && (normalizedName.length() > 0)) { + if ((normalizedName != null) && (!normalizedName.isEmpty())) { lookedupResource = context.lookup(normalizedName); } else { lookedupResource = context.lookup(clazz.getName() + "/" + field.getName()); @@ -551,7 +551,7 @@ public class DefaultInstanceManager implements InstanceManager { String normalizedName = normalize(name); - if ((normalizedName != null) && (normalizedName.length() > 0)) { + if ((normalizedName != null) && (!normalizedName.isEmpty())) { lookedupResource = context.lookup(normalizedName); } else { lookedupResource = context.lookup(clazz.getName() + "/" + Introspection.getPropertyName(method)); diff --git a/java/org/apache/catalina/core/NamingContextListener.java b/java/org/apache/catalina/core/NamingContextListener.java index 2dd9b0ea10..f0880fd163 100644 --- a/java/org/apache/catalina/core/NamingContextListener.java +++ b/java/org/apache/catalina/core/NamingContextListener.java @@ -360,110 +360,119 @@ public class NamingContextListener implements LifecycleListener, PropertyChangeL */ private void processGlobalResourcesChange(String name, Object oldValue, Object newValue) { - if (name.equals("ejb")) { - if (oldValue != null) { - ContextEjb ejb = (ContextEjb) oldValue; - if (ejb.getName() != null) { - removeEjb(ejb.getName()); + switch (name) { + case "ejb": + if (oldValue != null) { + ContextEjb ejb = (ContextEjb) oldValue; + if (ejb.getName() != null) { + removeEjb(ejb.getName()); + } } - } - if (newValue != null) { - ContextEjb ejb = (ContextEjb) newValue; - if (ejb.getName() != null) { - addEjb(ejb); + if (newValue != null) { + ContextEjb ejb = (ContextEjb) newValue; + if (ejb.getName() != null) { + addEjb(ejb); + } } - } - } else if (name.equals("environment")) { - if (oldValue != null) { - ContextEnvironment env = (ContextEnvironment) oldValue; - if (env.getName() != null) { - removeEnvironment(env.getName()); + break; + case "environment": + if (oldValue != null) { + ContextEnvironment env = (ContextEnvironment) oldValue; + if (env.getName() != null) { + removeEnvironment(env.getName()); + } } - } - if (newValue != null) { - ContextEnvironment env = (ContextEnvironment) newValue; - if (env.getName() != null) { - addEnvironment(env); + if (newValue != null) { + ContextEnvironment env = (ContextEnvironment) newValue; + if (env.getName() != null) { + addEnvironment(env); + } } - } - } else if (name.equals("localEjb")) { - if (oldValue != null) { - ContextLocalEjb ejb = (ContextLocalEjb) oldValue; - if (ejb.getName() != null) { - removeLocalEjb(ejb.getName()); + break; + case "localEjb": + if (oldValue != null) { + ContextLocalEjb ejb = (ContextLocalEjb) oldValue; + if (ejb.getName() != null) { + removeLocalEjb(ejb.getName()); + } } - } - if (newValue != null) { - ContextLocalEjb ejb = (ContextLocalEjb) newValue; - if (ejb.getName() != null) { - addLocalEjb(ejb); + if (newValue != null) { + ContextLocalEjb ejb = (ContextLocalEjb) newValue; + if (ejb.getName() != null) { + addLocalEjb(ejb); + } } - } - } else if (name.equals("messageDestinationRef")) { - if (oldValue != null) { - MessageDestinationRef mdr = (MessageDestinationRef) oldValue; - if (mdr.getName() != null) { - removeMessageDestinationRef(mdr.getName()); + break; + case "messageDestinationRef": + if (oldValue != null) { + MessageDestinationRef mdr = (MessageDestinationRef) oldValue; + if (mdr.getName() != null) { + removeMessageDestinationRef(mdr.getName()); + } } - } - if (newValue != null) { - MessageDestinationRef mdr = (MessageDestinationRef) newValue; - if (mdr.getName() != null) { - addMessageDestinationRef(mdr); + if (newValue != null) { + MessageDestinationRef mdr = (MessageDestinationRef) newValue; + if (mdr.getName() != null) { + addMessageDestinationRef(mdr); + } } - } - } else if (name.equals("resource")) { - if (oldValue != null) { - ContextResource resource = (ContextResource) oldValue; - if (resource.getName() != null) { - removeResource(resource.getName()); + break; + case "resource": + if (oldValue != null) { + ContextResource resource = (ContextResource) oldValue; + if (resource.getName() != null) { + removeResource(resource.getName()); + } } - } - if (newValue != null) { - ContextResource resource = (ContextResource) newValue; - if (resource.getName() != null) { - addResource(resource); + if (newValue != null) { + ContextResource resource = (ContextResource) newValue; + if (resource.getName() != null) { + addResource(resource); + } } - } - } else if (name.equals("resourceEnvRef")) { - if (oldValue != null) { - ContextResourceEnvRef resourceEnvRef = (ContextResourceEnvRef) oldValue; - if (resourceEnvRef.getName() != null) { - removeResourceEnvRef(resourceEnvRef.getName()); + break; + case "resourceEnvRef": + if (oldValue != null) { + ContextResourceEnvRef resourceEnvRef = (ContextResourceEnvRef) oldValue; + if (resourceEnvRef.getName() != null) { + removeResourceEnvRef(resourceEnvRef.getName()); + } } - } - if (newValue != null) { - ContextResourceEnvRef resourceEnvRef = (ContextResourceEnvRef) newValue; - if (resourceEnvRef.getName() != null) { - addResourceEnvRef(resourceEnvRef); + if (newValue != null) { + ContextResourceEnvRef resourceEnvRef = (ContextResourceEnvRef) newValue; + if (resourceEnvRef.getName() != null) { + addResourceEnvRef(resourceEnvRef); + } } - } - } else if (name.equals("resourceLink")) { - if (oldValue != null) { - ContextResourceLink rl = (ContextResourceLink) oldValue; - if (rl.getName() != null) { - removeResourceLink(rl.getName()); + break; + case "resourceLink": + if (oldValue != null) { + ContextResourceLink rl = (ContextResourceLink) oldValue; + if (rl.getName() != null) { + removeResourceLink(rl.getName()); + } } - } - if (newValue != null) { - ContextResourceLink rl = (ContextResourceLink) newValue; - if (rl.getName() != null) { - addResourceLink(rl); + if (newValue != null) { + ContextResourceLink rl = (ContextResourceLink) newValue; + if (rl.getName() != null) { + addResourceLink(rl); + } } - } - } else if (name.equals("service")) { - if (oldValue != null) { - ContextService service = (ContextService) oldValue; - if (service.getName() != null) { - removeService(service.getName()); + break; + case "service": + if (oldValue != null) { + ContextService service = (ContextService) oldValue; + if (service.getName() != null) { + removeService(service.getName()); + } } - } - if (newValue != null) { - ContextService service = (ContextService) newValue; - if (service.getName() != null) { - addService(service); + if (newValue != null) { + ContextService service = (ContextService) newValue; + if (service.getName() != null) { + addService(service); + } } - } + break; } @@ -658,61 +667,72 @@ public class NamingContextListener implements LifecycleListener, PropertyChangeL // initializing it. String type = env.getType(); try { - if (type.equals("java.lang.String")) { - value = env.getValue(); - } else if (type.equals("java.lang.Byte")) { - if (env.getValue() == null) { - value = Byte.valueOf((byte) 0); - } else { - value = Byte.decode(env.getValue()); - } - } else if (type.equals("java.lang.Short")) { - if (env.getValue() == null) { - value = Short.valueOf((short) 0); - } else { - value = Short.decode(env.getValue()); - } - } else if (type.equals("java.lang.Integer")) { - if (env.getValue() == null) { - value = Integer.valueOf(0); - } else { - value = Integer.decode(env.getValue()); - } - } else if (type.equals("java.lang.Long")) { - if (env.getValue() == null) { - value = Long.valueOf(0); - } else { - value = Long.decode(env.getValue()); - } - } else if (type.equals("java.lang.Boolean")) { - value = Boolean.valueOf(env.getValue()); - } else if (type.equals("java.lang.Double")) { - if (env.getValue() == null) { - value = Double.valueOf(0); - } else { - value = Double.valueOf(env.getValue()); - } - } else if (type.equals("java.lang.Float")) { - if (env.getValue() == null) { - value = Float.valueOf(0); - } else { - value = Float.valueOf(env.getValue()); - } - } else if (type.equals("java.lang.Character")) { - if (env.getValue() == null) { - value = Character.valueOf((char) 0); - } else { - if (env.getValue().length() == 1) { - value = Character.valueOf(env.getValue().charAt(0)); + switch (type) { + case "java.lang.String": + value = env.getValue(); + break; + case "java.lang.Byte": + if (env.getValue() == null) { + value = Byte.valueOf((byte) 0); } else { - throw new IllegalArgumentException(); + value = Byte.decode(env.getValue()); } - } - } else { - value = constructEnvEntry(env.getType(), env.getValue()); - if (value == null) { - log.error(sm.getString("naming.invalidEnvEntryType", env.getName())); - } + break; + case "java.lang.Short": + if (env.getValue() == null) { + value = Short.valueOf((short) 0); + } else { + value = Short.decode(env.getValue()); + } + break; + case "java.lang.Integer": + if (env.getValue() == null) { + value = Integer.valueOf(0); + } else { + value = Integer.decode(env.getValue()); + } + break; + case "java.lang.Long": + if (env.getValue() == null) { + value = Long.valueOf(0); + } else { + value = Long.decode(env.getValue()); + } + break; + case "java.lang.Boolean": + value = Boolean.valueOf(env.getValue()); + break; + case "java.lang.Double": + if (env.getValue() == null) { + value = Double.valueOf(0); + } else { + value = Double.valueOf(env.getValue()); + } + break; + case "java.lang.Float": + if (env.getValue() == null) { + value = Float.valueOf(0); + } else { + value = Float.valueOf(env.getValue()); + } + break; + case "java.lang.Character": + if (env.getValue() == null) { + value = Character.valueOf((char) 0); + } else { + if (env.getValue().length() == 1) { + value = Character.valueOf(env.getValue().charAt(0)); + } else { + throw new IllegalArgumentException(); + } + } + break; + default: + value = constructEnvEntry(env.getType(), env.getValue()); + if (value == null) { + log.error(sm.getString("naming.invalidEnvEntryType", env.getName())); + } + break; } } catch (IllegalArgumentException e) { log.error(sm.getString("naming.invalidEnvEntryValue", env.getName())); @@ -737,7 +757,7 @@ public class NamingContextListener implements LifecycleListener, PropertyChangeL private Object constructEnvEntry(String type, String value) { try { Class<?> clazz = Class.forName(type); - Constructor<?> c = null; + Constructor<?> c; try { c = clazz.getConstructor(String.class); return c.newInstance(value); @@ -1197,7 +1217,7 @@ public class NamingContextListener implements LifecycleListener, PropertyChangeL StringTokenizer tokenizer = new StringTokenizer(name, "/"); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); - if ((!token.equals("")) && (tokenizer.hasMoreTokens())) { + if ((!token.isEmpty()) && (tokenizer.hasMoreTokens())) { try { currentContext = currentContext.createSubcontext(token); } catch (NamingException e) { @@ -1219,7 +1239,7 @@ public class NamingContextListener implements LifecycleListener, PropertyChangeL */ private LookupRef lookForLookupRef(ResourceBase resourceBase) { String lookupName = resourceBase.getLookupName(); - if ((lookupName != null && !lookupName.equals(""))) { + if ((lookupName != null && !lookupName.isEmpty())) { return new LookupRef(resourceBase.getType(), lookupName); } return null; diff --git a/java/org/apache/catalina/core/StandardContext.java b/java/org/apache/catalina/core/StandardContext.java index b7ebe63eca..f1c1aa1623 100644 --- a/java/org/apache/catalina/core/StandardContext.java +++ b/java/org/apache/catalina/core/StandardContext.java @@ -36,6 +36,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; +import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; @@ -201,7 +202,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat * The list of unique application listener class names configured for this application, in the order they were * encountered in the resulting merged web.xml file. */ - private CopyOnWriteArrayList<String> applicationListeners = new CopyOnWriteArrayList<>(); + private final CopyOnWriteArrayList<String> applicationListeners = new CopyOnWriteArrayList<>(); /** * The set of application listeners that are required to have limited access to ServletContext methods. See Servlet @@ -213,26 +214,26 @@ public class StandardContext extends ContainerBase implements Context, Notificat * The list of instantiated application event listener objects. Note that SCIs and other code may use the * pluggability APIs to add listener instances directly to this list before the application starts. */ - private List<Object> applicationEventListenersList = new CopyOnWriteArrayList<>(); + private final List<Object> applicationEventListenersList = new CopyOnWriteArrayList<>(); /** * The set of instantiated application lifecycle listener objects. Note that SCIs and other code may use the * pluggability APIs to add listener instances directly to this list before the application starts. */ - private Object applicationLifecycleListenersObjects[] = new Object[0]; + private Object[] applicationLifecycleListenersObjects = new Object[0]; /** * The ordered set of ServletContainerInitializers for this web application. */ - private Map<ServletContainerInitializer,Set<Class<?>>> initializers = new LinkedHashMap<>(); + private final Map<ServletContainerInitializer,Set<Class<?>>> initializers = new LinkedHashMap<>(); /** * The set of application parameters defined for this application. */ - private ApplicationParameter applicationParameters[] = new ApplicationParameter[0]; + private ApplicationParameter[] applicationParameters = new ApplicationParameter[0]; private final Object applicationParametersLock = new Object(); @@ -240,7 +241,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat /** * The broadcaster that sends j2ee notifications. */ - private NotificationBroadcasterSupport broadcaster = null; + private final NotificationBroadcasterSupport broadcaster; /** * The Locale to character set mapper for this application. @@ -269,7 +270,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat /** * The security constraints for this web application. */ - private volatile SecurityConstraint constraints[] = new SecurityConstraint[0]; + private volatile SecurityConstraint[] constraints = new SecurityConstraint[0]; private final Object constraintsLock = new Object(); @@ -356,13 +357,13 @@ public class StandardContext extends ContainerBase implements Context, Notificat /** * The set of filter configurations (and associated filter instances) we have initialized, keyed by filter name. */ - private Map<String,ApplicationFilterConfig> filterConfigs = new HashMap<>(); // Guarded by filterDefs + private final Map<String,ApplicationFilterConfig> filterConfigs = new HashMap<>(); // Guarded by filterDefs /** * The set of filter definitions for this application, keyed by filter name. */ - private Map<String,FilterDef> filterDefs = new HashMap<>(); + private final Map<String,FilterDef> filterDefs = new HashMap<>(); /** @@ -418,13 +419,13 @@ public class StandardContext extends ContainerBase implements Context, Notificat /** * The message destinations for this web application. */ - private HashMap<String,MessageDestination> messageDestinations = new HashMap<>(); + private final HashMap<String,MessageDestination> messageDestinations = new HashMap<>(); /** * The MIME mappings for this web application, keyed by extension. */ - private Map<String,String> mimeMappings = new HashMap<>(); + private final Map<String,String> mimeMappings = new HashMap<>(); /** @@ -493,13 +494,13 @@ public class StandardContext extends ContainerBase implements Context, Notificat /** * The security role mappings for this application, keyed by role name (as used within the application). */ - private Map<String,String> roleMappings = new HashMap<>(); + private final Map<String,String> roleMappings = new HashMap<>(); /** * The security roles for this application, keyed by role name. */ - private String securityRoles[] = new String[0]; + private String[] securityRoles = new String[0]; private final Object securityRolesLock = new Object(); @@ -507,7 +508,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat /** * The servlet mappings for this web application, keyed by matching pattern. */ - private Map<String,String> servletMappings = new HashMap<>(); + private final Map<String,String> servletMappings = new HashMap<>(); private final Object servletMappingsLock = new Object(); @@ -520,7 +521,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat /** * The notification sequence number. */ - private AtomicLong sequenceNumber = new AtomicLong(0); + private final AtomicLong sequenceNumber = new AtomicLong(0); /** @@ -538,7 +539,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat /** * The watched resources for this application. */ - private String watchedResources[] = new String[0]; + private String[] watchedResources = new String[0]; private final Object watchedResourcesLock = new Object(); @@ -546,7 +547,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat /** * The welcome files for this application. */ - private String welcomeFiles[] = new String[0]; + private String[] welcomeFiles = new String[0]; private final Object welcomeFilesLock = new Object(); @@ -555,7 +556,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat * The set of classnames of LifecycleListeners that will be added to each newly created Wrapper by * <code>createWrapper()</code>. */ - private String wrapperLifecycles[] = new String[0]; + private String[] wrapperLifecycles = new String[0]; private final Object wrapperLifecyclesLock = new Object(); @@ -563,7 +564,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat * The set of classnames of ContainerListeners that will be added to each newly created Wrapper by * <code>createWrapper()</code>. */ - private String wrapperListeners[] = new String[0]; + private String[] wrapperListeners = new String[0]; private final Object wrapperListenersLock = new Object(); @@ -728,7 +729,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat private JspConfigDescriptor jspConfigDescriptor = null; - private Set<String> resourceOnlyServlets = new HashSet<>(); + private final Set<String> resourceOnlyServlets = new HashSet<>(); private String webappVersion = ""; @@ -739,7 +740,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat /** * Servlets created via {@link ApplicationContext#createServlet(Class)} for tracking purposes. */ - private Set<Servlet> createdServlets = new HashSet<>(); + private final Set<Servlet> createdServlets = new HashSet<>(); private boolean preemptiveAuthentication = false; @@ -747,8 +748,8 @@ public class StandardContext extends ContainerBase implements Context, Notificat private boolean jndiExceptionOnFailedWrite = true; - private Map<String,String> postConstructMethods = new HashMap<>(); - private Map<String,String> preDestroyMethods = new HashMap<>(); + private final Map<String,String> postConstructMethods = new HashMap<>(); + private final Map<String,String> preDestroyMethods = new HashMap<>(); private String containerSciFilter; @@ -1144,11 +1145,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat @Override public void setWebappVersion(String webappVersion) { - if (null == webappVersion) { - this.webappVersion = ""; - } else { - this.webappVersion = webappVersion; - } + this.webappVersion = Objects.requireNonNullElse(webappVersion, ""); } @@ -1178,7 +1175,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat } for (String servletName : resourceOnlyServlets.split(",")) { servletName = servletName.trim(); - if (servletName.length() > 0) { + if (!servletName.isEmpty()) { this.resourceOnlyServlets.add(servletName); } } @@ -1360,7 +1357,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat * result may be either set of listeners or a the union of both. */ @Override - public void setApplicationEventListeners(Object listeners[]) { + public void setApplicationEventListeners(Object[] listeners) { applicationEventListenersList.clear(); if (listeners != null && listeners.length > 0) { applicationEventListenersList.addAll(Arrays.asList(listeners)); @@ -1385,7 +1382,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat @Override - public void setApplicationLifecycleListeners(Object listeners[]) { + public void setApplicationLifecycleListeners(Object[] listeners) { applicationLifecycleListenersObjects = listeners; } @@ -1792,7 +1789,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat Lock writeLock = loaderLock.writeLock(); writeLock.lock(); - Loader oldLoader = null; + Loader oldLoader; try { // Change components if necessary oldLoader = this.loader; @@ -1847,7 +1844,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat Lock writeLock = managerLock.writeLock(); writeLock.lock(); - Manager oldManager = null; + Manager oldManager; try { // Change components if necessary oldManager = this.manager; @@ -2343,7 +2340,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat Lock writeLock = resourcesLock.writeLock(); writeLock.lock(); - WebResourceRoot oldResources = null; + WebResourceRoot oldResources; try { if (getState().isAvailable()) { throw new IllegalStateException(sm.getString("standardContext.resourcesStart")); @@ -2634,7 +2631,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat return; } } - ApplicationParameter results[] = Arrays.copyOf(applicationParameters, applicationParameters.length + 1); + ApplicationParameter[] results = Arrays.copyOf(applicationParameters, applicationParameters.length + 1); results[applicationParameters.length] = parameter; applicationParameters = results; } @@ -2682,9 +2679,9 @@ public class StandardContext extends ContainerBase implements Context, Notificat public void addConstraint(SecurityConstraint constraint) { // Validate the proposed constraint - SecurityCollection collections[] = constraint.findCollections(); + SecurityCollection[] collections = constraint.findCollections(); for (SecurityCollection collection : collections) { - String patterns[] = collection.findPatterns(); + String[] patterns = collection.findPatterns(); for (int j = 0; j < patterns.length; j++) { patterns[j] = adjustURLPattern(patterns[j]); if (!validateURLPattern(patterns[j])) { @@ -2949,7 +2946,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat @Override public Wrapper createWrapper() { - Wrapper wrapper = null; + Wrapper wrapper; if (wrapperClass != null) { try { wrapper = (Wrapper) wrapperClass.getConstructor().newInstance(); @@ -3069,7 +3066,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat /** - * @return the set of defined message destinations for this web application. If none have been defined, a + * @return the array of defined message destinations for this web application. If none have been defined, a * zero-length array is returned. */ public MessageDestination[] findMessageDestinations() { @@ -3107,7 +3104,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat @Override public String findRoleMapping(String role) { - String realRole = null; + String realRole; synchronized (roleMappings) { realRole = roleMappings.get(role); } @@ -3278,7 +3275,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat // Remove the specified parameter int j = 0; - ApplicationParameter results[] = new ApplicationParameter[applicationParameters.length - 1]; + ApplicationParameter[] results = new ApplicationParameter[applicationParameters.length - 1]; for (int i = 0; i < applicationParameters.length; i++) { if (i != n) { results[j++] = applicationParameters[i]; @@ -3325,7 +3322,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat // Remove the specified constraint int j = 0; - SecurityConstraint results[] = new SecurityConstraint[constraints.length - 1]; + SecurityConstraint[] results = new SecurityConstraint[constraints.length - 1]; for (int i = 0; i < constraints.length; i++) { if (i != n) { results[j++] = constraints[i]; @@ -3430,7 +3427,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat // Remove the specified security role int j = 0; - String results[] = new String[securityRoles.length - 1]; + String[] results = new String[securityRoles.length - 1]; for (int i = 0; i < securityRoles.length; i++) { if (i != n) { results[j++] = securityRoles[i]; @@ -3449,7 +3446,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat @Override public void removeServletMapping(String pattern) { - String name = null; + String name; synchronized (servletMappingsLock) { name = servletMappings.remove(pattern); } @@ -3480,7 +3477,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat // Remove the specified watched resource int j = 0; - String results[] = new String[watchedResources.length - 1]; + String[] results = new String[watchedResources.length - 1]; for (int i = 0; i < watchedResources.length; i++) { if (i != n) { results[j++] = watchedResources[i]; @@ -3514,7 +3511,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat // Remove the specified welcome file int j = 0; - String results[] = new String[welcomeFiles.length - 1]; + String[] results = new String[welcomeFiles.length - 1]; for (int i = 0; i < welcomeFiles.length; i++) { if (i != n) { results[j++] = welcomeFiles[i]; @@ -3552,7 +3549,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat // Remove the specified lifecycle listener int j = 0; - String results[] = new String[wrapperLifecycles.length - 1]; + String[] results = new String[wrapperLifecycles.length - 1]; for (int i = 0; i < wrapperLifecycles.length; i++) { if (i != n) { results[j++] = wrapperLifecycles[i]; @@ -3588,7 +3585,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat // Remove the specified listener int j = 0; - String results[] = new String[wrapperListeners.length - 1]; + String[] results = new String[wrapperListeners.length - 1]; for (int i = 0; i < wrapperListeners.length; i++) { if (i != n) { results[j++] = wrapperListeners[i]; @@ -3788,7 +3785,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat */ public void add(FilterMap filterMap) { synchronized (lock) { - FilterMap results[] = Arrays.copyOf(array, array.length + 1); + FilterMap[] results = Arrays.copyOf(array, array.length + 1); results[array.length] = filterMap; array = results; } @@ -3802,7 +3799,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat */ public void addBefore(FilterMap filterMap) { synchronized (lock) { - FilterMap results[] = new FilterMap[array.length + 1]; + FilterMap[] results = new FilterMap[array.length + 1]; System.arraycopy(array, 0, results, 0, insertPoint); System.arraycopy(array, insertPoint, results, insertPoint + 1, array.length - insertPoint); results[insertPoint] = filterMap; @@ -3831,7 +3828,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat } // Remove the specified filter mapping - FilterMap results[] = new FilterMap[array.length - 1]; + FilterMap[] results = new FilterMap[array.length - 1]; System.arraycopy(array, 0, results, 0, n); System.arraycopy(array, n + 1, results, n, (array.length - 1) - n); array = results; @@ -3934,8 +3931,8 @@ public class StandardContext extends ContainerBase implements Context, Notificat } // Instantiate the required listeners - String listeners[] = findApplicationListeners(); - Object results[] = new Object[listeners.length]; + String[] listeners = findApplicationListeners(); + Object[] results = new Object[listeners.length]; boolean ok = true; for (int i = 0; i < results.length; i++) { if (getLogger().isTraceEnabled()) { @@ -3995,14 +3992,14 @@ public class StandardContext extends ContainerBase implements Context, Notificat getServletContext(); context.setNewServletContextListenerAllowed(false); - Object instances[] = getApplicationLifecycleListeners(); + Object[] instances = getApplicationLifecycleListeners(); if (instances == null || instances.length == 0) { return ok; } ServletContextEvent event = new ServletContextEvent(getServletContext()); ServletContextEvent tldEvent = null; - if (noPluggabilityListeners.size() > 0) { + if (!noPluggabilityListeners.isEmpty()) { noPluggabilityServletContext = new NoPluggabilityServletContext(getServletContext()); tldEvent = new ServletContextEvent(noPluggabilityServletContext); } @@ -4043,7 +4040,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat } boolean ok = true; - Object listeners[] = getApplicationLifecycleListeners(); + Object[] listeners = getApplicationLifecycleListeners(); if (listeners != null && listeners.length > 0) { ServletContextEvent event = new ServletContextEvent(getServletContext()); ServletContextEvent tldEvent = null; @@ -4173,7 +4170,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat * * @return <code>true</code> if load on startup was considered successful */ - public boolean loadOnStartup(Container children[]) { + public boolean loadOnStartup(Container[] children) { // Collect "load on startup" servlets that need to be initialized TreeMap<Integer,ArrayList<Wrapper>> map = new TreeMap<>(); @@ -4575,7 +4572,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat private void addInjectionTarget(Injectable resource, Map<String,Map<String,String>> injectionMap) { List<InjectionTarget> injectionTargets = resource.getInjectionTargets(); - if (injectionTargets != null && injectionTargets.size() > 0) { + if (injectionTargets != null && !injectionTargets.isEmpty()) { String jndiName = resource.getName(); for (InjectionTarget injectionTarget : injectionTargets) { String clazz = injectionTarget.getTargetClass(); @@ -4594,12 +4591,12 @@ public class StandardContext extends ContainerBase implements Context, Notificat private void mergeParameters() { Map<String,String> mergedParams = new HashMap<>(); - String names[] = findParameters(); + String[] names = findParameters(); for (String s : names) { mergedParams.put(s, findParameter(s)); } - ApplicationParameter params[] = findApplicationParameters(); + ApplicationParameter[] params = findApplicationParameters(); for (ApplicationParameter param : params) { if (param.getOverride()) { mergedParams.computeIfAbsent(param.getName(), k -> param.getValue()); @@ -4877,7 +4874,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat protected String adjustURLPattern(String urlPattern) { if (urlPattern == null) { - return urlPattern; + return null; } if (urlPattern.startsWith("/") || urlPattern.startsWith("*.")) { return urlPattern; @@ -5130,7 +5127,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat @Override public boolean fireRequestInitEvent(ServletRequest request) { - Object instances[] = getApplicationEventListeners(); + Object[] instances = getApplicationEventListeners(); if ((instances != null) && (instances.length > 0)) { @@ -5163,7 +5160,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat @Override public boolean fireRequestDestroyEvent(ServletRequest request) { - Object instances[] = getApplicationEventListeners(); + Object[] instances = getApplicationEventListeners(); if ((instances != null) && (instances.length > 0)) { @@ -5267,7 +5264,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat // Acquire (or calculate) the work directory path String workDir = getWorkDir(); - if (workDir == null || workDir.length() == 0) { + if (workDir == null || workDir.isEmpty()) { // Retrieve our parent (normally a host) name String hostName = null; @@ -5284,10 +5281,10 @@ public class StandardContext extends ContainerBase implements Context, Notificat engineName = parentEngine.getName(); } } - if ((hostName == null) || (hostName.length() < 1)) { + if ((hostName == null) || (hostName.isEmpty())) { hostName = "_"; } - if ((engineName == null) || (engineName.length() < 1)) { + if ((engineName == null) || (engineName.isEmpty())) { engineName = "_"; } @@ -5297,7 +5294,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat } temp = temp.replace('/', '_'); temp = temp.replace('\\', '_'); - if (temp.length() < 1) { + if (temp.isEmpty()) { temp = ContextName.ROOT_NAME; } if (hostWorkDir != null) { @@ -5316,7 +5313,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat catalinaHomePath = getCatalinaBase().getCanonicalPath(); dir = new File(catalinaHomePath, workDir); } catch (IOException e) { - log.warn(sm.getString("standardContext.workCreateException", workDir, catalinaHomePath, getName()), e); + log.warn(sm.getString("standardContext.workCreateException", workDir, getCatalinaBase(), getName()), e); } } if (!dir.mkdirs() && !dir.isDirectory()) { @@ -5360,7 +5357,7 @@ public class StandardContext extends ContainerBase implements Context, Notificat if (urlPattern.indexOf('\n') >= 0 || urlPattern.indexOf('\r') >= 0) { return false; } - if (urlPattern.equals("")) { + if (urlPattern.isEmpty()) { return true; } if (urlPattern.startsWith("*.")) { @@ -5401,25 +5398,17 @@ public class StandardContext extends ContainerBase implements Context, Notificat @Override protected String getObjectNameKeyProperties() { - - StringBuilder keyProperties = new StringBuilder("j2eeType=WebModule,"); - keyProperties.append(getObjectKeyPropertiesNameOnly()); - keyProperties.append(",J2EEApplication="); - keyProperties.append(getJ2EEApplication()); - keyProperties.append(",J2EEServer="); - keyProperties.append(getJ2EEServer()); - - return keyProperties.toString(); + return "j2eeType=WebModule," + getObjectKeyPropertiesNameOnly() + + ",J2EEApplication=" + + getJ2EEApplication() + + ",J2EEServer=" + + getJ2EEServer(); } private String getObjectKeyPropertiesNameOnly() { StringBuilder result = new StringBuilder("name=//"); String hostname = getParent().getName(); - if (hostname == null) { - result.append("DEFAULT"); - } else { - result.append(hostname); - } + result.append(Objects.requireNonNullElse(hostname, "DEFAULT")); String contextName = getName(); if (!contextName.startsWith("/")) { diff --git a/java/org/apache/catalina/core/StandardHost.java b/java/org/apache/catalina/core/StandardHost.java index c8008ddc50..c57929b009 100644 --- a/java/org/apache/catalina/core/StandardHost.java +++ b/java/org/apache/catalina/core/StandardHost.java @@ -238,7 +238,7 @@ public class StandardHost extends ContainerBase implements Host { @Override public void setAppBase(String appBase) { - if (appBase.trim().equals("")) { + if (appBase.trim().isEmpty()) { log.warn(sm.getString("standardHost.problematicAppBase", getName())); } String oldAppBase = this.appBase; @@ -281,7 +281,7 @@ public class StandardHost extends ContainerBase implements Host { @Override public void setLegacyAppBase(String legacyAppBase) { - if (legacyAppBase.trim().equals("")) { + if (legacyAppBase.trim().isEmpty()) { log.warn(sm.getString("standardHost.problematicLegacyAppBase", getName())); } String oldLegacyAppBase = this.legacyAppBase; @@ -310,7 +310,7 @@ public class StandardHost extends ContainerBase implements Host { if (hostConfigBase != null) { return hostConfigBase; } - String path = null; + String path; if (getXmlBase() != null) { path = getXmlBase(); } else { @@ -618,7 +618,7 @@ public class StandardHost extends ContainerBase implements Host { } } // Add this alias to the list - String newAliases[] = Arrays.copyOf(aliases, aliases.length + 1); + String[] newAliases = Arrays.copyOf(aliases, aliases.length + 1); newAliases[aliases.length] = alias; aliases = newAliases; } @@ -678,7 +678,7 @@ public class StandardHost extends ContainerBase implements Host { * reload. Note: This method attempts to force a full garbage collection. This should be used with extreme caution * on a production system. * - * @return a list of possibly leaking contexts + * @return an array of possibly leaking contexts */ public String[] findReloadedContextMemoryLeaks() { @@ -727,7 +727,7 @@ public class StandardHost extends ContainerBase implements Host { // Remove the specified alias int j = 0; - String results[] = new String[aliases.length - 1]; + String[] results = new String[aliases.length - 1]; for (int i = 0; i < aliases.length; i++) { if (i != n) { results[j++] = aliases[i]; @@ -748,7 +748,7 @@ public class StandardHost extends ContainerBase implements Host { // Set error report valve String errorValve = getErrorReportValveClass(); - if ((errorValve != null) && (!errorValve.equals(""))) { + if ((errorValve != null) && (!errorValve.isEmpty())) { try { boolean found = false; Valve[] valves = getPipeline().getValves(); @@ -801,11 +801,7 @@ public class StandardHost extends ContainerBase implements Host { @Override protected String getObjectNameKeyProperties() { - - StringBuilder keyProperties = new StringBuilder("type=Host"); - keyProperties.append(getMBeanKeyProperties()); - - return keyProperties.toString(); + return "type=Host" + getMBeanKeyProperties(); } } diff --git a/java/org/apache/catalina/core/StandardHostValve.java b/java/org/apache/catalina/core/StandardHostValve.java index 57630b219b..a38ae82516 100644 --- a/java/org/apache/catalina/core/StandardHostValve.java +++ b/java/org/apache/catalina/core/StandardHostValve.java @@ -17,6 +17,7 @@ package org.apache.catalina.core; import java.io.IOException; +import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import jakarta.servlet.DispatcherType; @@ -305,11 +306,7 @@ final class StandardHostValve extends ValveBase { * Need to ensure message attribute is set even if there is no message (e.g. if error was triggered by an * exception with a null message). */ - if (message == null) { - request.setAttribute(RequestDispatcher.ERROR_MESSAGE, ""); - } else { - request.setAttribute(RequestDispatcher.ERROR_MESSAGE, message); - } + request.setAttribute(RequestDispatcher.ERROR_MESSAGE, Objects.requireNonNullElse(message, "")); if (exception != null) { request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, exception); diff --git a/java/org/apache/catalina/core/StandardPipeline.java b/java/org/apache/catalina/core/StandardPipeline.java index fc1d0adfcd..3551178064 100644 --- a/java/org/apache/catalina/core/StandardPipeline.java +++ b/java/org/apache/catalina/core/StandardPipeline.java @@ -105,7 +105,7 @@ public class StandardPipeline extends LifecycleBase implements Pipeline { Valve valve = (first != null) ? first : basic; boolean supported = true; while (supported && valve != null) { - supported = supported & valve.isAsyncSupported(); + supported = valve.isAsyncSupported(); valve = valve.getNext(); } return supported; diff --git a/java/org/apache/catalina/core/StandardServer.java b/java/org/apache/catalina/core/StandardServer.java index 6ce60aa178..dc2fc4ad57 100644 --- a/java/org/apache/catalina/core/StandardServer.java +++ b/java/org/apache/catalina/core/StandardServer.java @@ -104,7 +104,7 @@ public final class StandardServer extends LifecycleMBeanBase implements Server { /** * Global naming resources. */ - private NamingResourcesImpl globalNamingResources = null; + private NamingResourcesImpl globalNamingResources; /** @@ -461,7 +461,7 @@ public final class StandardServer extends LifecycleMBeanBase implements Server { servicesWriteLock.lock(); try { - Service results[] = new Service[services.length + 1]; + Service[] results = new Service[services.length + 1]; System.arraycopy(services, 0, results, 0, services.length); results[services.length] = service; services = results; @@ -580,7 +580,7 @@ public final class StandardServer extends LifecycleMBeanBase implements Server { expected += random.nextInt() % 1024; } while (expected > 0) { - int ch = -1; + int ch; try { ch = stream.read(); } catch (IOException e) { diff --git a/java/org/apache/catalina/core/StandardService.java b/java/org/apache/catalina/core/StandardService.java index 724dde9668..d1dc4c8823 100644 --- a/java/org/apache/catalina/core/StandardService.java +++ b/java/org/apache/catalina/core/StandardService.java @@ -78,7 +78,7 @@ public class StandardService extends LifecycleMBeanBase implements Service { /** * The set of Connectors associated with this Service. */ - protected Connector connectors[] = new Connector[0]; + protected Connector[] connectors = new Connector[0]; private final ReadWriteLock connectorsLock = new ReentrantReadWriteLock(); /** @@ -206,7 +206,7 @@ public class StandardService extends LifecycleMBeanBase implements Service { writeLock.lock(); try { connector.setService(this); - Connector results[] = new Connector[connectors.length + 1]; + Connector[] results = new Connector[connectors.length + 1]; System.arraycopy(connectors, 0, results, 0, connectors.length); results[connectors.length] = connector; connectors = results; @@ -231,7 +231,7 @@ public class StandardService extends LifecycleMBeanBase implements Service { Lock readLock = connectorsLock.readLock(); readLock.lock(); try { - ObjectName results[] = new ObjectName[connectors.length]; + ObjectName[] results = new ObjectName[connectors.length]; for (int i = 0; i < results.length; i++) { results[i] = connectors[i].getObjectName(); } @@ -282,7 +282,7 @@ public class StandardService extends LifecycleMBeanBase implements Service { return; } int k = 0; - Connector results[] = new Connector[connectors.length - 1]; + Connector[] results = new Connector[connectors.length - 1]; for (int i = 0; i < connectors.length; i++) { if (i != j) { results[k++] = connectors[i]; @@ -320,10 +320,7 @@ public class StandardService extends LifecycleMBeanBase implements Service { @Override public String toString() { - StringBuilder sb = new StringBuilder("StandardService["); - sb.append(getName()); - sb.append(']'); - return sb.toString(); + return "StandardService[" + getName() + "]"; } @@ -378,7 +375,7 @@ public class StandardService extends LifecycleMBeanBase implements Service { @Override public void removeExecutor(Executor ex) { - boolean removed = false; + boolean removed; executorsLock.writeLock().lock(); try { removed = executors.remove(ex); diff --git a/java/org/apache/catalina/core/StandardWrapper.java b/java/org/apache/catalina/core/StandardWrapper.java index bb38df260e..04bf618f83 100644 --- a/java/org/apache/catalina/core/StandardWrapper.java +++ b/java/org/apache/catalina/core/StandardWrapper.java @@ -23,6 +23,7 @@ import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; +import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantReadWriteLock; @@ -422,15 +423,20 @@ public class StandardWrapper extends ContainerBase implements ServletConfig, Wra for (int i = 0; methods != null && i < methods.length; i++) { Method m = methods[i]; - if (m.getName().equals("doGet")) { - allow.add("GET"); - allow.add("HEAD"); - } else if (m.getName().equals("doPost")) { - allow.add("POST"); - } else if (m.getName().equals("doPut")) { - allow.add("PUT"); - } else if (m.getName().equals("doDelete")) { - allow.add("DELETE"); + switch (m.getName()) { + case "doGet": + allow.add("GET"); + allow.add("HEAD"); + break; + case "doPost": + allow.add("POST"); + break; + case "doPut": + allow.add("PUT"); + break; + case "doDelete": + allow.add("DELETE"); + break; } } } @@ -476,7 +482,7 @@ public class StandardWrapper extends ContainerBase implements ServletConfig, Wra */ public static Throwable getRootCause(ServletException e) { Throwable rootCause = e; - Throwable rootCauseCheck = null; + Throwable rootCauseCheck; // Extra aggressive rootCause finding int loops = 0; do { @@ -642,7 +648,7 @@ public class StandardWrapper extends ContainerBase implements ServletConfig, Wra @Override public String findSecurityReference(String name) { - String reference = null; + String reference; referencesLock.readLock().lock(); try { @@ -792,7 +798,7 @@ public class StandardWrapper extends ContainerBase implements ServletConfig, Wra } finally { if (swallowOutput) { String log = SystemLogHandler.stopCapture(); - if (log != null && log.length() > 0) { + if (log != null && !log.isEmpty()) { if (getServletContext() != null) { getServletContext().log(log); } else { @@ -948,7 +954,7 @@ public class StandardWrapper extends ContainerBase implements ServletConfig, Wra // Write captured output if (swallowOutput) { String log = SystemLogHandler.stopCapture(); - if (log != null && log.length() > 0) { + if (log != null && !log.isEmpty()) { if (getServletContext() != null) { getServletContext().log(log); } else { @@ -1218,11 +1224,7 @@ public class StandardWrapper extends ContainerBase implements ServletConfig, Wra StringBuilder keyProperties = new StringBuilder(",WebModule=//"); String hostName = getParent().getParent().getName(); - if (hostName == null) { - keyProperties.append("DEFAULT"); - } else { - keyProperties.append(hostName); - } + keyProperties.append(Objects.requireNonNullElse(hostName, "DEFAULT")); String contextName = getParent().getName(); if (!contextName.startsWith("/")) { diff --git a/java/org/apache/catalina/core/StandardWrapperValve.java b/java/org/apache/catalina/core/StandardWrapperValve.java index 6fde983636..1f5c285384 100644 --- a/java/org/apache/catalina/core/StandardWrapperValve.java +++ b/java/org/apache/catalina/core/StandardWrapperValve.java @@ -127,7 +127,7 @@ final class StandardWrapperValve extends ValveBase { container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e); throwable = e; exception(request, response, e); - servlet = null; + // servlet = null; is set here } MessageBytes requestPathMB = request.getRequestPathMB(); @@ -156,7 +156,7 @@ final class StandardWrapperValve extends ValveBase { } } finally { String log = SystemLogHandler.stopCapture(); - if (log != null && log.length() > 0) { + if (log != null && !log.isEmpty()) { context.getLogger().info(log); } } --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org For additional commands, e-mail: dev-h...@tomcat.apache.org