01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17: package org.apache.harmony.vm;
18:
19: import java.util.jar.JarFile;
20: import java.util.jar.Manifest;
21: import java.util.jar.Attributes;
22:
23: import java.lang.reflect.Method;
24: import java.lang.reflect.Modifier;
25:
26: /**
27: * Small class to launch jars. Used by VM for the
28: * "java -jar foo.jar" use case.
29: *
30: * main() entry point takes array of arguments, with
31: * the jarname as the first arg
32: *
33: */
34: public class JarRunner {
35:
36: /**
37: * Expect jar filename as the first arg
38: */
39: public static void main(String[] args) throws Exception {
40:
41: if (args.length == 0) {
42: throw new Exception("No jar name specified");
43: }
44:
45: String jarName = args[0];
46:
47: /*
48: * open the jar and get the manifest, and main class name
49: */
50:
51: JarFile jarFile = new JarFile(jarName);
52: Manifest manifest = jarFile.getManifest();
53:
54: if (manifest == null) {
55: throw new Exception("No manifest in jar " + jarName);
56: }
57:
58: Attributes attrbs = manifest.getMainAttributes();
59: String className = attrbs.getValue(Attributes.Name.MAIN_CLASS);
60:
61: if (className == null || className.length() == 0) {
62: throw new Exception("Empty/Null Main-class specified in "
63: + jarName);
64: }
65:
66: className = className.replace('/', '.');
67:
68: /*
69: * load class, copy the args (skipping the first that is the jarname)
70: * and try to invoke main on the mainclass
71: */
72:
73: Class mainClass = Thread.currentThread()
74: .getContextClassLoader().loadClass(className);
75: Method mainMethod = mainClass
76: .getMethod("main", args.getClass());
77:
78: int mods = mainMethod.getModifiers();
79: if (!Modifier.isStatic(mods) || !Modifier.isPublic(mods)
80: || mainMethod.getReturnType() != void.class) {
81: throw new NoSuchMethodError(
82: "method main must be public static void: "
83: + mainMethod);
84: }
85: mainMethod.setAccessible(true);
86:
87: String newArgs[] = new String[args.length - 1];
88:
89: for (int i = 1; i < args.length; i++) {
90: newArgs[i - 1] = args[i];
91: }
92:
93: mainMethod.invoke(null, (java.lang.Object) newArgs);
94: }
95: }
|