1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.geronimo.gshell.bootstrap;
21
22 import java.lang.reflect.Method;
23 import java.lang.reflect.Modifier;
24 import java.net.URL;
25 import java.net.URLClassLoader;
26 import java.util.List;
27
28
29
30
31
32
33 public class Launcher
34 {
35 private final Configuration config;
36
37 public Launcher() {
38 this.config = new ConfigurationImpl();
39 }
40
41 public static void main(final String[] args) {
42 assert args != null;
43
44 Launcher launcher = new Launcher();
45 launcher.run(args);
46 }
47
48 public void run(final String[] args) {
49 assert args != null;
50
51 Log.debug("Running");
52
53 try {
54 config.configure();
55
56 launch(args);
57
58 Log.debug("Exiting");
59
60 System.exit(config.getSuccessExitCode());
61 }
62 catch (Throwable t) {
63 Log.debug("Failure: " + t);
64
65 t.printStackTrace(System.err);
66 System.err.flush();
67
68 System.exit(config.getFailureExitCode());
69 }
70 }
71
72 public void launch(final String[] args) throws Exception {
73 assert args != null;
74
75 Log.debug("Launching");
76
77 ClassLoader cl = getClassLoader();
78
79 Class type = cl.loadClass(config.getMainClass());
80 Method method = getMainMethod(type);
81
82 Thread.currentThread().setContextClassLoader(cl);
83
84 if (Log.DEBUG) {
85 Log.debug("Invoking: " + method);
86 }
87
88 method.invoke(null, new Object[] { args });
89 }
90
91 private ClassLoader getClassLoader() throws Exception {
92 List<URL> classPath = config.getClassPath();
93
94 if (Log.DEBUG) {
95 Log.debug("Classpath:");
96 for (URL url : classPath) {
97 Log.debug(" " + url);
98 }
99 }
100
101 ClassLoader parent = getClass().getClassLoader();
102 return new URLClassLoader(classPath.toArray(new URL[classPath.size()]), parent);
103 }
104
105 private Method getMainMethod(final Class type) throws Exception {
106 assert type != null;
107
108 Method method = type.getMethod("main", String[].class);
109 int modifiers = method.getModifiers();
110
111 if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers)) {
112 Class returns = method.getReturnType();
113 if (returns == Integer.TYPE || returns == Void.TYPE) {
114 return method;
115 }
116 }
117
118 throw new NoSuchMethodException("public static void main(String[] args) in " + type);
119 }
120 }