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