KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > MainImpl


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans;
21
22 import java.io.File JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.InputStream JavaDoc;
25 import java.lang.reflect.Method JavaDoc;
26 import java.net.URL JavaDoc;
27 import java.net.URLConnection JavaDoc;
28 import java.security.AllPermission JavaDoc;
29 import java.security.CodeSource JavaDoc;
30 import java.security.PermissionCollection JavaDoc;
31 import java.security.Permissions JavaDoc;
32 import java.util.ArrayList JavaDoc;
33 import java.util.Collection JavaDoc;
34 import java.util.Enumeration JavaDoc;
35 import java.util.HashSet JavaDoc;
36 import java.util.List JavaDoc;
37 import java.util.Set JavaDoc;
38 import java.util.StringTokenizer JavaDoc;
39 import java.util.jar.JarFile JavaDoc;
40 import org.openide.util.Lookup;
41 import org.openide.util.Union2;
42 import org.openide.util.lookup.Lookups;
43
44 /** Bootstrap main class.
45  * @author Jaroslav Tulach, Jesse Glick
46  */

47 final class MainImpl extends Object JavaDoc {
48
49     /** Starts the IDE.
50      * @param args the command line arguments
51      * @throws Exception for lots of reasons
52      */

53     public static void main (String JavaDoc args[]) throws Exception JavaDoc {
54         java.lang.reflect.Method JavaDoc[] m = new java.lang.reflect.Method JavaDoc[1];
55         int res = execute (args, System.in, System.out, System.err, m);
56         if (res == -1) {
57             // Connected to another running NB instance and succeeded in making a call.
58
return;
59         } else if (res != 0) {
60             // Some CLIHandler refused the invocation
61
System.exit(res);
62         }
63
64         m[0].invoke (null, new Object JavaDoc[] { args });
65     }
66
67     /** Returns string describing usage of the system. Does that by talking to
68      * all registered handlers and asking them to show their usage.
69      *
70      * @return the usage string for the system
71      */

72     public static String JavaDoc usage () throws Exception JavaDoc {
73         java.io.ByteArrayOutputStream JavaDoc os = new java.io.ByteArrayOutputStream JavaDoc ();
74         java.io.ByteArrayOutputStream JavaDoc err = new java.io.ByteArrayOutputStream JavaDoc ();
75
76         String JavaDoc[] newArgs = { "--help" };
77
78         execute(newArgs, System.in, os, err, null);
79         return new String JavaDoc (os.toByteArray ());
80     }
81
82     /** Constructs the correct ClassLoader, finds main method to execute
83      * and invokes all registered CLIHandlers.
84      *
85      * @param args the arguments to pass to the handlers
86      * @param reader the input stream reader for the handlers
87      * @param writer the output stream for the handlers
88      * @param methodToCall null or array with one item that will be set to
89      * a method that shall be executed as the main application
90      */

91     static int execute (
92         String JavaDoc[] args,
93         java.io.InputStream JavaDoc reader,
94         java.io.OutputStream JavaDoc writer,
95         java.io.OutputStream JavaDoc error,
96         java.lang.reflect.Method JavaDoc[] methodToCall
97     ) throws Exception JavaDoc {
98         // #42431: turn off jar: caches, they are evil
99
// Note that setDefaultUseCaches changes a static field
100
// yet for some reason it is an instance method!
101
new URLConnection JavaDoc(MainImpl.class.getResource("Main.class")) { // NOI18N
102
public void connect() throws IOException JavaDoc {}
103         }.setDefaultUseCaches(false);
104
105         ArrayList JavaDoc<Union2<File JavaDoc,JarFile JavaDoc>> list = new ArrayList JavaDoc<Union2<File JavaDoc,JarFile JavaDoc>>();
106
107         HashSet JavaDoc<File JavaDoc> processedDirs = new HashSet JavaDoc<File JavaDoc> ();
108         String JavaDoc home = System.getProperty ("netbeans.home"); // NOI18N
109
if (home != null) {
110             build_cp (new File JavaDoc (home), list, processedDirs);
111         }
112         // #34069: need to do the same for nbdirs.
113
String JavaDoc nbdirs = System.getProperty("netbeans.dirs"); // NOI18N
114
if (nbdirs != null) {
115             StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(nbdirs, File.pathSeparator);
116             while (tok.hasMoreTokens()) {
117                 // passing false as last argument as we need to initialize openfile-cli.jar
118
build_cp(new File JavaDoc(tok.nextToken()), list, processedDirs);
119             }
120         }
121
122         //
123
// prepend classpath
124
//
125
String JavaDoc prepend = System.getProperty("netbeans.classpath"); // NOI18N
126
if (prepend != null) {
127             StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc (prepend, File.pathSeparator);
128             while (tok.hasMoreElements()) {
129                 File JavaDoc f = new File JavaDoc(tok.nextToken());
130                 list.add(0, f.isDirectory() ?
131                     Union2.<File JavaDoc,JarFile JavaDoc>createFirst(f) :
132                     Union2.<File JavaDoc,JarFile JavaDoc>createSecond(new JarFile JavaDoc(f, false)));
133             }
134         }
135
136         // Compute effective dynamic classpath (mostly lib/*.jar) for TopLogging, NbInstaller:
137
StringBuffer JavaDoc buf = new StringBuffer JavaDoc(1000);
138         for (Union2<File JavaDoc,JarFile JavaDoc> o : list) {
139         String JavaDoc f = o.hasFirst() ? o.first().getAbsolutePath() : o.second().getName();
140             if (buf.length() > 0) {
141                 buf.append(File.pathSeparatorChar);
142             }
143             buf.append(f);
144         }
145         System.setProperty("netbeans.dynamic.classpath", buf.toString());
146
147         BootClassLoader loader = new BootClassLoader(list, new ClassLoader JavaDoc[] {
148             MainImpl.class.getClassLoader()
149         });
150
151         // Needed for Lookup.getDefault to find NbTopManager.Lkp.
152
// Note that ModuleManager.updateContextClassLoaders will later change
153
// the loader on this and other threads to be MM.SystemClassLoader anyway.
154
Thread.currentThread().setContextClassLoader (loader);
155
156
157         //
158
// Evaluate command line interfaces and lock the user directory
159
//
160

161         CLIHandler.Status result;
162         result = CLIHandler.initialize(args, reader, writer, error, loader, true, false, loader);
163         if (result.getExitCode () == CLIHandler.Status.CANNOT_CONNECT) {
164             int value = javax.swing.JOptionPane.showConfirmDialog (
165                 null,
166                 java.util.ResourceBundle.getBundle("org/netbeans/Bundle").getString("MSG_AlreadyRunning"),
167                 java.util.ResourceBundle.getBundle("org/netbeans/Bundle").getString("MSG_AlreadyRunningTitle"),
168                 javax.swing.JOptionPane.OK_CANCEL_OPTION,
169                 javax.swing.JOptionPane.WARNING_MESSAGE
170             );
171             if (value == javax.swing.JOptionPane.OK_OPTION) {
172                 result = CLIHandler.initialize(args, reader, writer, error, loader, true, true, loader);
173             }
174
175         }
176
177         String JavaDoc className = System.getProperty(
178             "netbeans.mainclass", "org.netbeans.core.startup.Main" // NOI18N
179
);
180
181         Class JavaDoc<?> c = loader.loadClass(className);
182         Method JavaDoc m = c.getMethod ("main", String JavaDoc[].class); // NOI18N
183

184         if (methodToCall != null) {
185             methodToCall[0] = m;
186         }
187
188         return result.getExitCode ();
189     }
190
191     /**
192      * Call when the system is up and running, to complete handling of
193      * delayed command-line options like -open FILE.
194      */

195     public static void finishInitialization() {
196         int r = CLIHandler.finishInitialization (false);
197         if (r != 0) {
198             // Not much to do about it.
199
System.err.println ("Post-initialization command-line options could not be run."); // NOI18N
200
//System.err.println("r=" + r + " args=" + java.util.Arrays.asList(args.getArguments()));
201
}
202     }
203
204     static final class BootClassLoader extends JarClassLoader
205     implements Runnable JavaDoc {
206         private Lookup metaInf;
207
208         private List JavaDoc<CLIHandler> handlers;
209
210         public BootClassLoader(List JavaDoc<Union2<File JavaDoc,JarFile JavaDoc>> cp, ClassLoader JavaDoc[] parents) {
211             super(cp, parents);
212
213             metaInf = Lookups.metaInfServices(this);
214
215             String JavaDoc value = null;
216             try {
217                 if (cp.isEmpty ()) {
218                     value = searchBuildNumber(this.getResources("META-INF/MANIFEST.MF"));
219                 } else {
220                     value = searchBuildNumber(this.simpleFindResources("META-INF/MANIFEST.MF"));
221                 }
222             } catch (IOException JavaDoc ex) {
223                 ex.printStackTrace();
224             }
225
226             if (value == null) {
227                 System.err.println("Cannot set netbeans.buildnumber property no OpenIDE-Module-Implementation-Version found"); // NOI18N
228
} else {
229                 System.setProperty ("netbeans.buildnumber", value); // NOI18N
230
}
231         }
232
233         /** @param en enumeration of URLs */
234         private static String JavaDoc searchBuildNumber(Enumeration JavaDoc<URL JavaDoc> en) {
235             String JavaDoc value = null;
236             try {
237                 java.util.jar.Manifest JavaDoc mf;
238                 URL JavaDoc u = null;
239                 while(en.hasMoreElements()) {
240                     u = en.nextElement();
241                     InputStream JavaDoc is = u.openStream();
242                     mf = new java.util.jar.Manifest JavaDoc(is);
243                     is.close();
244                     value = mf.getMainAttributes().getValue("OpenIDE-Module-Implementation-Version"); // NOI18N
245
if (value != null) {
246                         break;
247                     }
248                 }
249             } catch (IOException JavaDoc ex) {
250                 ex.printStackTrace();
251             }
252             return value;
253         }
254
255         private boolean onlyRunRunOnce;
256         /** Checks for new JARs in netbeans.user */
257         public void run () {
258             // do not call this method twice
259
if (onlyRunRunOnce) return;
260             onlyRunRunOnce = true;
261
262             ArrayList JavaDoc<Union2<File JavaDoc,JarFile JavaDoc>> toAdd = new ArrayList JavaDoc<Union2<File JavaDoc,JarFile JavaDoc>> ();
263             String JavaDoc user = System.getProperty ("netbeans.user"); // NOI18N
264
try {
265                 if (user != null) {
266                     build_cp (new File JavaDoc (user), toAdd, new HashSet JavaDoc<File JavaDoc> ());
267                 }
268
269                 if (!toAdd.isEmpty ()) {
270                     addSources (toAdd);
271                     metaInf = Lookups.metaInfServices(this);
272                     if (handlers != null) {
273                         handlers.clear();
274                         handlers.addAll(metaInf.lookupAll(CLIHandler.class));
275                     }
276                 }
277             } catch (IOException JavaDoc ex) {
278                 ex.printStackTrace();
279             }
280         }
281
282
283         /** Startup optimalization. See issue 27226. */
284         protected PermissionCollection JavaDoc getPermissions(CodeSource JavaDoc cs) {
285             return getAllPermission();
286         }
287         /** Startup optimalization. See issue 27226. */
288         private static PermissionCollection JavaDoc modulePermissions;
289         /** Startup optimalization. See issue 27226. */
290         private static synchronized PermissionCollection JavaDoc getAllPermission() {
291             if (modulePermissions == null) {
292                 modulePermissions = new Permissions JavaDoc();
293                 modulePermissions.add(new AllPermission JavaDoc());
294                 modulePermissions.setReadOnly();
295             }
296             return modulePermissions;
297         }
298
299         /** For a given classloader finds all registered CLIHandlers.
300          */

301         public final Collection JavaDoc allCLIs () {
302             if (handlers == null) {
303                 handlers = new ArrayList JavaDoc<CLIHandler>(metaInf.lookupAll(CLIHandler.class));
304             }
305             return handlers;
306         }
307
308         protected boolean isSpecialResource (String JavaDoc pkg) {
309             boolean retValue = super.isSpecialResource (pkg);
310             if (retValue) return true;
311
312             return false;
313         }
314     } // end of BootClassLoader
315

316     private static void append_jars_to_cp (File JavaDoc dir, Collection JavaDoc<Union2<File JavaDoc,JarFile JavaDoc>> toAdd) throws IOException JavaDoc {
317         if (!dir.isDirectory()) return;
318
319         File JavaDoc[] arr = dir.listFiles();
320         for (int i = 0; i < arr.length; i++) {
321             String JavaDoc n = arr[i].getName ();
322             /*
323             if (n.equals("updater.jar") || // NOI18N
324                 (dir.getName().equals("locale") && n.startsWith("updater_") && n.endsWith(".jar"))) { // NOI18N
325                 // Used by launcher, not by us.
326                 continue;
327             }
328             */

329             if (n.endsWith("jar") || n.endsWith ("zip")) { // NOI18N
330
toAdd.add(Union2.<File JavaDoc,JarFile JavaDoc>createSecond(new JarFile JavaDoc(arr[i], false)));
331             }
332         }
333     }
334
335
336     private static void build_cp(File JavaDoc base, Collection JavaDoc<Union2<File JavaDoc,JarFile JavaDoc>> toAdd, Set JavaDoc<File JavaDoc> processedDirs)
337     throws java.io.IOException JavaDoc {
338         if (!processedDirs.add (base)) {
339             // already processed
340
return;
341         }
342
343         append_jars_to_cp(new File JavaDoc(base, "core/patches"), toAdd); // NOI18N
344
append_jars_to_cp(new File JavaDoc(base, "core"), toAdd); // NOI18N
345
// XXX a minor optimization: exclude any unused locale JARs
346
// For example, lib/locale/ might contain:
347
// core_ja.jar
348
// core_f4j.jar
349
// core_f4j_ja.jar
350
// core_f4j_ce.jar
351
// core_f4j_ce_ja.jar
352
// core_ru.jar
353
// core_fr.jar
354
// [etc.]
355
// Only some of these will apply to the current session, based on the
356
// current values of Locale.default and NbBundle.branding.
357
append_jars_to_cp(new File JavaDoc(base, "core/locale"), toAdd); // NOI18N
358
}
359 }
360
Popular Tags