1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.commons.io;
21
22 import java.lang.reflect.InvocationTargetException;
23 import java.util.concurrent.Callable;
24 import javax.swing.JDialog;
25 import javax.swing.JFrame;
26 import javax.swing.SwingUtilities;
27 import org.xnap.commons.gui.ProgressDialog;
28
29 /***
30 * Provides static helper methods for executing {@link org.xnap.commons.io.Job}
31 * objects.
32 *
33 * @author Steffen Pingel
34 */
35 public class JobExecutor {
36
37 public static <T> Callable<T> callable(final Job<T> job, final ProgressMonitor monitor)
38 {
39 return new Callable<T>()
40 {
41 public T call() throws Exception
42 {
43 return job.run(monitor);
44 }
45 };
46 }
47
48 public static <T> T run(String title, Job<T> job) throws Exception
49 {
50 ProgressDialog dialog = new ProgressDialog();
51 dialog.setTitle(title);
52 return run(dialog, job);
53 }
54
55 public static <T> T run(JDialog owner, String title, Job<T> job) throws Exception
56 {
57 ProgressDialog dialog = new ProgressDialog(owner);
58 dialog.setLocationRelativeTo(owner);
59 dialog.setTitle(title);
60 return run(dialog, job);
61 }
62
63 public static <T> T run(JFrame owner, String title, Job<T> job) throws Exception
64 {
65 ProgressDialog dialog = new ProgressDialog(owner);
66 dialog.setLocationRelativeTo(owner);
67 dialog.setTitle(title);
68 return run(dialog, job);
69 }
70
71 @SuppressWarnings("unchecked")
72 private static <T> T run(final ProgressDialog dialog, final Job<T> job) throws Exception {
73 final T[] retSuccess = (T[])new Object[1];
74 final Throwable[] ret = new Exception[1];
75
76 Runnable runner = new Runnable() {
77 public void run()
78 {
79 try {
80 retSuccess[0] = job.run(dialog);
81 }
82 catch (Throwable e) {
83 ret[0] = e;
84 }
85 SwingUtilities.invokeLater(new Runnable() {
86 public void run() {
87 dialog.done();
88 }
89 });
90 }
91 };
92
93 Thread t = new Thread(runner, "Job");
94 t.start();
95
96
97 dialog.setModal(true);
98 dialog.showDialog();
99
100
101 if (ret[0] != null) {
102 if (ret[0] instanceof Exception) {
103 throw (Exception)ret[0];
104 }
105 else {
106 throw new InvocationTargetException(ret[0]);
107 }
108 }
109 return (T)retSuccess[0];
110 }
111
112 }