This is an automated email from the ASF dual-hosted git repository. lukaszlenart pushed a commit to branch action-context-boost in repository https://gitbox.apache.org/repos/asf/struts.git
The following commit(s) were added to refs/heads/action-context-boost by this push: new 8e6815e WW-4789 WW-3788 Stops using get() 8e6815e is described below commit 8e6815e115859f35e9be3529c42eda61bea541de Author: Lukasz Lenart <lukaszlen...@apache.org> AuthorDate: Wed Apr 8 08:22:00 2020 +0200 WW-4789 WW-3788 Stops using get() --- .../chat/ChatAuthenticationInterceptor.java | 29 +++--- .../struts2/showcase/chat/ChatInterceptor.java | 28 +++--- .../com/opensymphony/xwork2/ActionContext.java | 2 +- .../org/apache/struts2/result/PlainTextResult.java | 21 ++--- .../org/apache/struts2/result/PostbackResult.java | 14 +-- .../struts2/result/ServletRedirectResult.java | 65 ++++++------- .../org/apache/struts2/result/StreamResult.java | 23 +++-- .../struts2/views/freemarker/FreemarkerResult.java | 34 ++++--- .../ScopedModelDrivenInterceptorTest.java | 18 ++-- .../main/java/org/apache/struts2/JSPRuntime.java | 5 +- .../views/jasperreports/JasperReportsResult.java | 10 +- .../java/org/apache/struts2/json/JSONResult.java | 69 +++++++------- .../org/apache/struts2/json/smd/SMDGenerator.java | 13 ++- .../struts2/rest/RestWorkflowInterceptor.java | 105 ++++++++++----------- .../sitemesh/FreemarkerDecoratorServlet.java | 29 +++--- 15 files changed, 232 insertions(+), 233 deletions(-) diff --git a/apps/showcase/src/main/java/org/apache/struts2/showcase/chat/ChatAuthenticationInterceptor.java b/apps/showcase/src/main/java/org/apache/struts2/showcase/chat/ChatAuthenticationInterceptor.java index fccaad7..e820f55 100644 --- a/apps/showcase/src/main/java/org/apache/struts2/showcase/chat/ChatAuthenticationInterceptor.java +++ b/apps/showcase/src/main/java/org/apache/struts2/showcase/chat/ChatAuthenticationInterceptor.java @@ -25,27 +25,28 @@ import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; -import org.apache.struts2.dispatcher.SessionMap; +import org.apache.logging.log4j.Logger; + +import java.util.Map; public class ChatAuthenticationInterceptor extends AbstractInterceptor { - private static final long serialVersionUID = 1L; - private static final Logger LOG = LogManager.getLogger(ChatAuthenticationInterceptor.class); - public static final String USER_SESSION_KEY = "chatUserSessionKey"; + private static final long serialVersionUID = 1L; + private static final Logger LOG = LogManager.getLogger(ChatAuthenticationInterceptor.class); + public static final String USER_SESSION_KEY = "chatUserSessionKey"; - public String intercept(ActionInvocation invocation) throws Exception { + public String intercept(ActionInvocation invocation) throws Exception { - LOG.debug("Authenticating chat user"); + LOG.debug("Authenticating chat user"); - SessionMap session = (SessionMap) ActionContext.getContext().get(ActionContext.SESSION); - User user = (User) session.get(USER_SESSION_KEY); + Map<String, Object> session = ActionContext.getContext().getSession(); + User user = (User) session.get(USER_SESSION_KEY); - if (user == null) { - return Action.LOGIN; - } - return invocation.invoke(); - } + if (user == null) { + return Action.LOGIN; + } + return invocation.invoke(); + } } diff --git a/apps/showcase/src/main/java/org/apache/struts2/showcase/chat/ChatInterceptor.java b/apps/showcase/src/main/java/org/apache/struts2/showcase/chat/ChatInterceptor.java index 4497709..324226b 100644 --- a/apps/showcase/src/main/java/org/apache/struts2/showcase/chat/ChatInterceptor.java +++ b/apps/showcase/src/main/java/org/apache/struts2/showcase/chat/ChatInterceptor.java @@ -24,31 +24,31 @@ import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; -import javax.servlet.http.HttpSession; +import java.util.Map; /** * Authenticate showcase chat example, make sure everyone have a username. */ public class ChatInterceptor extends AbstractInterceptor { - private static final Logger LOG = LogManager.getLogger(ChatInterceptor.class); + private static final Logger LOG = LogManager.getLogger(ChatInterceptor.class); - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public static final String CHAT_USER_SESSION_KEY = "ChatUserSessionKey"; + public static final String CHAT_USER_SESSION_KEY = "ChatUserSessionKey"; - public String intercept(ActionInvocation invocation) throws Exception { - HttpSession session = (HttpSession) ActionContext.getContext().get(ActionContext.SESSION); - User chatUser = (User) session.getAttribute(CHAT_USER_SESSION_KEY); - if (chatUser == null) { - LOG.debug("Chat user not logged in"); - return Action.LOGIN; - } - return invocation.invoke(); - } + public String intercept(ActionInvocation invocation) throws Exception { + Map<String, Object> session = ActionContext.getContext().getSession(); + User chatUser = (User) session.get(CHAT_USER_SESSION_KEY); + if (chatUser == null) { + LOG.debug("Chat user not logged in"); + return Action.LOGIN; + } + return invocation.invoke(); + } } diff --git a/core/src/main/java/com/opensymphony/xwork2/ActionContext.java b/core/src/main/java/com/opensymphony/xwork2/ActionContext.java index 1c5739a..3d7b78e 100644 --- a/core/src/main/java/com/opensymphony/xwork2/ActionContext.java +++ b/core/src/main/java/com/opensymphony/xwork2/ActionContext.java @@ -116,7 +116,7 @@ public class ActionContext implements Serializable { * * @param context a context map. */ - private ActionContext(Map<String, Object> context) { + protected ActionContext(Map<String, Object> context) { this.context = context; } diff --git a/core/src/main/java/org/apache/struts2/result/PlainTextResult.java b/core/src/main/java/org/apache/struts2/result/PlainTextResult.java index f2dda71..c264817 100644 --- a/core/src/main/java/org/apache/struts2/result/PlainTextResult.java +++ b/core/src/main/java/org/apache/struts2/result/PlainTextResult.java @@ -32,13 +32,13 @@ import java.nio.charset.Charset; /** * <!-- START SNIPPET: description --> - * + * <p> * A result that send the content out as plain text. Useful typically when needed * to display the raw content of a JSP or Html file for example. - * + * <p> * <!-- END SNIPPET: description --> - * - * + * <p> + * <p> * <!-- START SNIPPET: params --> * * <ul> @@ -47,7 +47,7 @@ import java.nio.charset.Charset; * response type (eg. Content-Type=text/plain; charset=UTF-8) and when reading * using a Reader. Some example of charSet would be UTF-8, ISO-8859-1 etc. * </ul> - * + * <p> * <!-- END SNIPPET: params --> * * @@ -68,7 +68,6 @@ import java.nio.charset.Charset; * * <!-- END SNIPPET: example --> * </pre> - * */ public class PlainTextResult extends StrutsResultSupport { @@ -113,22 +112,22 @@ public class PlainTextResult extends StrutsResultSupport { // verify charset Charset charset = readCharset(); - HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(HTTP_RESPONSE); + HttpServletResponse response = invocation.getInvocationContext().getServletResponse(); applyCharset(charset, response); applyAdditionalHeaders(response); String location = adjustLocation(finalLocation); try (PrintWriter writer = response.getWriter(); - InputStream resourceAsStream = readStream(invocation, location); - InputStreamReader reader = new InputStreamReader(resourceAsStream, charset == null ? Charset.defaultCharset() : charset)) { + InputStream resourceAsStream = readStream(invocation, location); + InputStreamReader reader = new InputStreamReader(resourceAsStream, charset == null ? Charset.defaultCharset() : charset)) { logWrongStream(finalLocation, resourceAsStream); sendStream(writer, reader); } } protected InputStream readStream(ActionInvocation invocation, String location) { - ServletContext servletContext = (ServletContext) invocation.getInvocationContext().get(SERVLET_CONTEXT); + ServletContext servletContext = invocation.getInvocationContext().getServletContext(); return servletContext.getResourceAsStream(location); } @@ -141,7 +140,7 @@ public class PlainTextResult extends StrutsResultSupport { protected void sendStream(PrintWriter writer, InputStreamReader reader) throws IOException { char[] buffer = new char[BUFFER_SIZE]; int charRead; - while((charRead = reader.read(buffer)) != -1) { + while ((charRead = reader.read(buffer)) != -1) { writer.write(buffer, 0, charRead); } } diff --git a/core/src/main/java/org/apache/struts2/result/PostbackResult.java b/core/src/main/java/org/apache/struts2/result/PostbackResult.java index 1a275d5..261404d 100644 --- a/core/src/main/java/org/apache/struts2/result/PostbackResult.java +++ b/core/src/main/java/org/apache/struts2/result/PostbackResult.java @@ -21,7 +21,6 @@ package org.apache.struts2.result; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.inject.Inject; -import org.apache.struts2.ServletActionContext; import org.apache.struts2.dispatcher.mapper.ActionMapper; import org.apache.struts2.dispatcher.mapper.ActionMapping; @@ -75,7 +74,7 @@ import java.util.Map; public class PostbackResult extends StrutsResultSupport { private static final long serialVersionUID = -2283504349296877429L; - + private String actionName; private String namespace; private String method; @@ -87,8 +86,8 @@ public class PostbackResult extends StrutsResultSupport { @Override protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception { ActionContext ctx = invocation.getInvocationContext(); - HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST); - HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE); + HttpServletRequest request = ctx.getServletRequest(); + HttpServletResponse response = ctx.getServletResponse(); // Cache? if (!cache) { @@ -99,7 +98,7 @@ public class PostbackResult extends StrutsResultSupport { //set contenttype @see ww-4564 response.setContentType("text/html"); - + // Render PrintWriter pw = new PrintWriter(response.getOutputStream()); pw.write("<!DOCTYPE html><html><body><form action=\"" + finalLocation + "\" method=\"POST\">"); @@ -119,7 +118,7 @@ public class PostbackResult extends StrutsResultSupport { /** * Determines if the specified form input element should be included. * - * @param name the input element name + * @param name the input element name * @param values the input element values * @return {@code true} if included; otherwise {@code false} */ @@ -129,7 +128,7 @@ public class PostbackResult extends StrutsResultSupport { protected String makePostbackUri(ActionInvocation invocation) { ActionContext ctx = invocation.getInvocationContext(); - HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST); + HttpServletRequest request = ctx.getServletRequest(); String postbackUri; if (actionName != null) { @@ -178,6 +177,7 @@ public class PostbackResult extends StrutsResultSupport { /** * Stores the option to cache the rendered intermediate page. The default * is {@code true}. + * * @param cache enable/disable cache */ public final void setCache(boolean cache) { diff --git a/core/src/main/java/org/apache/struts2/result/ServletRedirectResult.java b/core/src/main/java/org/apache/struts2/result/ServletRedirectResult.java index defb5b5..0973492 100644 --- a/core/src/main/java/org/apache/struts2/result/ServletRedirectResult.java +++ b/core/src/main/java/org/apache/struts2/result/ServletRedirectResult.java @@ -26,7 +26,6 @@ import com.opensymphony.xwork2.util.reflection.ReflectionException; import com.opensymphony.xwork2.util.reflection.ReflectionExceptionHandler; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.apache.struts2.ServletActionContext; import org.apache.struts2.dispatcher.Dispatcher; import org.apache.struts2.dispatcher.mapper.ActionMapper; import org.apache.struts2.dispatcher.mapper.ActionMapping; @@ -38,7 +37,11 @@ import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; -import java.util.*; +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import static javax.servlet.http.HttpServletResponse.SC_FOUND; @@ -59,22 +62,22 @@ import static javax.servlet.http.HttpServletResponse.SC_FOUND; * <b>This result type takes the following parameters:</b> * </p> * <!-- START SNIPPET: params --> - * + * * <ul> - * + * * <li><b>location (default)</b> - the location to go to after execution.</li> - * + * * <li><b>parse</b> - true by default. If set to false, the location param will * not be parsed for Ognl expressions.</li> - * - * <li><b>anchor</b> - Optional. Also known as "fragment" or colloquially as + * + * <li><b>anchor</b> - Optional. Also known as "fragment" or colloquially as * "hash". You can specify an anchor for a result.</li> * </ul> - * + * * <p> * This result follows the same rules from {@link StrutsResultSupport}. * </p> - * + * <p> * <!-- END SNIPPET: params --> * <p> * <b>Example:</b> @@ -93,7 +96,6 @@ import static javax.servlet.http.HttpServletResponse.SC_FOUND; * </result> * <!-- END SNIPPET: example --> * </pre> - * */ public class ServletRedirectResult extends StrutsResultSupport implements ReflectionExceptionHandler, Redirectable { @@ -139,7 +141,7 @@ public class ServletRedirectResult extends StrutsResultSupport implements Reflec /** * Set the optional anchor value. - * + * * @param anchor the anchor value */ public void setAnchor(String anchor) { @@ -149,7 +151,7 @@ public class ServletRedirectResult extends StrutsResultSupport implements Reflec /** * Sets whether or not to prepend the servlet context path to the redirected * URL. - * + * * @param prependServletContext <tt>true</tt> to prepend the location with the servlet context path, <tt>false</tt> otherwise. */ public void setPrependServletContext(boolean prependServletContext) { @@ -166,15 +168,15 @@ public class ServletRedirectResult extends StrutsResultSupport implements Reflec /** * Redirects to the location specified by calling * {@link HttpServletResponse#sendRedirect(String)}. - * + * * @param finalLocation the location to redirect to. - * @param invocation an encapsulation of the action execution state. + * @param invocation an encapsulation of the action execution state. * @throws Exception if an error occurs when redirecting. */ protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception { ActionContext ctx = invocation.getInvocationContext(); - HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST); - HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE); + HttpServletRequest request = ctx.getServletRequest(); + HttpServletResponse response = ctx.getServletResponse(); if (isPathUrl(finalLocation)) { if (!finalLocation.startsWith("/")) { @@ -228,24 +230,24 @@ public class ServletRedirectResult extends StrutsResultSupport implements Reflec protected List<String> getProhibitedResultParams() { return Arrays.asList( - DEFAULT_PARAM, - "namespace", - "method", - "encode", - "parse", - "location", - "prependServletContext", - "suppressEmptyParameters", - "anchor", - "statusCode" + DEFAULT_PARAM, + "namespace", + "method", + "encode", + "parse", + "location", + "prependServletContext", + "suppressEmptyParameters", + "anchor", + "statusCode" ); } /** * Sends the redirection. Can be overridden to customize how the redirect is * handled (i.e. to use a different status code) - * - * @param response The response + * + * @param response The response * @param finalLocation The location URI * @throws IOException in case of IO errors */ @@ -304,7 +306,7 @@ public class ServletRedirectResult extends StrutsResultSupport implements Reflec /** * Sets the suppressEmptyParameters option - * + * * @param suppressEmptyParameters The new value for this option */ public void setSuppressEmptyParameters(boolean suppressEmptyParameters) { @@ -313,10 +315,9 @@ public class ServletRedirectResult extends StrutsResultSupport implements Reflec /** * Adds a request parameter to be added to the redirect url - * - * @param key The parameter name - * @param value The parameter value * + * @param key The parameter name + * @param value The parameter value * @return the servlet redirect result */ public ServletRedirectResult addParameter(String key, Object value) { diff --git a/core/src/main/java/org/apache/struts2/result/StreamResult.java b/core/src/main/java/org/apache/struts2/result/StreamResult.java index 554b1a9..47dbc45 100644 --- a/core/src/main/java/org/apache/struts2/result/StreamResult.java +++ b/core/src/main/java/org/apache/struts2/result/StreamResult.java @@ -64,10 +64,10 @@ import java.io.OutputStream; * of evaluating the expression will be used. If not set, then no charset will be set on * the header</li> * </ul> - * + * * <p>These parameters can also be set by exposing a similarly named getter method on your Action. For example, you can * provide <code>getContentType()</code> to override that parameter for the current action.</p> - * + * <p> * <!-- END SNIPPET: params --> * <p> * <b>Example:</b> @@ -81,7 +81,6 @@ import java.io.OutputStream; * <param name="bufferSize">1024</param> * </result> * <!-- END SNIPPET: example --></pre> - * */ public class StreamResult extends StrutsResultSupport { @@ -94,7 +93,7 @@ public class StreamResult extends StrutsResultSupport { protected String contentType = "text/plain"; protected String contentLength; protected String contentDisposition = "inline"; - protected String contentCharSet ; + protected String contentCharSet; protected String inputName = "inputStream"; protected InputStream inputStream; protected int bufferSize = 1024; @@ -108,7 +107,7 @@ public class StreamResult extends StrutsResultSupport { this.inputStream = in; } - /** + /** * @return Returns the whether or not the client should be requested to allow caching of the data stream. */ public boolean getAllowCaching() { @@ -232,11 +231,11 @@ public class StreamResult extends StrutsResultSupport { } - HttpServletResponse oResponse = (HttpServletResponse) invocation.getInvocationContext().get(HTTP_RESPONSE); + HttpServletResponse oResponse = invocation.getInvocationContext().getServletResponse(); LOG.debug("Set the content type: {};charset{}", contentType, contentCharSet); - if (contentCharSet != null && ! contentCharSet.equals("")) { - oResponse.setContentType(conditionalParse(contentType, invocation)+";charset="+conditionalParse(contentCharSet, invocation)); + if (contentCharSet != null && !contentCharSet.equals("")) { + oResponse.setContentType(conditionalParse(contentType, invocation) + ";charset=" + conditionalParse(contentCharSet, invocation)); } else { oResponse.setContentType(conditionalParse(contentType, invocation)); } @@ -250,7 +249,7 @@ public class StreamResult extends StrutsResultSupport { if (_contentLengthAsInt >= 0) { oResponse.setContentLength(_contentLengthAsInt); } - } catch(NumberFormatException e) { + } catch (NumberFormatException e) { LOG.warn("failed to recognize {} as a number, contentLength header will not be set", _contentLength, e); } } @@ -269,16 +268,16 @@ public class StreamResult extends StrutsResultSupport { oOutput = oResponse.getOutputStream(); LOG.debug("Streaming result [{}] type=[{}] length=[{}] content-disposition=[{}] charset=[{}]", - inputName, contentType, contentLength, contentDisposition, contentCharSet); + inputName, contentType, contentLength, contentDisposition, contentCharSet); - LOG.debug("Streaming to output buffer +++ START +++"); + LOG.debug("Streaming to output buffer +++ START +++"); byte[] oBuff = new byte[bufferSize]; int iSize; while (-1 != (iSize = inputStream.read(oBuff))) { LOG.debug("Sending stream ... {}", iSize); oOutput.write(oBuff, 0, iSize); } - LOG.debug("Streaming to output buffer +++ END +++"); + LOG.debug("Streaming to output buffer +++ END +++"); // Flush oOutput.flush(); diff --git a/core/src/main/java/org/apache/struts2/views/freemarker/FreemarkerResult.java b/core/src/main/java/org/apache/struts2/views/freemarker/FreemarkerResult.java index 5f57297..7d59456 100644 --- a/core/src/main/java/org/apache/struts2/views/freemarker/FreemarkerResult.java +++ b/core/src/main/java/org/apache/struts2/views/freemarker/FreemarkerResult.java @@ -23,8 +23,6 @@ import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.LocaleProvider; import com.opensymphony.xwork2.inject.Inject; import com.opensymphony.xwork2.util.ValueStack; -import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.LogManager; import freemarker.template.Configuration; import freemarker.template.ObjectWrapper; import freemarker.template.Template; @@ -33,6 +31,8 @@ import freemarker.template.TemplateExceptionHandler; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; import org.apache.commons.lang3.ObjectUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.apache.struts2.ServletActionContext; import org.apache.struts2.StrutsStatics; import org.apache.struts2.result.StrutsResultSupport; @@ -68,7 +68,7 @@ public class FreemarkerResult extends StrutsResultSupport { */ protected String location; private String pContentType = "text/html"; - private static final String PARENT_TEMPLATE_WRITER = FreemarkerResult.class.getName() + ".parentWriter"; + private static final String PARENT_TEMPLATE_WRITER = FreemarkerResult.class.getName() + ".parentWriter"; public FreemarkerResult() { super(); @@ -77,7 +77,7 @@ public class FreemarkerResult extends StrutsResultSupport { public FreemarkerResult(String location) { super(location); } - + @Inject public void setFreemarkerManager(FreemarkerManager mgr) { this.freemarkerManager = mgr; @@ -109,9 +109,8 @@ public class FreemarkerResult extends StrutsResultSupport { * </p> * * @param locationArg location argument - * @param invocation the action invocation - * - * @throws IOException in case of IO errors + * @param invocation the action invocation + * @throws IOException in case of IO errors * @throws TemplateException in case of freemarker template errors */ public void doExecute(String locationArg, ActionInvocation invocation) throws IOException, TemplateException { @@ -121,12 +120,12 @@ public class FreemarkerResult extends StrutsResultSupport { this.wrapper = getObjectWrapper(); ActionContext ctx = invocation.getInvocationContext(); - HttpServletRequest req = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST); + HttpServletRequest req = ctx.getServletRequest(); String absoluteLocation; if (location.startsWith("/")) { - absoluteLocation = location; - } else { + absoluteLocation = location; + } else { String namespace = invocation.getProxy().getNamespace(); if (namespace == null || namespace.length() == 0 || namespace.equals("/")) { absoluteLocation = "/" + location; @@ -152,7 +151,7 @@ public class FreemarkerResult extends StrutsResultSupport { // Process the template Writer writer = getWriter(); - if (willWriteIfCompleted){ + if (willWriteIfCompleted) { CharArrayWriter parentCharArrayWriter = (CharArrayWriter) req.getAttribute(PARENT_TEMPLATE_WRITER); boolean isTopTemplate; if (isTopTemplate = (parentCharArrayWriter == null)) { @@ -242,7 +241,7 @@ public class FreemarkerResult extends StrutsResultSupport { * @throws IOException in case of IO errors */ protected Writer getWriter() throws IOException { - if(writer != null) { + if (writer != null) { return writer; } return ServletActionContext.getResponse().getWriter(); @@ -278,7 +277,7 @@ public class FreemarkerResult extends StrutsResultSupport { ValueStack stack = ActionContext.getContext().getValueStack(); Object action = null; - if(invocation!= null ) action = invocation.getAction(); //Added for NullPointException + if (invocation != null) action = invocation.getAction(); //Added for NullPointException return freemarkerManager.buildTemplateModel(stack, action, servletContext, request, response, wrapper); } @@ -301,8 +300,7 @@ public class FreemarkerResult extends StrutsResultSupport { * the default implementation of postTemplateProcess applies the contentType parameter * * @param template the freemarker template - * @param model the template model - * + * @param model the template model * @throws IOException in case of IO errors */ protected void postTemplateProcess(Template template, TemplateModel model) throws IOException { @@ -316,7 +314,7 @@ public class FreemarkerResult extends StrutsResultSupport { * objects into the model root * * @param template the freemarker template - * @param model the template model + * @param model the template model * @return true to process the template, false to suppress template processing. * @throws IOException in case of IO errors */ @@ -342,8 +340,8 @@ public class FreemarkerResult extends StrutsResultSupport { response.setContentType(contentType); } - } else if(isInsideActionTag()){ - //trigger com.opensymphony.module.sitemesh.filter.PageResponseWrapper.deactivateSiteMesh() + } else if (isInsideActionTag()) { + //trigger com.opensymphony.module.sitemesh.filter.PageResponseWrapper.deactivateSiteMesh() response.setContentType(response.getContentType()); } diff --git a/core/src/test/java/com/opensymphony/xwork2/interceptor/ScopedModelDrivenInterceptorTest.java b/core/src/test/java/com/opensymphony/xwork2/interceptor/ScopedModelDrivenInterceptorTest.java index b243237..6938d30 100644 --- a/core/src/test/java/com/opensymphony/xwork2/interceptor/ScopedModelDrivenInterceptorTest.java +++ b/core/src/test/java/com/opensymphony/xwork2/interceptor/ScopedModelDrivenInterceptorTest.java @@ -18,7 +18,12 @@ */ package com.opensymphony.xwork2.interceptor; -import com.opensymphony.xwork2.*; +import com.opensymphony.xwork2.Action; +import com.opensymphony.xwork2.ActionContext; +import com.opensymphony.xwork2.ObjectFactory; +import com.opensymphony.xwork2.ProxyObjectFactory; +import com.opensymphony.xwork2.SimpleAction; +import com.opensymphony.xwork2.XWorkTestCase; import com.opensymphony.xwork2.config.entities.ActionConfig; import com.opensymphony.xwork2.mock.MockActionInvocation; import com.opensymphony.xwork2.mock.MockActionProxy; @@ -31,7 +36,7 @@ import java.util.Map; public class ScopedModelDrivenInterceptorTest extends XWorkTestCase { protected ScopedModelDrivenInterceptor inter = null; - + /** * Set up instance variables required by this test case. */ @@ -45,24 +50,23 @@ public class ScopedModelDrivenInterceptorTest extends XWorkTestCase { } public void testResolveModel() throws Exception { - ActionContext ctx = ActionContext.getContext(); - ctx.setSession(new HashMap<String, Object>()); + ActionContext ctx = ActionContext.getContext().withSession(new HashMap<>()); ObjectFactory factory = ActionContext.getContext().getContainer().getInstance(ObjectFactory.class); Object obj = inter.resolveModel(factory, ctx, "java.lang.String", "request", "foo"); assertNotNull(obj); assertTrue(obj instanceof String); - assertTrue(obj == ctx.get("foo")); + assertSame(obj, ctx.get("foo")); obj = inter.resolveModel(factory, ctx, "java.lang.String", "session", "foo"); assertNotNull(obj); assertTrue(obj instanceof String); - assertTrue(obj == ctx.getSession().get("foo")); + assertSame(obj, ctx.getSession().get("foo")); obj = inter.resolveModel(factory, ctx, "java.lang.String", "session", "foo"); assertNotNull(obj); assertTrue(obj instanceof String); - assertTrue(obj == ctx.getSession().get("foo")); + assertSame(obj, ctx.getSession().get("foo")); } public void testScopedModelDrivenAction() throws Exception { diff --git a/plugins/embeddedjsp/src/main/java/org/apache/struts2/JSPRuntime.java b/plugins/embeddedjsp/src/main/java/org/apache/struts2/JSPRuntime.java index 1a47a4d..81bbed4 100644 --- a/plugins/embeddedjsp/src/main/java/org/apache/struts2/JSPRuntime.java +++ b/plugins/embeddedjsp/src/main/java/org/apache/struts2/JSPRuntime.java @@ -19,8 +19,8 @@ package org.apache.struts2; import com.opensymphony.xwork2.ActionContext; -import org.apache.struts2.dispatcher.HttpParameters; import org.apache.struts2.dispatcher.Parameter; +import org.apache.struts2.views.util.DefaultUrlHelper; import org.apache.struts2.views.util.UrlHelper; import javax.servlet.Servlet; @@ -29,7 +29,6 @@ import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.HttpJspPage; import java.util.HashMap; import java.util.Map; -import org.apache.struts2.views.util.DefaultUrlHelper; /** * Maintains a cache of jsp locations -> servlet instances for those jsps. When a jsp is requested @@ -55,7 +54,7 @@ public abstract class JSPRuntime { if (i > 0) { //extract params from the url and add them to the request final UrlHelper urlHelperGetInstance = ServletActionContext.getContext().getInstance(UrlHelper.class); - final UrlHelper contextUrlHelper = (urlHelperGetInstance != null ? urlHelperGetInstance : (UrlHelper) ServletActionContext.getContext().get(StrutsConstants.STRUTS_URL_HELPER)); + final UrlHelper contextUrlHelper = (urlHelperGetInstance != null ? urlHelperGetInstance : (UrlHelper) ActionContext.getContext().get(StrutsConstants.STRUTS_URL_HELPER)); final UrlHelper urlHelper = (contextUrlHelper != null ? contextUrlHelper : new DefaultUrlHelper()); String query = location.substring(i + 1); Map<String, Object> queryParams = urlHelper.parseQueryString(query, true); diff --git a/plugins/jasperreports/src/main/java/org/apache/struts2/views/jasperreports/JasperReportsResult.java b/plugins/jasperreports/src/main/java/org/apache/struts2/views/jasperreports/JasperReportsResult.java index 3fbdf98..b639570 100644 --- a/plugins/jasperreports/src/main/java/org/apache/struts2/views/jasperreports/JasperReportsResult.java +++ b/plugins/jasperreports/src/main/java/org/apache/struts2/views/jasperreports/JasperReportsResult.java @@ -39,7 +39,6 @@ import net.sf.jasperreports.engine.util.JRLoader; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.apache.struts2.ServletActionContext; import org.apache.struts2.result.StrutsResultSupport; import javax.servlet.ServletContext; @@ -252,10 +251,8 @@ public class JasperReportsResult extends StrutsResultSupport implements JasperRe LOG.debug("Creating JasperReport for dataSource = {}, format = {}", dataSource, format); - HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext() - .get(ServletActionContext.HTTP_REQUEST); - HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext() - .get(ServletActionContext.HTTP_RESPONSE); + HttpServletRequest request = invocation.getInvocationContext().getServletRequest(); + HttpServletResponse response = invocation.getInvocationContext().getServletResponse(); // Handle IE special case: it sends a "contype" request first. // TODO Set content type to config settings? @@ -290,8 +287,7 @@ public class JasperReportsResult extends StrutsResultSupport implements JasperRe // Determine the directory that the report file is in and set the reportDirectory parameter // For WW 2.1.7: // ServletContext servletContext = ((ServletConfig) invocation.getInvocationContext().get(ServletActionContext.SERVLET_CONFIG)).getServletContext(); - ServletContext servletContext = (ServletContext) invocation.getInvocationContext() - .get(ServletActionContext.SERVLET_CONTEXT); + ServletContext servletContext = invocation.getInvocationContext().getServletContext(); String systemId = servletContext.getRealPath(finalLocation); Map<String, Object> parameters = new ValueStackShadowMap(stack); File directory = new File(systemId.substring(0, systemId.lastIndexOf(File.separator))); diff --git a/plugins/json/src/main/java/org/apache/struts2/json/JSONResult.java b/plugins/json/src/main/java/org/apache/struts2/json/JSONResult.java index 0547e92..2327244 100644 --- a/plugins/json/src/main/java/org/apache/struts2/json/JSONResult.java +++ b/plugins/json/src/main/java/org/apache/struts2/json/JSONResult.java @@ -18,29 +18,26 @@ */ package org.apache.struts2.json; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.regex.Pattern; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - +import com.opensymphony.xwork2.ActionContext; +import com.opensymphony.xwork2.ActionInvocation; +import com.opensymphony.xwork2.Result; +import com.opensymphony.xwork2.inject.Inject; +import com.opensymphony.xwork2.util.ValueStack; +import com.opensymphony.xwork2.util.WildcardUtil; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.struts2.StrutsConstants; -import org.apache.struts2.StrutsStatics; import org.apache.struts2.json.smd.SMDGenerator; -import com.opensymphony.xwork2.ActionContext; -import com.opensymphony.xwork2.ActionInvocation; -import com.opensymphony.xwork2.Result; -import com.opensymphony.xwork2.inject.Inject; -import com.opensymphony.xwork2.util.ValueStack; -import com.opensymphony.xwork2.util.WildcardUtil; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.regex.Pattern; /** * <!-- START SNIPPET: description --> @@ -101,15 +98,15 @@ public class JSONResult implements Result { private String wrapSuffix; private boolean devMode = false; private JSONUtil jsonUtil; - + @Inject(StrutsConstants.STRUTS_I18N_ENCODING) public void setDefaultEncoding(String val) { this.defaultEncoding = val; } - - @Inject(StrutsConstants.STRUTS_DEVMODE) + + @Inject(StrutsConstants.STRUTS_DEVMODE) public void setDevMode(String val) { - this.devMode = BooleanUtils.toBoolean(val); + this.devMode = BooleanUtils.toBoolean(val); } @Inject @@ -188,12 +185,12 @@ public class JSONResult implements Result { public void execute(ActionInvocation invocation) throws Exception { ActionContext actionContext = invocation.getInvocationContext(); - HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST); - HttpServletResponse response = (HttpServletResponse) actionContext.get(StrutsStatics.HTTP_RESPONSE); - + HttpServletRequest request = actionContext.getServletRequest(); + HttpServletResponse response = actionContext.getServletResponse(); + // only permit caching bean information when struts devMode = false cacheBeanInfo = !devMode; - + try { Object rootObject; rootObject = readRootObject(invocation); @@ -224,7 +221,7 @@ public class JSONResult implements Result { protected String createJSONString(HttpServletRequest request, Object rootObject) throws JSONException { String json = jsonUtil.serialize(rootObject, excludeProperties, includeProperties, ignoreHierarchy, - enumAsBean, excludeNullProperties, defaultDateFormat, cacheBeanInfo); + enumAsBean, excludeNullProperties, defaultDateFormat, cacheBeanInfo); json = addCallbackIfApplicable(request, json); return json; } @@ -235,8 +232,8 @@ public class JSONResult implements Result { protected void writeToResponse(HttpServletResponse response, String json, boolean gzip) throws IOException { JSONUtil.writeJSONToResponse(new SerializationParams(response, getEncoding(), isWrapWithComments(), - json, false, gzip, noCache, statusCode, errorCode, prefix, contentType, wrapPrefix, - wrapSuffix)); + json, false, gzip, noCache, statusCode, errorCode, prefix, contentType, wrapPrefix, + wrapSuffix)); } @SuppressWarnings("unchecked") @@ -248,7 +245,7 @@ public class JSONResult implements Result { * Retrieve the encoding * * @return The encoding associated with this template (defaults to the value - * of param 'encoding', if empty default to 'struts.i18n.encoding' property) + * of param 'encoding', if empty default to 'struts.i18n.encoding' property) */ protected String getEncoding() { String encoding = this.encoding; @@ -327,9 +324,9 @@ public class JSONResult implements Result { } /** - * @param ignoreInterfaces Controls whether interfaces should be inspected for method annotations - * You may need to set to this true if your action is a proxy as annotations - * on methods are not inherited + * @param ignoreInterfaces Controls whether interfaces should be inspected for method annotations + * You may need to set to this true if your action is a proxy as annotations + * on methods are not inherited */ public void setIgnoreInterfaces(boolean ignoreInterfaces) { this.ignoreInterfaces = ignoreInterfaces; @@ -337,8 +334,8 @@ public class JSONResult implements Result { /** * @param enumAsBean Controls how Enum's are serialized : If true, an Enum is serialized as a - * name=value pair (name=name()) (default) If false, an Enum is serialized - * as a bean with a special property _name=name() + * name=value pair (name=name()) (default) If false, an Enum is serialized + * as a bean with a special property _name=name() */ public void setEnumAsBean(boolean enumAsBean) { this.enumAsBean = enumAsBean; @@ -423,7 +420,7 @@ public class JSONResult implements Result { } /** - * @param wrapPrefix Text to be inserted at the begining of the response + * @param wrapPrefix Text to be inserted at the begining of the response */ public void setWrapPrefix(String wrapPrefix) { this.wrapPrefix = wrapPrefix; @@ -434,7 +431,7 @@ public class JSONResult implements Result { } /** - * @param wrapSuffix Text to be inserted at the end of the response + * @param wrapSuffix Text to be inserted at the end of the response */ public void setWrapSuffix(String wrapSuffix) { this.wrapSuffix = wrapSuffix; @@ -443,7 +440,7 @@ public class JSONResult implements Result { /** * If defined will be used instead of {@link #defaultEncoding}, you can define it with result * <result name="success" type="json"> - * <param name="encoding">UTF-8</param> + * <param name="encoding">UTF-8</param> * </result> * * @param encoding valid encoding string diff --git a/plugins/json/src/main/java/org/apache/struts2/json/smd/SMDGenerator.java b/plugins/json/src/main/java/org/apache/struts2/json/smd/SMDGenerator.java index 9746aa5..e1c3ce5 100644 --- a/plugins/json/src/main/java/org/apache/struts2/json/smd/SMDGenerator.java +++ b/plugins/json/src/main/java/org/apache/struts2/json/smd/SMDGenerator.java @@ -20,9 +20,8 @@ package org.apache.struts2.json.smd; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; -import org.apache.struts2.StrutsStatics; +import org.apache.logging.log4j.Logger; import org.apache.struts2.json.JSONUtil; import org.apache.struts2.json.annotations.SMD; import org.apache.struts2.json.annotations.SMDMethod; @@ -51,15 +50,15 @@ public class SMDGenerator { public org.apache.struts2.json.smd.SMD generate(ActionInvocation actionInvocation) { ActionContext actionContext = actionInvocation.getInvocationContext(); - HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST); + HttpServletRequest request = actionContext.getServletRequest(); - Class clazz = rootObject.getClass(); + Class<?> clazz = rootObject.getClass(); org.apache.struts2.json.smd.SMD smd = new org.apache.struts2.json.smd.SMD(); // URL smd.setServiceUrl(request.getRequestURI()); // customize SMD - org.apache.struts2.json.annotations.SMD smdAnnotation = (SMD) clazz.getAnnotation(SMD.class); + org.apache.struts2.json.annotations.SMD smdAnnotation = clazz.getAnnotation(SMD.class); if (smdAnnotation != null) { smd.setObjectName(smdAnnotation.objectName()); smd.setServiceType(smdAnnotation.serviceType()); @@ -87,7 +86,7 @@ public class SMDGenerator { // find params for this method processMethodsParameters(method, smdMethod); - } else if(LOG.isDebugEnabled()) { + } else if (LOG.isDebugEnabled()) { LOG.debug("Ignoring property " + method.getName()); } } @@ -137,7 +136,7 @@ public class SMDGenerator { * Find an SMDethodParameter annotation on this array */ private org.apache.struts2.json.annotations.SMDMethodParameter getSMDMethodParameterAnnotation( - Annotation[] annotations) { + Annotation[] annotations) { for (Annotation annotation : annotations) { if (annotation instanceof org.apache.struts2.json.annotations.SMDMethodParameter) return (org.apache.struts2.json.annotations.SMDMethodParameter) annotation; diff --git a/plugins/rest/src/main/java/org/apache/struts2/rest/RestWorkflowInterceptor.java b/plugins/rest/src/main/java/org/apache/struts2/rest/RestWorkflowInterceptor.java index f685fa3..63654ee 100644 --- a/plugins/rest/src/main/java/org/apache/struts2/rest/RestWorkflowInterceptor.java +++ b/plugins/rest/src/main/java/org/apache/struts2/rest/RestWorkflowInterceptor.java @@ -21,12 +21,11 @@ package org.apache.struts2.rest; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; -import com.opensymphony.xwork2.interceptor.ValidationAware; import com.opensymphony.xwork2.inject.Inject; import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor; +import com.opensymphony.xwork2.interceptor.ValidationAware; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.apache.struts2.ServletActionContext; import org.apache.struts2.dispatcher.mapper.ActionMapping; import java.util.HashMap; @@ -62,7 +61,7 @@ import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; * <!-- END SNIPPET: description --> * * <p><u>Interceptor parameters:</u></p> - * + * <p> * <!-- START SNIPPET: parameters --> * * <ul> @@ -71,11 +70,11 @@ import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; * an action / field error is found.</li> * * </ul> - * + * <p> * <!-- END SNIPPET: parameters --> * * <p><u>Extending the interceptor:</u></p> - * + * <p> * <!-- START SNIPPET: extending --> * <p> * There are no known extension points for this interceptor. @@ -86,14 +85,14 @@ import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; * * <pre> * <!-- START SNIPPET: example --> - * + * * <action name="someAction" class="com.examples.SomeAction"> * <interceptor-ref name="params"/> * <interceptor-ref name="validation"/> * <interceptor-ref name="workflow"/> * <result name="success">good_result.ftl</result> * </action> - * + * * <-- In this case myMethod as well as mySecondMethod of the action class * will not pass through the workflow process --> * <action name="someAction" class="com.examples.SomeAction"> @@ -114,8 +113,8 @@ import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; * <interceptor-ref name="validation"/> * <interceptor-ref name="workflow"> * <param name="inputResultName">error</param> -* <param name="excludeMethods">*</param> -* <param name="includeMethods">myWorkflowMethod</param> + * <param name="excludeMethods">*</param> + * <param name="includeMethods">myWorkflowMethod</param> * </interceptor-ref> * <result name="success">good_result.ftl</result> * </action> @@ -130,14 +129,14 @@ import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; * @author tm_jee */ public class RestWorkflowInterceptor extends MethodFilterInterceptor { - - private static final long serialVersionUID = 7563014655616490865L; - private static final Logger LOG = LogManager.getLogger(RestWorkflowInterceptor.class); - - private String inputResultName = Action.INPUT; - - private ContentTypeHandlerManager manager; + private static final long serialVersionUID = 7563014655616490865L; + + private static final Logger LOG = LogManager.getLogger(RestWorkflowInterceptor.class); + + private String inputResultName = Action.INPUT; + + private ContentTypeHandlerManager manager; private String postMethodName = "create"; private String editMethodName = "edit"; @@ -172,26 +171,26 @@ public class RestWorkflowInterceptor extends MethodFilterInterceptor { } @Inject - public void setContentTypeHandlerManager(ContentTypeHandlerManager mgr) { - this.manager = mgr; - } - - /** - * Set the <code>inputResultName</code> (result name to be returned when - * a action / field error is found registered). Default to {@link Action#INPUT} - * - * @param inputResultName what result name to use when there was validation error(s). - */ - public void setInputResultName(String inputResultName) { - this.inputResultName = inputResultName; - } - - /** - * Intercept {@link ActionInvocation} and processes the errors using the {@link org.apache.struts2.rest.handler.ContentTypeHandler} - * appropriate for the request. - * - * @return String result name - */ + public void setContentTypeHandlerManager(ContentTypeHandlerManager mgr) { + this.manager = mgr; + } + + /** + * Set the <code>inputResultName</code> (result name to be returned when + * a action / field error is found registered). Default to {@link Action#INPUT} + * + * @param inputResultName what result name to use when there was validation error(s). + */ + public void setInputResultName(String inputResultName) { + this.inputResultName = inputResultName; + } + + /** + * Intercept {@link ActionInvocation} and processes the errors using the {@link org.apache.struts2.rest.handler.ContentTypeHandler} + * appropriate for the request. + * + * @return String result name + */ protected String doIntercept(ActionInvocation invocation) throws Exception { Object action = invocation.getAction(); @@ -199,26 +198,26 @@ public class RestWorkflowInterceptor extends MethodFilterInterceptor { ValidationAware validationAwareAction = (ValidationAware) action; if (validationAwareAction.hasErrors()) { - LOG.debug("Errors on action {}, returning result name 'input'", validationAwareAction); - ActionMapping mapping = (ActionMapping) ActionContext.getContext().get(ServletActionContext.ACTION_MAPPING); - String method = inputResultName; + LOG.debug("Errors on action {}, returning result name 'input'", validationAwareAction); + ActionMapping mapping = ActionContext.getContext().getActionMapping(); + String method = inputResultName; if (postMethodName.equals(mapping.getMethod())) { - method = newMethodName; + method = newMethodName; } else if (putMethodName.equals(mapping.getMethod())) { - method = editMethodName; + method = editMethodName; } - - - HttpHeaders info = new DefaultHttpHeaders() - .disableCaching() - .renderResult(method) - .withStatus(validationFailureStatusCode); - - Map<String, Object> errors = new HashMap<>(); - - errors.put("actionErrors", validationAwareAction.getActionErrors()); - errors.put("fieldErrors", validationAwareAction.getFieldErrors()); - return manager.handleResult(invocation, info, errors); + + + HttpHeaders info = new DefaultHttpHeaders() + .disableCaching() + .renderResult(method) + .withStatus(validationFailureStatusCode); + + Map<String, Object> errors = new HashMap<>(); + + errors.put("actionErrors", validationAwareAction.getActionErrors()); + errors.put("fieldErrors", validationAwareAction.getFieldErrors()); + return manager.handleResult(invocation, info, errors); } } diff --git a/plugins/sitemesh/src/main/java/org/apache/struts2/sitemesh/FreemarkerDecoratorServlet.java b/plugins/sitemesh/src/main/java/org/apache/struts2/sitemesh/FreemarkerDecoratorServlet.java index 85ef896..b6bd1ac 100644 --- a/plugins/sitemesh/src/main/java/org/apache/struts2/sitemesh/FreemarkerDecoratorServlet.java +++ b/plugins/sitemesh/src/main/java/org/apache/struts2/sitemesh/FreemarkerDecoratorServlet.java @@ -22,13 +22,17 @@ import com.opensymphony.module.sitemesh.HTMLPage; import com.opensymphony.module.sitemesh.RequestConstants; import com.opensymphony.xwork2.ActionContext; import freemarker.core.InvalidReferenceException; -import freemarker.template.*; +import freemarker.template.Configuration; +import freemarker.template.ObjectWrapper; +import freemarker.template.SimpleHash; +import freemarker.template.Template; +import freemarker.template.TemplateException; +import freemarker.template.TemplateModel; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.struts2.ServletActionContext; -import org.apache.struts2.StrutsStatics; +import org.apache.struts2.StrutsException; import org.apache.struts2.dispatcher.Dispatcher; -import org.apache.struts2.dispatcher.StrutsRequestWrapper; import org.apache.struts2.dispatcher.listener.StrutsListener; import org.apache.struts2.views.freemarker.FreemarkerManager; import org.apache.struts2.views.freemarker.ScopesHashModel; @@ -146,10 +150,13 @@ public class FreemarkerDecoratorServlet extends freemarker.ext.servlet.Freemarke setBrowserCachingPolicy(response); ServletContext servletContext = getServletContext(); - ScopesHashModel model = (ScopesHashModel) request.getAttribute(freemarkerManager.ATTR_TEMPLATE_MODEL); + ScopesHashModel model = (ScopesHashModel) request.getAttribute(FreemarkerManager.ATTR_TEMPLATE_MODEL); try { if (model == null) { ActionContext ctx = ServletActionContext.getActionContext(request); + if (ctx == null) { + throw new StrutsException("ActionContext is null! Freemarker accessed out of action?"); + } model = freemarkerManager.buildTemplateModel(ctx.getValueStack(), ctx.getActionInvocation().getAction(), servletContext, request, response, wrapper); } @@ -165,15 +172,15 @@ public class FreemarkerDecoratorServlet extends freemarker.ext.servlet.Freemarke } } catch (InvalidReferenceException x) { // this exception is thrown if there is an error processing a reference. We want to report these! - HttpServletRequest req = ((StrutsRequestWrapper) ActionContext.getContext().get("com.opensymphony.xwork2.dispatcher.HttpServletRequest")); + HttpServletRequest req = ActionContext.getContext().getServletRequest(); String resultCode = ActionContext.getContext().getActionInvocation().getResultCode(); - if (req == null){ + if (req == null) { req = request; } StringBuilder msgBuf = new StringBuilder("Error applying freemarker template to\n request: "); msgBuf.append(req.getRequestURL()); - if (req.getQueryString() != null){ + if (req.getQueryString() != null) { msgBuf.append("?").append(req.getQueryString()); } msgBuf.append(" with resultCode: ").append(resultCode).append(".\n\n").append(x.getMessage()); @@ -186,14 +193,14 @@ public class FreemarkerDecoratorServlet extends freemarker.ext.servlet.Freemarke // constructor-passed throwable won't show up automatically in // stack traces. try { - e.getClass().getMethod("initCause", new Class[]{Throwable.class}).invoke(e, new Object[]{x}); + e.getClass().getMethod("initCause", new Class[]{Throwable.class}).invoke(e, x); } catch (Exception ex) { // Can't set init cause, we're probably running on a pre-1.4 // JDK, oh well... } throw e; } catch (TemplateException te) { - if (config.getTemplateExceptionHandler().getClass().getName().indexOf("Debug") != -1) { + if (config.getTemplateExceptionHandler().getClass().getName().contains("Debug")) { this.log("Error executing FreeMarker template", te); } else { ServletException e = new ServletException("Error executing FreeMarker template", te); @@ -202,7 +209,7 @@ public class FreemarkerDecoratorServlet extends freemarker.ext.servlet.Freemarke // constructor-passed throwable won't show up automatically in // stack traces. try { - e.getClass().getMethod("initCause", new Class[]{Throwable.class}).invoke(e, new Object[]{te}); + e.getClass().getMethod("initCause", new Class[]{Throwable.class}).invoke(e, te); } catch (Exception ex) { // Can't set init cause, we're probably running on a pre-1.4 // JDK, oh well... @@ -320,7 +327,7 @@ public class FreemarkerDecoratorServlet extends freemarker.ext.servlet.Freemarke // HTTP/1.0 res.setHeader("Pragma", "no-cache"); // Last resort for those that ignore all of the above - res.setHeader("Expires", freemarkerManager.EXPIRATION_DATE); + res.setHeader("Expires", FreemarkerManager.EXPIRATION_DATE); } } }