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