KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > snipsnap > server > Launcher


1 /*
2  * This file is part of "SnipSnap Wiki/Weblog".
3  *
4  * Copyright (c) 2002 Stephan J. Schmidt, Matthias L. Jugel
5  * All Rights Reserved.
6  *
7  * Please visit http://snipsnap.org/ for updates and contact.
8  *
9  * --LICENSE NOTICE--
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  * --LICENSE NOTICE--
24  */

25 package org.snipsnap.server;
26
27 import java.io.BufferedInputStream JavaDoc;
28 import java.io.File JavaDoc;
29 import java.io.FileOutputStream JavaDoc;
30 import java.io.IOException JavaDoc;
31 import java.io.InputStream JavaDoc;
32 import java.lang.reflect.InvocationTargetException JavaDoc;
33 import java.lang.reflect.Method JavaDoc;
34 import java.net.MalformedURLException JavaDoc;
35 import java.net.URL JavaDoc;
36 import java.net.URLClassLoader JavaDoc;
37 import java.security.Policy JavaDoc;
38 import java.util.ArrayList JavaDoc;
39 import java.util.List JavaDoc;
40 import java.util.StringTokenizer JavaDoc;
41 import java.util.jar.Attributes JavaDoc;
42 import java.util.jar.JarInputStream JavaDoc;
43 import java.util.jar.Manifest JavaDoc;
44
45 /**
46  * Launcher for Java Applications. Creates the classpath and then starts the application.
47  *
48  * @author Matthias L. Jugel
49  * @version $Id: Launcher.java 1707 2004-07-09 14:34:00Z leo $
50  */

51 public class Launcher {
52   public final static String JavaDoc CLASSPATH = "launcher.classpath";
53
54   private final static URL JavaDoc location = Launcher.class.getProtectionDomain().getCodeSource().getLocation();
55
56   public static void invokeMain(String JavaDoc mainClassName, final String JavaDoc args[])
57           throws ClassNotFoundException JavaDoc, NoSuchMethodException JavaDoc, IllegalAccessException JavaDoc, InvocationTargetException JavaDoc {
58     ClassLoader JavaDoc parentClassLoader = Thread.currentThread().getContextClassLoader();
59     if (null == parentClassLoader) {
60       parentClassLoader = Launcher.class.getClassLoader();
61     }
62     if (null == parentClassLoader) {
63       parentClassLoader = ClassLoader.getSystemClassLoader();
64     }
65     URLClassLoader JavaDoc classLoader = new URLClassLoader JavaDoc(initClassPath(System.getProperty(CLASSPATH)),
66                                                     parentClassLoader);
67     Thread.currentThread().setContextClassLoader(classLoader);
68     if (System.getSecurityManager() != null) {
69       System.err.println("Launcher: uninstalling security manager ...");
70       System.setSecurityManager(null);
71     }
72
73     try {
74       Policy.getPolicy().refresh();
75     } catch (Exception JavaDoc e) {
76       e.printStackTrace();
77     }
78
79     // load and start main class
80
Class JavaDoc mainClass = classLoader.loadClass(mainClassName);
81     final Method JavaDoc main = mainClass.getDeclaredMethod("main", new Class JavaDoc[]{String JavaDoc[].class});
82     main.invoke(null, new Object JavaDoc[]{args});
83   }
84
85   protected static URL JavaDoc[] initClassPath(String JavaDoc extraClassPath) {
86     List JavaDoc urlArray = new ArrayList JavaDoc();
87     try {
88       Manifest JavaDoc launcherManifest = new JarInputStream JavaDoc(location.openStream()).getManifest();
89       Attributes JavaDoc launcherAttribs = launcherManifest.getMainAttributes();
90       String JavaDoc mainJarAttr = launcherAttribs.getValue("Launcher-Main-Jar");
91       if (System.getProperty("launcher.main.jar") != null) {
92         mainJarAttr = System.getProperty("launcher.main.jar");
93       }
94       URL JavaDoc mainJarUrl = getResourceUrl(mainJarAttr);
95       Manifest JavaDoc mainManifest = new JarInputStream JavaDoc(mainJarUrl.openStream()).getManifest();
96       Attributes JavaDoc mainAttributes = mainManifest.getMainAttributes();
97       String JavaDoc manifestClassPath = mainAttributes.getValue("Class-Path");
98
99       urlArray.add(mainJarUrl);
100       // append extra class path to manifest class path (after replacing separatorchar)
101
if (extraClassPath != null && extraClassPath.length() > 0) {
102         manifestClassPath += " " + extraClassPath.replace(File.pathSeparatorChar, ' ');
103       }
104
105       StringBuffer JavaDoc classPath = new StringBuffer JavaDoc(location.getFile());
106       StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(manifestClassPath, " \t" + File.pathSeparatorChar, false);
107       while (tokenizer.hasMoreTokens()) {
108         classPath.append(File.pathSeparatorChar);
109         URL JavaDoc classPathEntry = getResourceUrl(tokenizer.nextToken());
110         urlArray.add(classPathEntry);
111         classPath.append(classPathEntry.getFile());
112       }
113       System.setProperty("java.class.path", classPath.toString());
114     } catch (IOException JavaDoc e) {
115       System.err.println("Error: Set the system property launcher.main.jar to specify the jar file to start.");
116     }
117     return (URL JavaDoc[]) urlArray.toArray(new URL JavaDoc[0]);
118   }
119
120   private static URL JavaDoc getResourceUrl(String JavaDoc resource) throws IOException JavaDoc {
121     File JavaDoc directoryBase = new File JavaDoc(location.getFile()).getParentFile();
122     File JavaDoc file = new File JavaDoc(resource);
123     // see if this is an absolute URL
124
if (file.isAbsolute() && file.exists()) {
125       return file.toURL();
126     }
127     // handle non-absolute URLs
128
file = new File JavaDoc(directoryBase, resource);
129     if (file.exists()) {
130       return file.toURL();
131     }
132
133     URL JavaDoc resourceURL = Launcher.class.getResource("/" + resource);
134     if (null != resourceURL) {
135       return extract(resourceURL);
136     }
137
138     throw new MalformedURLException JavaDoc("missing resource: " + resource);
139   }
140
141   /**
142    * Extract file from launcher jar to be able to access is via classpath.
143    *
144    * @param resource the jar resource to be extracted
145    * @return a url pointing to the new file
146    * @throws IOException if the extraction was not possible
147    */

148   private static URL JavaDoc extract(URL JavaDoc resource) throws IOException JavaDoc {
149     System.err.println("Launcher: extracting '" + resource.getFile() + "' ...");
150     File JavaDoc f = File.createTempFile("launcher_", ".jar");
151     f.deleteOnExit();
152     if (f.getParentFile() != null) {
153       f.getParentFile().mkdirs();
154     }
155     InputStream JavaDoc is = new BufferedInputStream JavaDoc(resource.openStream());
156     FileOutputStream JavaDoc os = new FileOutputStream JavaDoc(f);
157     byte[] arr = new byte[8192];
158     for (int i = 0; i >= 0; i = is.read(arr)) {
159       os.write(arr, 0, i);
160     }
161     is.close();
162     os.close();
163     return f.toURL();
164   }
165 }
Popular Tags