WW-5382 Rework Dispatcher injections

This commit is contained in:
Kusal Kithul-Godage
2024-01-02 03:29:54 +11:00
parent ae71c464a8
commit 946737c811
9 changed files with 969 additions and 928 deletions
@@ -64,6 +64,7 @@ import org.apache.struts2.config.StrutsBeanSelectionProvider;
import org.apache.struts2.config.StrutsJavaConfiguration;
import org.apache.struts2.config.StrutsJavaConfigurationProvider;
import org.apache.struts2.config.StrutsXmlConfigurationProvider;
import org.apache.struts2.dispatcher.mapper.ActionMapper;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.apache.struts2.dispatcher.multipart.MultiPartRequest;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
@@ -119,6 +120,10 @@ public class Dispatcher {
*/
private static final List<DispatcherListener> dispatcherListeners = new CopyOnWriteArrayList<>();
/**
* This field exists so {@link #getContainer()} can determine whether to (re-)inject this instance in the case of
* a {@link ConfigurationManager} reload.
*/
private Container injectedContainer;
/**
@@ -146,11 +151,6 @@ public class Dispatcher {
*/
private String multipartSaveDir;
/**
* Stores the value of {@link StrutsConstants#STRUTS_MULTIPART_PARSER} setting
*/
private String multipartHandlerName;
/**
* Stores the value of {@link StrutsConstants#STRUTS_MULTIPART_ENABLED}
*/
@@ -194,6 +194,11 @@ public class Dispatcher {
* Store ConfigurationManager instance, set on init.
*/
protected ConfigurationManager configurationManager;
private ObjectFactory objectFactory;
private ActionProxyFactory actionProxyFactory;
private LocaleProviderFactory localeProviderFactory;
private StaticContentLoader staticContentLoader;
private ActionMapper actionMapper;
/**
* Provide the dispatcher instance for the current thread.
@@ -213,6 +218,13 @@ public class Dispatcher {
Dispatcher.instance.set(instance);
}
/**
* Removes the dispatcher instance for this thread.
*/
public static void clearInstance() {
Dispatcher.instance.remove();
}
/**
* Add a dispatcher lifecycle listener.
*
@@ -308,9 +320,12 @@ public class Dispatcher {
multipartSaveDir = val;
}
@Inject(StrutsConstants.STRUTS_MULTIPART_PARSER)
/**
* @deprecated since 6.4.0, no replacement.
*/
@Deprecated
public void setMultipartHandler(String val) {
multipartHandlerName = val;
// no-op
}
@Inject(value = StrutsConstants.STRUTS_MULTIPART_ENABLED, required = false)
@@ -328,6 +343,10 @@ public class Dispatcher {
this.valueStackFactory = valueStackFactory;
}
public ValueStackFactory getValueStackFactory() {
return valueStackFactory;
}
@Inject(StrutsConstants.STRUTS_HANDLE_EXCEPTION)
public void setHandleException(String handleException) {
this.handleException = Boolean.parseBoolean(handleException);
@@ -348,12 +367,48 @@ public class Dispatcher {
this.errorHandler = errorHandler;
}
@Inject
public void setObjectFactory(ObjectFactory objectFactory) {
this.objectFactory = objectFactory;
}
@Inject
public void setActionProxyFactory(ActionProxyFactory actionProxyFactory) {
this.actionProxyFactory = actionProxyFactory;
}
public ActionProxyFactory getActionProxyFactory() {
return actionProxyFactory;
}
@Inject
public void setLocaleProviderFactory(LocaleProviderFactory localeProviderFactory) {
this.localeProviderFactory = localeProviderFactory;
}
@Inject
public void setStaticContentLoader(StaticContentLoader staticContentLoader) {
this.staticContentLoader = staticContentLoader;
}
public StaticContentLoader getStaticContentLoader() {
return staticContentLoader;
}
@Inject
public void setActionMapper(ActionMapper actionMapper) {
this.actionMapper = actionMapper;
}
public ActionMapper getActionMapper() {
return actionMapper;
}
/**
* Releases all instances bound to this dispatcher instance.
*/
public void cleanup() {
// clean up ObjectFactory
ObjectFactory objectFactory = getContainer().getInstance(ObjectFactory.class);
if (objectFactory == null) {
LOG.warn("Object Factory is null, something is seriously wrong, no clean up will be performed");
}
@@ -540,10 +595,6 @@ public class Dispatcher {
loadConfigPaths("struts-deferred.xml");
}
private Container init_PreloadConfiguration() {
return getContainer();
}
/**
* Load configurations, including both XML and zero-configuration strategies,
* and update optional settings, including whether to reload configurations and resource files.
@@ -684,7 +735,6 @@ public class Dispatcher {
}
protected ActionProxy createActionProxy(String namespace, String name, String method, Map<String, Object> extraContext) {
ActionProxyFactory actionProxyFactory = getContainer().getInstance(ActionProxyFactory.class);
return actionProxyFactory.createActionProxy(namespace, name, method, extraContext, true, false);
}
@@ -860,6 +910,7 @@ public class Dispatcher {
* @param response The response
*/
public void prepare(HttpServletRequest request, HttpServletResponse response) {
getContainer(); // Init ContainerHolder and reinject this instance IF ConfigurationManager was reloaded
String encoding = null;
if (defaultEncoding != null) {
encoding = defaultEncoding;
@@ -932,15 +983,12 @@ public class Dispatcher {
}
if (isMultipartSupportEnabled(request) && isMultipartRequest(request)) {
MultiPartRequest multiPartRequest = getMultiPartRequest();
LocaleProviderFactory localeProviderFactory = getContainer().getInstance(LocaleProviderFactory.class);
request = new MultiPartRequestWrapper(
multiPartRequest,
request,
getSaveDir(),
localeProviderFactory.createLocaleProvider(),
disableRequestAttributeValueStackLookup
getMultiPartRequest(),
request,
getSaveDir(),
localeProviderFactory.createLocaleProvider(),
disableRequestAttributeValueStackLookup
);
} else {
request = new StrutsRequestWrapper(request, disableRequestAttributeValueStackLookup);
@@ -1065,5 +1113,4 @@ public class Dispatcher {
}
return ContainerHolder.get();
}
}
@@ -18,8 +18,8 @@
*/
package org.apache.struts2.dispatcher;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.apache.struts2.RequestUtils;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@@ -54,7 +54,7 @@ public class ExecuteOperations {
resourcePath = request.getPathInfo();
}
StaticContentLoader staticResourceLoader = dispatcher.getContainer().getInstance(StaticContentLoader.class);
StaticContentLoader staticResourceLoader = dispatcher.getStaticContentLoader();
if (staticResourceLoader.canHandle(resourcePath)) {
staticResourceLoader.findStaticResource(resourcePath, request, response);
// The framework did its job here
@@ -57,7 +57,7 @@ public class InitOperations {
* @return the static content loader
*/
public StaticContentLoader initStaticContentLoader(HostConfig filterConfig, Dispatcher dispatcher) {
StaticContentLoader loader = dispatcher.getContainer().getInstance(StaticContentLoader.class);
StaticContentLoader loader = dispatcher.getStaticContentLoader();
loader.setHostConfig(filterConfig);
return loader;
}
@@ -20,13 +20,11 @@ package org.apache.struts2.dispatcher;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.ValueStackFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.RequestUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsException;
import org.apache.struts2.dispatcher.mapper.ActionMapper;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import javax.servlet.ServletException;
@@ -78,7 +76,7 @@ public class PrepareOperations {
dispatcher.cleanUpRequest(request);
} finally {
ActionContext.clear();
Dispatcher.setInstance(null);
Dispatcher.clearInstance();
devModeOverride.remove();
}
});
@@ -101,7 +99,7 @@ public class PrepareOperations {
} else {
ctx = ServletActionContext.getActionContext(request); //checks if we are probably in an async
if (ctx == null) {
ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();
ValueStack stack = dispatcher.getValueStackFactory().createValueStack();
stack.getContext().putAll(dispatcher.createContextMap(request, response, null));
ctx = ActionContext.of(stack.getContext()).bind();
}
@@ -188,7 +186,7 @@ public class PrepareOperations {
Object mappingAttr = request.getAttribute(STRUTS_ACTION_MAPPING_KEY);
if (mappingAttr == null || forceLookup) {
try {
mapping = dispatcher.getContainer().getInstance(ActionMapper.class).getMapping(request, dispatcher.getConfigurationManager());
mapping = dispatcher.getActionMapper().getMapping(request, dispatcher.getConfigurationManager());
if (mapping != null) {
request.setAttribute(STRUTS_ACTION_MAPPING_KEY, mapping);
} else {
@@ -59,7 +59,7 @@ public class StrutsTestCaseHelper {
public static void tearDown() {
(new Dispatcher(null, null)).cleanUpAfterInit(); // Clear ContainerHolder
Dispatcher.setInstance(null);
Dispatcher.clearInstance();
ActionContext.clear();
}
@@ -251,12 +251,8 @@ public class DispatcherTest extends StrutsJUnit4InternalTestCase {
@Test
public void testObjectFactoryDestroy() {
dispatcher = spy(dispatcher);
Container spiedContainer = spy(container);
doReturn(spiedContainer).when(dispatcher).getContainer();
InnerDestroyableObjectFactory destroyedObjectFactory = new InnerDestroyableObjectFactory();
doReturn(destroyedObjectFactory).when(spiedContainer).getInstance(ObjectFactory.class);
dispatcher.setObjectFactory(destroyedObjectFactory);
assertFalse(destroyedObjectFactory.destroyed);
dispatcher.cleanup();
@@ -18,31 +18,26 @@
*/
package org.apache.struts2.validators;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ActionProxyFactory;
import com.opensymphony.xwork2.DefaultActionInvocation;
import com.opensymphony.xwork2.ValidationAwareSupport;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.interceptor.ValidationAware;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.dispatcher.ApplicationMap;
import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.dispatcher.HttpParameters;
import org.apache.struts2.dispatcher.RequestMap;
import org.apache.struts2.dispatcher.SessionMap;
import org.directwebremoting.WebContextFactory;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ActionProxyFactory;
import com.opensymphony.xwork2.DefaultActionInvocation;
import com.opensymphony.xwork2.interceptor.ValidationAware;
import com.opensymphony.xwork2.ValidationAwareSupport;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
/**
* <p>
@@ -87,7 +82,7 @@ public class DWRValidator {
res);
try {
ActionProxyFactory actionProxyFactory = du.getContainer().getInstance(ActionProxyFactory.class);
ActionProxyFactory actionProxyFactory = du.getActionProxyFactory();
ActionProxy proxy = actionProxyFactory.createActionProxy(namespace, actionName, null, ctx, true, true);
proxy.execute();
Object action = proxy.getAction();
@@ -1,199 +1,204 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.sitemesh;
import com.opensymphony.module.sitemesh.RequestConstants;
import com.opensymphony.sitemesh.Content;
import com.opensymphony.sitemesh.webapp.SiteMeshWebAppContext;
import com.opensymphony.sitemesh.webapp.decorator.BaseWebAppDecorator;
import com.opensymphony.xwork2.*;
import com.opensymphony.xwork2.interceptor.PreResultListener;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.ValueStackFactory;
import freemarker.template.Configuration;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.Dispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;
/**
* Adapts a SiteMesh 2 {@link com.opensymphony.module.sitemesh.Decorator} to a
* SiteMesh 3 {@link com.opensymphony.sitemesh.Decorator}.
*
* @since SiteMesh 3
*/
public abstract class OldDecorator2NewStrutsDecorator extends BaseWebAppDecorator implements RequestConstants {
protected com.opensymphony.module.sitemesh.Decorator oldDecorator;
private static String customEncoding;
public OldDecorator2NewStrutsDecorator(com.opensymphony.module.sitemesh.Decorator oldDecorator) {
this.oldDecorator = oldDecorator;
}
public OldDecorator2NewStrutsDecorator() {
oldDecorator = null;
}
/**
* Applies the decorator, using the relevent contexts
*
* @param content The content
* @param request The servlet request
* @param response The servlet response
* @param servletContext The servlet context
* @param ctx The action context for this request, populated with the server state
*/
protected abstract void render(Content content, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, ActionContext ctx) throws ServletException, IOException;
/**
* Applies the decorator, creating the relevent contexts and delegating to
* the extended applyDecorator().
*
* @param content The content
* @param request The servlet request
* @param response The servlet response
* @param servletContext The servlet context
* @param webAppContext The web app context
*/
protected void render(Content content, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, SiteMeshWebAppContext webAppContext) throws IOException, ServletException {
// see if the URI path (webapp) is set
if (oldDecorator.getURIPath() != null) {
// in a security conscious environment, the servlet container
// may return null for a given URL
if (servletContext.getContext(oldDecorator.getURIPath()) != null) {
servletContext = servletContext.getContext(oldDecorator.getURIPath());
}
}
ActionContext ctx = ServletActionContext.getActionContext(request);
if (ctx == null) {
// ok, one isn't associated with the request, so let's create one using the current Dispatcher
ValueStack vs = Dispatcher.getInstance().getContainer().getInstance(ValueStackFactory.class).createValueStack();
vs.getContext().putAll(Dispatcher.getInstance().createContextMap(request, response, null));
ctx = ActionContext.of(vs.getContext());
if (ctx.getActionInvocation() == null) {
// put in a dummy ActionSupport so basic functionality still works
ActionSupport action = new ActionSupport();
vs.push(action);
ctx.withActionInvocation(new DummyActionInvocation(action));
}
}
// delegate to the actual page decorator
render(content, request, response, servletContext, ctx);
}
/**
* Returns the locale used for the {@link freemarker.template.Configuration#getTemplate(String, java.util.Locale)} call. The base implementation
* simply returns the locale setting of the action (assuming the action implements {@link LocaleProvider}) or, if
* the action does not the configuration's locale is returned. Override this method to provide different behaviour,
*/
protected Locale getLocale(ActionInvocation invocation, Configuration configuration) {
if (invocation.getAction() instanceof LocaleProvider) {
return ((LocaleProvider) invocation.getAction()).getLocale();
} else {
return configuration.getLocale();
}
}
/**
* Gets the L18N encoding of the system. The default is UTF-8.
*/
protected String getEncoding() {
String encoding = customEncoding;
if (encoding == null) {
encoding = System.getProperty("file.encoding");
}
if (encoding == null) {
encoding = "UTF-8";
}
return encoding;
}
static class DummyActionInvocation implements ActionInvocation {
ActionSupport action;
public DummyActionInvocation(ActionSupport action) {
this.action = action;
}
public Object getAction() {
return action;
}
public boolean isExecuted() {
return false;
}
public ActionContext getInvocationContext() {
return null;
}
public ActionProxy getProxy() {
return null;
}
public Result getResult() throws Exception {
return null;
}
public String getResultCode() {
return null;
}
public void setResultCode(String resultCode) {
}
public ValueStack getStack() {
return null;
}
public void addPreResultListener(PreResultListener listener) {
}
public String invoke() throws Exception {
return null;
}
public String invokeActionOnly() throws Exception {
return null;
}
public void setActionEventListener(ActionEventListener listener) {
}
public void init(ActionProxy proxy) {
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.sitemesh;
import com.opensymphony.module.sitemesh.RequestConstants;
import com.opensymphony.sitemesh.Content;
import com.opensymphony.sitemesh.webapp.SiteMeshWebAppContext;
import com.opensymphony.sitemesh.webapp.decorator.BaseWebAppDecorator;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionEventListener;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.LocaleProvider;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.interceptor.PreResultListener;
import com.opensymphony.xwork2.util.ValueStack;
import freemarker.template.Configuration;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.Dispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;
/**
* Adapts a SiteMesh 2 {@link com.opensymphony.module.sitemesh.Decorator} to a
* SiteMesh 3 {@link com.opensymphony.sitemesh.Decorator}.
*
* @since SiteMesh 3
*/
public abstract class OldDecorator2NewStrutsDecorator extends BaseWebAppDecorator implements RequestConstants {
protected com.opensymphony.module.sitemesh.Decorator oldDecorator;
private static String customEncoding;
public OldDecorator2NewStrutsDecorator(com.opensymphony.module.sitemesh.Decorator oldDecorator) {
this.oldDecorator = oldDecorator;
}
public OldDecorator2NewStrutsDecorator() {
oldDecorator = null;
}
/**
* Applies the decorator, using the relevent contexts
*
* @param content The content
* @param request The servlet request
* @param response The servlet response
* @param servletContext The servlet context
* @param ctx The action context for this request, populated with the server state
*/
protected abstract void render(Content content, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, ActionContext ctx) throws ServletException, IOException;
/**
* Applies the decorator, creating the relevent contexts and delegating to
* the extended applyDecorator().
*
* @param content The content
* @param request The servlet request
* @param response The servlet response
* @param servletContext The servlet context
* @param webAppContext The web app context
*/
protected void render(Content content, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, SiteMeshWebAppContext webAppContext) throws IOException, ServletException {
// see if the URI path (webapp) is set
if (oldDecorator.getURIPath() != null) {
// in a security conscious environment, the servlet container
// may return null for a given URL
if (servletContext.getContext(oldDecorator.getURIPath()) != null) {
servletContext = servletContext.getContext(oldDecorator.getURIPath());
}
}
ActionContext ctx = ServletActionContext.getActionContext(request);
if (ctx == null) {
// ok, one isn't associated with the request, so let's create one using the current Dispatcher
ValueStack vs = Dispatcher.getInstance().getValueStackFactory().createValueStack();
vs.getContext().putAll(Dispatcher.getInstance().createContextMap(request, response, null));
ctx = ActionContext.of(vs.getContext());
if (ctx.getActionInvocation() == null) {
// put in a dummy ActionSupport so basic functionality still works
ActionSupport action = new ActionSupport();
vs.push(action);
ctx.withActionInvocation(new DummyActionInvocation(action));
}
}
// delegate to the actual page decorator
render(content, request, response, servletContext, ctx);
}
/**
* Returns the locale used for the {@link freemarker.template.Configuration#getTemplate(String, java.util.Locale)} call. The base implementation
* simply returns the locale setting of the action (assuming the action implements {@link LocaleProvider}) or, if
* the action does not the configuration's locale is returned. Override this method to provide different behaviour,
*/
protected Locale getLocale(ActionInvocation invocation, Configuration configuration) {
if (invocation.getAction() instanceof LocaleProvider) {
return ((LocaleProvider) invocation.getAction()).getLocale();
} else {
return configuration.getLocale();
}
}
/**
* Gets the L18N encoding of the system. The default is UTF-8.
*/
protected String getEncoding() {
String encoding = customEncoding;
if (encoding == null) {
encoding = System.getProperty("file.encoding");
}
if (encoding == null) {
encoding = "UTF-8";
}
return encoding;
}
static class DummyActionInvocation implements ActionInvocation {
ActionSupport action;
public DummyActionInvocation(ActionSupport action) {
this.action = action;
}
public Object getAction() {
return action;
}
public boolean isExecuted() {
return false;
}
public ActionContext getInvocationContext() {
return null;
}
public ActionProxy getProxy() {
return null;
}
public Result getResult() throws Exception {
return null;
}
public String getResultCode() {
return null;
}
public void setResultCode(String resultCode) {
}
public ValueStack getStack() {
return null;
}
public void addPreResultListener(PreResultListener listener) {
}
public String invoke() throws Exception {
return null;
}
public String invokeActionOnly() throws Exception {
return null;
}
public void setActionEventListener(ActionEventListener listener) {
}
public void init(ActionProxy proxy) {
}
}
}