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.interceptor;
22
23 import java.io.Serializable;
24
25 import com.opensymphony.xwork2.ActionInvocation;
26
27 /***
28 * Background thread to be executed by the ExecuteAndWaitInterceptor.
29 *
30 */
31 public class BackgroundProcess implements Serializable {
32
33 private static final long serialVersionUID = 3884464776311686443L;
34
35 protected Object action;
36 protected ActionInvocation invocation;
37 protected String result;
38 protected Exception exception;
39 protected boolean done;
40
41 /***
42 * Constructs a background process
43 *
44 * @param threadName The thread name
45 * @param invocation The action invocation
46 * @param threadPriority The thread priority
47 */
48 public BackgroundProcess(String threadName, final ActionInvocation invocation, int threadPriority) {
49 this.invocation = invocation;
50 this.action = invocation.getAction();
51 try {
52 final Thread t = new Thread(new Runnable() {
53 public void run() {
54 try {
55 beforeInvocation();
56 result = invocation.invokeActionOnly();
57 afterInvocation();
58 } catch (Exception e) {
59 exception = e;
60 }
61
62 done = true;
63 }
64 });
65 t.setName(threadName);
66 t.setPriority(threadPriority);
67 t.start();
68 } catch (Exception e) {
69 exception = e;
70 }
71 }
72
73 /***
74 * Called before the background thread determines the result code
75 * from the ActionInvocation.
76 *
77 * @throws Exception any exception thrown will be thrown, in turn, by the ExecuteAndWaitInterceptor
78 */
79 protected void beforeInvocation() throws Exception {
80 }
81
82 /***
83 * Called after the background thread determines the result code
84 * from the ActionInvocation, but before the background thread is
85 * marked as done.
86 *
87 * @throws Exception any exception thrown will be thrown, in turn, by the ExecuteAndWaitInterceptor
88 */
89 protected void afterInvocation() throws Exception {
90 }
91
92 /***
93 * Retrieves the action.
94 *
95 * @return the action.
96 */
97 public Object getAction() {
98 return action;
99 }
100
101 /***
102 * Retrieves the action invocation.
103 *
104 * @return the action invocation
105 */
106 public ActionInvocation getInvocation() {
107 return invocation;
108 }
109
110 /***
111 * Gets the result of the background process.
112 *
113 * @return the result; <tt>null</tt> if not done.
114 */
115 public String getResult() {
116 return result;
117 }
118
119 /***
120 * Gets the exception if any was thrown during the execution of the background process.
121 *
122 * @return the exception or <tt>null</tt> if no exception was thrown.
123 */
124 public Exception getException() {
125 return exception;
126 }
127
128 /***
129 * Returns the status of the background process.
130 *
131 * @return <tt>true</tt> if finished, <tt>false</tt> otherwise
132 */
133 public boolean isDone() {
134 return done;
135 }
136 }