-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathAsyncTask.java
321 lines (283 loc) · 9.99 KB
/
AsyncTask.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package org.vaadin.flow.helper;
import com.vaadin.flow.component.*;
import com.vaadin.flow.router.BeforeLeaveEvent;
import com.vaadin.flow.server.Command;
import com.vaadin.flow.server.VaadinSession;
import com.vaadin.flow.shared.Registration;
import com.vaadin.flow.shared.communication.PushMode;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Asynchronous task created by {@link AsyncManager#register(Component, Action)}
*
* @author Artem Godin
* @see AsyncManager
*/
public class AsyncTask extends Task {
//--- Defaults
/**
* Value for {@link #missedPolls} for push enabled tasks
*/
private static final int PUSH_ACTIVE = -1;
//--- Fields
/**
* {@link FutureTask} representing action
*/
private FutureTask<AsyncTask> task;
/**
* Registration for PollEvent listener
*/
private Registration pollingListenerRegistration;
/**
* Registration for DetachEvent listener
*/
private Registration componentDetachListenerRegistration;
/**
* Registration for UI DetachEvent listener
*/
private Registration uiDetachListenerRegistration;
/**
* Registration for BeforeLeave event listener
*/
private Registration beforeLeaveListenerRegistration;
/**
* Number of poll events happened while action is executing, or {@link #PUSH_ACTIVE} if
* push is used for current task
*/
private final AtomicInteger missedPolls = new AtomicInteger();
/**
* {@code true}, if thread may be interrupted if UI/Component detaches
*/
private boolean mayInterrupt = true;
/**
* Create a new task
*/
AsyncTask(AsyncManager asyncManager) {
super(asyncManager);
}
//--- Public methods
/**
* Perform command in UI context. It uses {@link UI#accessSynchronously(Command)} internally.
*
* @param command Command to run
*/
public void push(Command command) {
if (getUI() == null) {
return;
}
boolean mustPush = missedPolls.get() == PUSH_ACTIVE && getUI().getPushConfiguration().getPushMode() == PushMode.MANUAL;
getUI().accessSynchronously(() -> {
try {
command.execute();
if (mustPush) {
getUI().push();
}
} catch (UIDetachedException ignore) {
// Do not report
// How could this even happen?
} catch (Exception e) {
// Dump
getAsyncManager().handleException(this, e);
}
});
}
/**
* Cancel and unregister the task. Thread interruption behaviour is controlled
* by {@link AsyncTask#allowThreadInterrupt()} and
* {@link AsyncTask#preventThreadInterrupt()} methods.
*/
public void cancel() {
if (!task.isCancelled() && !task.isDone()) {
task.cancel(mayInterrupt);
}
getAsyncManager().handleTaskStateChanged(this, AsyncManager.TaskStateHandler.State.CANCELED);
remove();
}
/**
* Wait for the task to finish.
*
* @throws ExecutionException
* @throws InterruptedException
*/
public void await() throws ExecutionException, InterruptedException {
task.get();
}
/**
* Allow worker thread to be interrupted when UI or Component detaches. Default behaviour.
*/
public void allowThreadInterrupt() {
this.mayInterrupt = true;
}
/**
* Prevent worker thread interruption when UI or Component detaches.
*/
public void preventThreadInterrupt() {
this.mayInterrupt = false;
}
//--- Implementation
/**
* Register action
*
* @param ui UI owning current view
* @param action Action
*/
public void register(UI ui, Component component, Action action) {
setUI(ui);
if (ui.getPushConfiguration().getPushMode().isEnabled()) {
registerPush(component, action);
} else {
registerPoll(component, action);
}
}
/**
* Register action for push mode
*
* @param action Action
*/
private void registerPush(Component component, Action action) {
add();
missedPolls.set(PUSH_ACTIVE);
task = createFutureTask(action);
componentDetachListenerRegistration = component.addDetachListener(this::onDetachEvent);
uiDetachListenerRegistration = getUI().addDetachListener(this::onDetachEvent);
beforeLeaveListenerRegistration = getUI().addBeforeLeaveListener(this::onBeforeLeaveEvent);
execute();
}
/**
* Register action for polling
*
* @param action Action
*/
private void registerPoll(Component component, Action action) {
add();
task = createFutureTask(action);
pollingListenerRegistration = getUI().addPollListener(this::onPollEvent);
uiDetachListenerRegistration = getUI().addDetachListener(this::onDetachEvent);
componentDetachListenerRegistration = component.addDetachListener(this::onDetachEvent);
beforeLeaveListenerRegistration = getUI().addBeforeLeaveListener(this::onBeforeLeaveEvent);
getAsyncManager().adjustPollingInterval(getUI());
execute();
}
/**
* Wrap action with {@link FutureTask}
*
* @param action Action
* @return Action wrapped with exception handling
*/
private FutureTask<AsyncTask> createFutureTask(Action action) {
return new FutureTask<>(() -> {
try {
getAsyncManager().handleTaskStateChanged(this, AsyncManager.TaskStateHandler.State.RUNNING);
// Session + Security für den Async-Task setzen
VaadinSession.setCurrent(getUI().getSession());
SecurityContextHolder.setContext((SecurityContext) VaadinSession.getCurrent().getSession().getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY));
action.run(this);
} catch (UIDetachedException ignore) {
// Do not report
} catch (InterruptedException e) {
// Interrupt current thread
Thread.currentThread().interrupt();
} catch (Exception e) {
// Dump
getAsyncManager().handleException(this, e);
} finally {
getAsyncManager().handleTaskStateChanged(this, AsyncManager.TaskStateHandler.State.DONE);
remove();
}
}, this);
}
/**
* Execute task in {@link AsyncManager#getExecutorService()} executor
*/
private void execute() {
getAsyncManager().getExecutorService().execute(task);
}
/**
* Add current task to {@link AsyncManager#asyncTasks}
*/
private void add() {
getAsyncManager().addAsyncTask(getUI(), this);
}
/**
* Remove current task from {@link AsyncManager#asyncTasks} and unregister all listeners
*/
private void remove() {
if (getUI() != null) {
getAsyncManager().removeAsyncTask(getUI(), this);
// Polling interval needs to be adjusted if task is finished
try {
getUI().accessSynchronously(() -> {
getAsyncManager().adjustPollingInterval(getUI());
if (componentDetachListenerRegistration != null) {
componentDetachListenerRegistration.remove();
}
if (uiDetachListenerRegistration != null) {
uiDetachListenerRegistration.remove();
}
if (pollingListenerRegistration != null) {
pollingListenerRegistration.remove();
}
if (beforeLeaveListenerRegistration != null) {
beforeLeaveListenerRegistration.remove();
}
componentDetachListenerRegistration = null;
uiDetachListenerRegistration = null;
pollingListenerRegistration = null;
beforeLeaveListenerRegistration = null;
});
} catch (UIDetachedException ignore) {
// ignore detached ui -- there will be no polling events for them anyway
}
setUI(null);
}
}
/**
* Get current polling interval based on {@link #missedPolls} and {@link AsyncManager#pollingIntervals}
*
* @return Polling interval in milliseconds
*/
int getPollingInterval() {
int missed = missedPolls.get();
if (missed == PUSH_ACTIVE) {
return Integer.MAX_VALUE;
}
if (missed >= getAsyncManager().getPollingIntervals().length) {
return getAsyncManager().getPollingIntervals()[getAsyncManager().getPollingIntervals().length - 1];
}
return getAsyncManager().getPollingIntervals()[missed];
}
//--- Event listeners
/**
* Invoked when a Detach event has been fired.
*
* @param ignore component event
*/
private void onDetachEvent(DetachEvent ignore) {
// cancel deregisters all listeners via remove()
cancel();
}
/**
* Invoked when a BeforeLeave event has been fired.
*
* @param ignore component event
*/
private void onBeforeLeaveEvent(BeforeLeaveEvent ignore) {
// cancel deregisters all listeners
cancel();
}
/**
* Invoked when a Poll event has been fired.
*
* @param ignore component event
*/
private void onPollEvent(PollEvent ignore) {
if (missedPolls.get() != PUSH_ACTIVE) {
missedPolls.incrementAndGet();
getAsyncManager().adjustPollingInterval(getUI());
}
}
}