1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.apache.struts2.portlet.interceptor;
22
23 import com.opensymphony.xwork2.ActionInvocation;
24 import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
25 import com.opensymphony.xwork2.util.CompoundRoot;
26 import com.opensymphony.xwork2.util.TextUtils;
27 import com.opensymphony.xwork2.util.ValueStack;
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30 import org.apache.struts2.portlet.PortletActionConstants;
31 import org.apache.struts2.portlet.dispatcher.DirectRenderFromEventAction;
32
33 import javax.portlet.ActionResponse;
34 import javax.portlet.RenderRequest;
35 import java.util.Map;
36
37 public class PortletStateInterceptor extends AbstractInterceptor implements PortletActionConstants {
38
39 private final static Log LOG = LogFactory.getLog(PortletStateInterceptor.class);
40
41 private static final long serialVersionUID = 6138452063353911784L;
42
43 @Override
44 public String intercept(ActionInvocation invocation) throws Exception {
45 Integer phase = (Integer) invocation.getInvocationContext().get(PHASE);
46 if (RENDER_PHASE.equals(phase)) {
47 restoreStack(invocation);
48 return invocation.invoke();
49 } else if (EVENT_PHASE.equals(phase)) {
50 try {
51 return invocation.invoke();
52 } finally {
53 saveStack(invocation);
54 }
55 } else {
56 return invocation.invoke();
57 }
58 }
59
60 @SuppressWarnings("unchecked")
61 private void saveStack(ActionInvocation invocation) {
62 Map session = invocation.getInvocationContext().getSession();
63 session.put(STACK_FROM_EVENT_PHASE, invocation.getStack());
64 ActionResponse actionResponse = (ActionResponse) invocation.getInvocationContext().get(RESPONSE);
65 actionResponse.setRenderParameter(EVENT_ACTION, "true");
66 }
67
68 @SuppressWarnings("unchecked")
69 private void restoreStack(ActionInvocation invocation) {
70 RenderRequest request = (RenderRequest) invocation.getInvocationContext().get(REQUEST);
71 if (TextUtils.stringSet(request.getParameter(EVENT_ACTION))) {
72 Map session = invocation.getInvocationContext().getSession();
73 if(!isProperPrg(invocation)) {
74 LOG.debug("Restoring value stack from event phase");
75 ValueStack oldStack = (ValueStack) invocation.getInvocationContext().getSession().get(
76 STACK_FROM_EVENT_PHASE);
77 if (oldStack != null) {
78 CompoundRoot oldRoot = oldStack.getRoot();
79 ValueStack currentStack = invocation.getStack();
80 CompoundRoot root = currentStack.getRoot();
81 root.addAll(oldRoot);
82 LOG.debug("Restored stack");
83 }
84 }
85 else {
86 LOG.debug("Won't restore stack from event phase since it's a proper PRG request");
87 }
88 }
89 }
90
91 private boolean isProperPrg(ActionInvocation invocation) {
92 return !(invocation.getAction() instanceof DirectRenderFromEventAction);
93 }
94
95 }