1 package com.atlassian.webdriver.testing.rule;
2
3 import com.atlassian.webdriver.LifecycleAwareWebDriverGrid;
4 import org.junit.rules.TestWatcher;
5 import org.junit.runner.Description;
6
7 import javax.annotation.concurrent.ThreadSafe;
8 import java.util.Iterator;
9 import java.util.Queue;
10 import java.util.Timer;
11 import java.util.TimerTask;
12 import java.util.concurrent.ConcurrentLinkedQueue;
13 import java.util.concurrent.TimeUnit;
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 @ThreadSafe
39 public class DriverCleanupRule extends TestWatcher
40 {
41
42 private static final Timer KILLER_TIMER = new Timer("Atlassian-BrowserKiller", true);
43 private static final Queue<TimerTask> KILLER_TASKS = new ConcurrentLinkedQueue<TimerTask>();
44
45 private final long timeout;
46 private final TimeUnit timeUnit;
47
48 public DriverCleanupRule(long timeout, TimeUnit timeUnit)
49 {
50 this.timeout = timeout;
51 this.timeUnit = timeUnit;
52 }
53
54 public DriverCleanupRule()
55 {
56 this(3, TimeUnit.SECONDS);
57 }
58
59 @Override
60 protected void starting(Description description)
61 {
62 for (Iterator<TimerTask> tasks = KILLER_TASKS.iterator(); tasks.hasNext();)
63 {
64 tasks.next().cancel();
65 tasks.remove();
66 }
67 }
68
69 @Override
70 protected void finished(Description description)
71 {
72 final TimerTask newKiller = new BrowserKiller();
73 KILLER_TASKS.add(newKiller);
74 KILLER_TIMER.schedule(newKiller, timeUnit.toMillis(timeout));
75 }
76
77 private static final class BrowserKiller extends TimerTask
78 {
79
80 @Override
81 public void run()
82 {
83 LifecycleAwareWebDriverGrid.shutdown();
84 }
85 }
86 }