1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.javascript.background;
16
17 import java.io.IOException;
18 import java.io.ObjectInputStream;
19 import java.io.ObjectOutputStream;
20 import java.lang.ref.WeakReference;
21 import java.util.PriorityQueue;
22 import java.util.concurrent.atomic.AtomicInteger;
23
24 import org.apache.commons.logging.Log;
25 import org.apache.commons.logging.LogFactory;
26 import org.htmlunit.Page;
27 import org.htmlunit.WebWindow;
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45 @SuppressWarnings("PMD.AvoidSynchronizedAtMethodLevel")
46 class JavaScriptJobManagerImpl implements JavaScriptJobManager {
47
48
49
50
51
52 private transient WeakReference<WebWindow> window_;
53
54
55
56
57
58 private transient volatile boolean startEventLoop_;
59
60
61
62
63
64 private transient PriorityQueue<JavaScriptJob> scheduledJobsQ_ = new PriorityQueue<>();
65
66 private transient JavaScriptJob currentlyRunningJob_;
67
68
69 private static final AtomicInteger NEXT_JOB_ID_ = new AtomicInteger(1);
70
71
72 private static final Log LOG = LogFactory.getLog(JavaScriptJobManagerImpl.class);
73
74
75
76
77
78
79 JavaScriptJobManagerImpl(final WebWindow window) {
80 window_ = new WeakReference<>(window);
81 }
82
83
84 @Override
85 public synchronized int getJobCount() {
86 return scheduledJobsQ_.size() + (currentlyRunningJob_ != null ? 1 : 0);
87 }
88
89
90 @Override
91 public synchronized int getJobCount(final JavaScriptJobFilter filter) {
92 if (filter == null) {
93 return scheduledJobsQ_.size() + (currentlyRunningJob_ != null ? 1 : 0);
94 }
95
96 int count = 0;
97 if (currentlyRunningJob_ != null && filter.passes(currentlyRunningJob_)) {
98 count++;
99 }
100 for (final JavaScriptJob job : scheduledJobsQ_) {
101 if (filter.passes(job)) {
102 count++;
103 }
104 }
105 return count;
106 }
107
108
109 @Override
110 public int addJob(final JavaScriptJob job, final Page page) {
111 final WebWindow w = getWindow();
112 if (w == null) {
113
114
115
116
117 return 0;
118 }
119 if (w.getEnclosedPage() != page) {
120
121
122
123
124 return 0;
125 }
126 final int id = NEXT_JOB_ID_.getAndIncrement();
127 job.setId(Integer.valueOf(id));
128
129 if (startEventLoop_) {
130
131 startEventLoop_ = false;
132 w.getWebClient().getJavaScriptEngine().registerWindowAndMaybeStartEventLoop(w);
133 }
134
135 synchronized (this) {
136 scheduledJobsQ_.add(job);
137
138 if (LOG.isDebugEnabled()) {
139 LOG.debug("job added to queue");
140 LOG.debug(" window is: " + w);
141 LOG.debug(" added job: " + job);
142 LOG.debug("after adding job to the queue, the queue is: ");
143 printQueue();
144 }
145
146 notifyAll();
147 }
148
149 return id;
150 }
151
152
153 @Override
154 public synchronized void removeJob(final int id) {
155 for (final JavaScriptJob job : scheduledJobsQ_) {
156 final int jobId = job.getId().intValue();
157 if (jobId == id) {
158 scheduledJobsQ_.remove(job);
159 notifyAll();
160 break;
161 }
162 }
163 }
164
165
166 @Override
167 public synchronized void stopJob(final int id) {
168
169
170 removeJob(id);
171 }
172
173
174 @Override
175 public synchronized void removeAllJobs() {
176 scheduledJobsQ_.clear();
177 notifyAll();
178 }
179
180
181 @Override
182 @SuppressWarnings("PMD.GuardLogStatement")
183 public int waitForJobs(final long timeoutMillis) {
184 final boolean debug = LOG.isDebugEnabled();
185 if (debug) {
186 LOG.debug("Waiting for all jobs to finish (will wait max " + timeoutMillis + " millis).");
187 }
188 if (timeoutMillis > 0) {
189 long now = System.currentTimeMillis();
190 final long end = now + timeoutMillis;
191
192 synchronized (this) {
193 while (getJobCount() > 0 && now < end) {
194 try {
195 wait(end - now);
196 }
197 catch (final InterruptedException e) {
198 LOG.error("InterruptedException while in waitForJobs", e);
199
200
201 Thread.currentThread().interrupt();
202 }
203
204
205 now = System.currentTimeMillis();
206 }
207 }
208 }
209 final int jobs = getJobCount();
210 if (debug) {
211 LOG.debug("Finished waiting for all jobs to finish (final job count is " + jobs + ").");
212 }
213 return jobs;
214 }
215
216
217 @Override
218 public int waitForJobsStartingBefore(final long delayMillis) {
219 return waitForJobsStartingBefore(delayMillis, -1, null);
220 }
221
222
223 @Override
224 public int waitForJobsStartingBefore(final long delayMillis, final long timeoutMillis) {
225 return waitForJobsStartingBefore(delayMillis, timeoutMillis, null);
226 }
227
228
229 @Override
230 @SuppressWarnings("PMD.GuardLogStatement")
231 public int waitForJobsStartingBefore(final long delayMillis, final JavaScriptJobFilter filter) {
232 return waitForJobsStartingBefore(delayMillis, -1, filter);
233 }
234
235
236 @Override
237 @SuppressWarnings("PMD.GuardLogStatement")
238 public int waitForJobsStartingBefore(final long delayMillis, final long timeoutMillis,
239 final JavaScriptJobFilter filter) {
240 final boolean debug = LOG.isDebugEnabled();
241
242 long now = System.currentTimeMillis();
243 long end = now + timeoutMillis;
244 if (timeoutMillis < 0 || timeoutMillis < delayMillis) {
245 end = -1;
246 }
247
248 final long latestExecutionTime = System.currentTimeMillis() + delayMillis;
249 if (debug) {
250 LOG.debug("Waiting for all jobs that have execution time before "
251 + delayMillis + " (" + latestExecutionTime + ") to finish");
252 }
253
254 final long interval = Math.max(40, delayMillis);
255 synchronized (this) {
256 JavaScriptJob earliestJob = getEarliestJob(filter);
257 boolean pending = earliestJob != null && earliestJob.getTargetExecutionTime() < latestExecutionTime;
258 pending = pending
259 || (
260 currentlyRunningJob_ != null
261 && (filter == null || filter.passes(currentlyRunningJob_))
262 && currentlyRunningJob_.getTargetExecutionTime() < latestExecutionTime
263 );
264
265 while (pending && (end == -1 || now < end)) {
266 try {
267 final long waitTime = (end == -1)
268 ? Math.max(40, interval)
269 : Math.max(40, Math.min(interval, end - now));
270 wait(waitTime);
271 }
272 catch (final InterruptedException e) {
273 LOG.error("InterruptedException while in waitForJobsStartingBefore", e);
274
275
276 Thread.currentThread().interrupt();
277 }
278
279 earliestJob = getEarliestJob(filter);
280 pending = earliestJob != null && earliestJob.getTargetExecutionTime() < latestExecutionTime;
281 pending = pending
282 || (
283 currentlyRunningJob_ != null
284 && (filter == null || filter.passes(currentlyRunningJob_))
285 && currentlyRunningJob_.getTargetExecutionTime() < latestExecutionTime
286 );
287 if (pending) {
288 now = System.currentTimeMillis();
289 }
290 }
291 }
292
293 final int jobs = getJobCount(filter);
294 if (debug) {
295 LOG.debug("Finished waiting for all jobs that have target execution time earlier than "
296 + latestExecutionTime + ", final job count is " + jobs);
297 }
298 return jobs;
299 }
300
301
302 @Override
303 public synchronized void shutdown() {
304 scheduledJobsQ_.clear();
305 notifyAll();
306 }
307
308
309
310
311
312
313
314
315 private WebWindow getWindow() {
316 return window_.get();
317 }
318
319
320
321
322 private void printQueue() {
323 if (LOG.isDebugEnabled()) {
324 LOG.debug("------ printing JavaScript job queue -----");
325 LOG.debug(" number of jobs on the queue: " + scheduledJobsQ_.size());
326 int count = 1;
327 for (final JavaScriptJob job : scheduledJobsQ_) {
328 LOG.debug(" " + count + ") Job target execution time: " + job.getTargetExecutionTime());
329 LOG.debug(" job to string: " + job);
330 LOG.debug(" job id: " + job.getId());
331 if (job.isPeriodic()) {
332 LOG.debug(" period: " + job.getPeriod().intValue());
333 }
334 count++;
335 }
336 LOG.debug("------------------------------------------");
337 }
338 }
339
340
341
342
343 @Override
344 public synchronized String jobStatusDump(final JavaScriptJobFilter filter) {
345 final String lineSeparator = System.lineSeparator();
346
347 final StringBuilder status = new StringBuilder(110)
348 .append("------ JavaScript job status -----")
349 .append(lineSeparator);
350
351 if (null != currentlyRunningJob_ && (filter == null || filter.passes(currentlyRunningJob_))) {
352 status.append(" current running job: ").append(currentlyRunningJob_.toString())
353 .append(" job id: ").append(currentlyRunningJob_.getId())
354 .append(lineSeparator)
355 .append(lineSeparator)
356 .append(lineSeparator);
357 }
358 status.append(" number of jobs on the queue: ")
359 .append(scheduledJobsQ_.size())
360 .append(lineSeparator);
361
362 int count = 1;
363 for (final JavaScriptJob job : scheduledJobsQ_) {
364 if (filter == null || filter.passes(job)) {
365 final long now = System.currentTimeMillis();
366 final long execTime = job.getTargetExecutionTime();
367 status.append(" ").append(count).append(") Job target execution time: ")
368 .append(execTime).append(" (should start in ")
369 .append((execTime - now) / 1000d).append("s)")
370 .append(lineSeparator)
371 .append(" job to string: ").append(job)
372 .append(lineSeparator).append(" job id: ").append(job.getId())
373 .append(lineSeparator);
374 if (job.isPeriodic()) {
375 status.append(" period: ")
376 .append(job.getPeriod().toString())
377 .append(lineSeparator);
378 }
379 count++;
380 }
381 }
382 status.append("------------------------------------------")
383 .append(lineSeparator);
384
385 return status.toString();
386 }
387
388
389
390
391 @Override
392 public synchronized JavaScriptJob getEarliestJob() {
393 return scheduledJobsQ_.peek();
394 }
395
396
397
398
399 @Override
400 public synchronized JavaScriptJob getEarliestJob(final JavaScriptJobFilter filter) {
401 if (filter == null) {
402 return scheduledJobsQ_.peek();
403 }
404
405 for (final JavaScriptJob job : scheduledJobsQ_) {
406 if (filter.passes(job)) {
407 return job;
408 }
409 }
410 return null;
411 }
412
413
414
415
416 @Override
417 @SuppressWarnings("PMD.GuardLogStatement")
418 public boolean runSingleJob(final JavaScriptJob givenJob) {
419 assert givenJob != null;
420 final JavaScriptJob job = getEarliestJob();
421 if (job != givenJob) {
422 return false;
423 }
424
425 final long currentTime = System.currentTimeMillis();
426 if (job.getTargetExecutionTime() > currentTime) {
427 return false;
428 }
429
430 final boolean debug = LOG.isDebugEnabled();
431
432 synchronized (this) {
433 if (scheduledJobsQ_.remove(job)) {
434 currentlyRunningJob_ = job;
435
436 }
437
438
439
440 if (job.isPeriodic()) {
441 final long jobPeriod = job.getPeriod().longValue();
442
443
444 final long missedPeriods = (currentTime - job.getTargetExecutionTime()) / jobPeriod + 1;
445 job.setTargetExecutionTime(job.getTargetExecutionTime() + missedPeriods * jobPeriod);
446
447
448 if (debug) {
449 LOG.debug("Rescheduling periodic job " + job);
450 }
451 scheduledJobsQ_.add(job);
452 notifyAll();
453 }
454 }
455
456 if (debug) {
457 final String periodicJob = job.isPeriodic() ? "interval " : "";
458 LOG.debug("Starting " + periodicJob + "job " + job);
459 }
460 try {
461 job.run();
462 }
463 catch (final RuntimeException e) {
464 LOG.error("Job run failed with unexpected RuntimeException: " + e.getMessage(), e);
465 }
466 finally {
467 synchronized (this) {
468 if (job == currentlyRunningJob_) {
469 currentlyRunningJob_ = null;
470 }
471 notifyAll();
472 }
473 }
474 if (debug) {
475 final String periodicJob = job.isPeriodic() ? "interval " : "";
476 LOG.debug("Finished " + periodicJob + "job " + job);
477 }
478 return true;
479 }
480
481
482
483
484
485
486
487
488
489 private void writeObject(final ObjectOutputStream out) throws IOException {
490 out.defaultWriteObject();
491 out.writeObject(getWindow());
492 }
493
494
495
496
497
498
499
500
501 private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
502 in.defaultReadObject();
503 window_ = new WeakReference<>((WebWindow) in.readObject());
504 startEventLoop_ = true;
505
506
507 scheduledJobsQ_ = new PriorityQueue<>();
508 currentlyRunningJob_ = null;
509 }
510 }