KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > core > startup > Main


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.core.startup;
21
22 import java.beans.Introspector JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.lang.reflect.Method JavaDoc;
26 import java.net.URL JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import javax.swing.SwingUtilities JavaDoc;
29 import javax.swing.UIManager JavaDoc;
30 import org.netbeans.Util;
31 import org.openide.filesystems.FileObject;
32 import org.openide.filesystems.FileStateInvalidException;
33 import org.openide.filesystems.Repository;
34 import org.openide.modules.Dependency;
35 import org.openide.modules.InstalledFileLocator;
36 import org.openide.modules.SpecificationVersion;
37 import org.openide.util.Exceptions;
38 import org.openide.util.Lookup;
39 import org.openide.util.NbBundle;
40 import org.openide.util.Utilities;
41
42 /**
43  * Main class for NetBeans when run in GUI mode.
44  */

45 public final class Main extends Object JavaDoc {
46     /** module subsystem */
47     private static ModuleSystem moduleSystem;
48     /** module subsystem is fully ready */
49     private static boolean moduleSystemInitialized;
50
51   /** Prints the text to splash screen or to status line, if available.
52    */

53   public static void setStatusText (String JavaDoc msg) {
54         Splash.getInstance().print (msg);
55         if (moduleSystemInitialized) {
56             org.netbeans.core.startup.CoreBridge.conditionallyPrintStatus (msg);
57         }
58   }
59   
60   /** Starts TopThreadGroup which properly overrides uncaughtException
61    * Further - new thread in the group execs main
62    */

63   public static void main (String JavaDoc[] argv) throws Exception JavaDoc {
64     TopThreadGroup tg = new TopThreadGroup ("IDE Main", argv); // NOI18N - programatic name
65
StartLog.logStart ("Forwarding to topThreadGroup"); // NOI18N
66
tg.start ();
67     StartLog.logProgress ("Main.main finished"); // NOI18N
68
}
69
70
71   private static boolean nbFactoryInitialized;
72   /** Initializes default stream factory */
73   public static void initializeURLFactory () {
74     if (!nbFactoryInitialized) {
75         NbURLStreamHandlerFactory fact = new NbURLStreamHandlerFactory();
76         try {
77             java.net.URL.setURLStreamHandlerFactory(fact);
78         } catch (Error JavaDoc e) {
79             fact.registerUsingReflection(e);
80         }
81         nbFactoryInitialized = true;
82     }
83   }
84   
85   /**
86    * Sets up the custom font size and theme url for the plaf library to
87    * process.
88    */

89   static void initUICustomizations() {
90       if (!CLIOptions.isGui ()) {
91           return;
92       }
93     
94       URL JavaDoc themeURL = null;
95       boolean wantTheme = Boolean.getBoolean ("netbeans.useTheme") ||
96           CLIOptions.uiClass != null && CLIOptions.uiClass.getName().indexOf("MetalLookAndFeel") >= 0;
97
98       try {
99           if (wantTheme) {
100               //Put a couple things into UIDefaults for the plaf library to process if it wants
101
FileObject fo =
102                     Repository.getDefault().getDefaultFileSystem().findResource("themes.xml"); //NOI18N
103
if (fo == null) {
104                     // File on SFS failed --> try to load from a jar from path
105
// /org/netbeans/core/startup/resources/themes.xml
106
try {
107                         themeURL = new URL JavaDoc("nbresloc:/org/netbeans/core/startup/resources/themes.xml"); //NOI18N
108
// check whether the file is there:
109
themeURL.openStream().close();
110                     } catch (IOException JavaDoc ex) {
111                         themeURL = null;
112                     }
113                } else {
114                     try {
115                         themeURL = fo.getURL();
116                     } catch (FileStateInvalidException fsie) {
117                         //do nothing
118
}
119                }
120           }
121       } finally {
122           CoreBridge.getDefault ().initializePlaf(CLIOptions.uiClass, CLIOptions.getFontSize(), themeURL);
123       }
124       if (CLIOptions.getFontSize() > 0 && "GTK".equals(UIManager.getLookAndFeel().getID())) { //NOI18N
125
Util.err.warning(NbBundle.getMessage(Main.class,
126           "GTK_FONTSIZE_UNSUPPORTED")); //NOI18N
127
}
128       StartLog.logProgress("Fonts updated"); // NOI18N
129
}
130     /** Get and initialize module subsystem. */
131     public static ModuleSystem getModuleSystem() {
132         synchronized (Main.class) {
133             if (moduleSystem != null) {
134                 return moduleSystem;
135             }
136
137             StartLog.logStart ("Modules initialization"); // NOI18N
138
try {
139                 moduleSystem = new ModuleSystem(Repository.getDefault().getDefaultFileSystem());
140             } catch (IOException JavaDoc ioe) {
141                 // System will be screwed up.
142
throw (IllegalStateException JavaDoc) new IllegalStateException JavaDoc("Module system cannot be created").initCause(ioe); // NOI18N
143
}
144             StartLog.logProgress ("ModuleSystem created"); // NOI18N
145
}
146
147         moduleSystem.loadBootModules();
148         moduleSystem.readList();
149         moduleSystem.restore();
150         StartLog.logEnd ("Modules initialization"); // NOI18N
151

152         moduleSystemInitialized = true;
153         
154         return moduleSystem;
155     }
156     
157     /** Is used to find out whether the system has already been initialized
158      * for the first time or not yet.
159      * @return true if changes in the lookup shall mean real changes, false if it just
160      * the first initalization
161      */

162     public static boolean isInitialized() {
163         return moduleSystemInitialized;
164     }
165     
166   
167   /**
168   * @exception SecurityException if it is called multiple times
169   */

170   static void start (String JavaDoc[] args) throws SecurityException JavaDoc {
171     StartLog.logEnd ("Forwarding to topThreadGroup"); // NOI18N
172
StartLog.logStart ("Preparation"); // NOI18N
173

174     // just setup some reasonable values for this deprecated property
175
// 6.2 seems to be like the right version as that is the last one
176
// that ever saw openide
177
System.setProperty ("org.openide.specification.version", "6.2"); // NOI18N
178
System.setProperty ("org.openide.version", "deprecated"); // NOI18N
179
System.setProperty ("org.openide.major.version", "IDE/1"); // NOI18N
180

181     // Enforce JDK 1.5+ since we would not work without it.
182
if (Dependency.JAVA_SPEC.compareTo(new SpecificationVersion("1.5")) < 0) { // NOI18N
183
System.err.println("The IDE requires JDK 5 or higher to run."); // XXX I18N?
184
org.netbeans.TopSecurityManager.exit(1);
185     }
186
187     // In the past we derived ${jdk.home} from ${java.home} by appending
188
// "/.." to the end of ${java.home} assuming that JRE is under JDK
189
// directory. It does not always work. On MacOS X JDK and JRE files
190
// are mixed together, thus ${jdk.home} == ${java.home}. In several
191
// Linux distros JRE and JDK are installed at the same directory level
192
// with ${jdk.home}/jre a symlink to ${java.home}, which means
193
// ${java.home}/.. != ${jdk.home}.
194
//
195
// Now the launcher can set ${jdk.home} explicitly because it knows
196
// best where the JDK is.
197

198     String JavaDoc jdkHome = System.getProperty("jdk.home"); // NOI18N
199

200     if (jdkHome == null) {
201         jdkHome = System.getProperty("java.home"); // NOI18N
202

203         if (Utilities.isMac()) {
204             jdkHome += File.separator + ".."; // NOI18N
205
}
206
207         System.setProperty("jdk.home", jdkHome); // NOI18N
208
}
209
210     // initialize the URL factory
211
initializeURLFactory();
212   
213     if (System.getProperties ().get ("org.openide.TopManager") == null) { // NOI18N
214
// this tells the system that we run in guy mode
215
System.setProperty ("org.openide.TopManager.GUI", "true"); // NOI18N
216
// update the top manager to our main if it has not been provided yet
217
System.getProperties().put (
218         // Note that it is no longer actually a TopManager; historical relic:
219
"org.openide.TopManager", // NOI18N
220
"org.netbeans.core.NonGui" // NOI18N
221
);
222     }
223
224     CLIOptions.initialize();
225     StartLog.logProgress ("Command line parsed"); // NOI18N
226

227
228 // 5. initialize GUI
229
StartLog.logStart ("XML Factories"); //NOI18N
230

231     org.netbeans.core.startup.SAXFactoryImpl.install();
232     org.netbeans.core.startup.DOMFactoryImpl.install();
233     //Bugfix #35919: Log message to console when initialization of local
234
//graphics environment fails eg. due to incorrect value of $DISPLAY
235
//on X Windows (Linux, Solaris). In such case IDE will not start
236
//so we must inform user about error.
237

238     if (CLIOptions.isGui ()) {
239         try {
240             java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment();
241         } catch (java.lang.InternalError JavaDoc exc) {
242             String JavaDoc s = NbBundle.getMessage(Main.class, "EXC_GraphicsStartFails1", exc.getMessage());
243             System.out.println(s);
244             s = NbBundle.getMessage(Main.class, "EXC_GraphicsStartFails2", CLIOptions.getUserDir() + "/var/log/messages.log");
245             System.out.println(s);
246             throw exc;
247         }
248     }
249     StartLog.logEnd ("XML Factories"); //NOI18N
250

251     
252
253     org.netbeans.core.startup.InstalledFileLocatorImpl.prepareCache();
254
255     // Initialize beans - [PENDING - better place for this ?]
256
// [PENDING - can PropertyEditorManager garbage collect ?]
257
String JavaDoc[] sysbisp = Introspector.getBeanInfoSearchPath();
258     String JavaDoc[] nbbisp = new String JavaDoc[] {
259         "org.netbeans.beaninfo", // NOI18N
260
};
261     String JavaDoc[] allbisp = new String JavaDoc[sysbisp.length + nbbisp.length];
262     System.arraycopy(nbbisp, 0, allbisp, 0, nbbisp.length);
263     System.arraycopy(sysbisp, 0, allbisp, nbbisp.length, sysbisp.length);
264     Introspector.setBeanInfoSearchPath(allbisp);
265
266
267     try {
268         if ((System.getProperty ("netbeans.full.hack") == null) && (System.getProperty ("netbeans.close") == null)) {
269         // -----------------------------------------------------------------------------------------------------
270
// License check
271
if (!handleLicenseCheck()) {
272                 org.netbeans.TopSecurityManager.exit(0);
273             }
274         // -----------------------------------------------------------------------------------------------------
275
// Upgrade
276
if (!handleImportOfUserDir ()) {
277                 org.netbeans.TopSecurityManager.exit(0);
278             }
279         }
280     } catch (Exception JavaDoc e) {
281         Exceptions.printStackTrace(e);
282     }
283     StartLog.logProgress ("License check performed and upgrade wizard consulted"); // NOI18N
284

285     //
286
// 8.5 - we can show the splash only after the upgrade wizard finished
287
//
288

289     Splash.getInstance().setRunning(true);
290
291     // -----------------------------------------------------------------------------------------------------
292

293     Splash.getInstance().print(NbBundle.getMessage(Main.class, "MSG_IDEInit"));
294
295     
296     // -----------------------------------------------------------------------------------------------------
297
// 9. Modules
298

299     assert Repository.getDefault() instanceof NbRepository : "Has to be NbRepository: " + Repository.getDefault(); // NOI18N
300
getModuleSystem ();
301     
302     // property editors are registered in modules, so wait a while before loading them
303
CoreBridge.getDefault().registerPropertyEditors();
304     StartLog.logProgress ("PropertyEditors registered"); // NOI18N
305

306     CoreBridge.getDefault().loadSettings();
307     StartLog.logProgress ("IDE settings loaded"); // NOI18N
308

309     {
310         Iterator JavaDoc it = Lookup.getDefault().lookupAll(RunLevel.class).iterator();
311         
312         while (it.hasNext ()) {
313             RunLevel level = (RunLevel)it.next ();
314             level.run ();
315         }
316     }
317     
318     org.netbeans.Main.finishInitialization();
319     StartLog.logProgress("Ran any delayed command-line options"); // NOI18N
320

321     Splash.getInstance().setRunning(false);
322     Splash.getInstance().dispose();
323     StartLog.logProgress ("Splash hidden"); // NOI18N
324
StartLog.logEnd ("Preparation"); // NOI18N
325
}
326   
327     /** Loads a class from available class loaders. */
328     private static final Class JavaDoc getKlass(String JavaDoc cls) {
329         try {
330             ClassLoader JavaDoc loader;
331             ModuleSystem ms = moduleSystem;
332             if (ms != null) {
333                 loader = ms.getManager ().getClassLoader ();
334             } else {
335                 loader = Main.class.getClassLoader ();
336             }
337             
338             return Class.forName(cls, false, loader);
339         } catch (ClassNotFoundException JavaDoc e) {
340             throw new NoClassDefFoundError JavaDoc(e.getLocalizedMessage());
341         }
342     }
343
344     /** Does import of userdir. Made non-private just for testing purposes.
345      *
346      * @return true if the execution should continue or false if it should
347      * stop
348      */

349     static boolean handleImportOfUserDir () {
350         class ImportHandler implements Runnable JavaDoc {
351             private File JavaDoc installed = new File JavaDoc (new File JavaDoc (CLIOptions.getUserDir (), "var"), "imported"); // NOI18N
352
private String JavaDoc classname;
353             private boolean executedOk;
354             
355             public boolean shouldDoAnImport () {
356                 classname = System.getProperty ("netbeans.importclass"); // NOI18N
357

358                 return classname != null && !installed.exists ();
359             }
360             
361             
362             public void run() {
363                 // This module is included in our distro somewhere... may or may not be turned on.
364
// Whatever - try running some classes from it anyway.
365
try {
366                     Class JavaDoc<?> clazz = getKlass (classname);
367                 
368                     // Method showMethod = wizardClass.getMethod( "handleUpgrade", new Class[] { Splash.SplashOutput.class } ); // NOI18N
369
Method JavaDoc showMethod = clazz.getMethod( "main", String JavaDoc[].class ); // NOI18N
370
showMethod.invoke (null, new Object JavaDoc[] {
371                         new String JavaDoc[0]
372                     });
373                     executedOk = true;
374                 } catch (java.lang.reflect.InvocationTargetException JavaDoc ex) {
375                     // canceled by user, all is fine
376
if (ex.getTargetException () instanceof org.openide.util.UserCancelException) {
377                         executedOk = true;
378                     } else {
379                         ex.printStackTrace();
380                     }
381                 } catch (Exception JavaDoc e) {
382                     // If exceptions are thrown, notify them - something is broken.
383
e.printStackTrace();
384                 } catch (LinkageError JavaDoc e) {
385                     // These too...
386
e.printStackTrace();
387                 }
388             }
389             
390             
391             public boolean canContinue () {
392                 if (shouldDoAnImport ()) {
393                     try {
394                         SwingUtilities.invokeAndWait (this);
395                         if (executedOk) {
396                             // if the import went fine, then we are fine
397
// just create the file
398
installed.getParentFile ().mkdirs ();
399                             installed.createNewFile ();
400                             return true;
401                         } else {
402                             return false;
403                         }
404                     } catch (IOException JavaDoc ex) {
405                         // file was not created a bit of problem but go on
406
ex.printStackTrace();
407                         return true;
408                     } catch (java.lang.reflect.InvocationTargetException JavaDoc ex) {
409                         return false;
410                     } catch (InterruptedException JavaDoc ex) {
411                         ex.printStackTrace();
412                         return false;
413                     }
414                 } else {
415                     // if there is no need to upgrade that every thing is good
416
return true;
417                 }
418             }
419         }
420         
421         
422         ImportHandler handler = new ImportHandler ();
423         
424         return handler.canContinue ();
425     }
426     
427     /** Displays license to user to accept if necessary. Made non-private just for testing purposes.
428      *
429      * @return true if the execution should continue or false if it should
430      * stop
431      */

432     static boolean handleLicenseCheck () {
433         class LicenseHandler implements Runnable JavaDoc {
434             private String JavaDoc classname;
435             private boolean executedOk;
436             
437             /** Checks if licence was accepted already or not. */
438             public boolean shouldDisplayLicense () {
439                 File JavaDoc f = InstalledFileLocator.getDefault().locate("var/license_accepted",null,false); // NOI18N
440
if (f != null) {
441                     return false;
442                 }
443                 classname = System.getProperty("netbeans.accept_license_class"); // NOI18N
444
return (classname != null);
445             }
446             
447             public void run() {
448                 // This module is included in our distro somewhere... may or may not be turned on.
449
// Whatever - try running some classes from it anyway.
450
try {
451                     Class JavaDoc<?> clazz = getKlass (classname);
452                 
453                     Method JavaDoc showMethod = clazz.getMethod("showLicensePanel"); // NOI18N
454
showMethod.invoke (null, new Object JavaDoc [] {});
455                     executedOk = true;
456                     //User accepted license => create file marker in userdir
457
File JavaDoc f = new File JavaDoc(new File JavaDoc(CLIOptions.getUserDir(), "var"), "license_accepted"); // NOI18N
458
if (!f.exists()) {
459                         f.getParentFile().mkdirs();
460                         try {
461                             f.createNewFile();
462                         } catch (IOException JavaDoc exc) {
463                             exc.printStackTrace();
464                         }
465                     }
466                 } catch (java.lang.reflect.InvocationTargetException JavaDoc ex) {
467                     // canceled by user, all is fine
468
if (ex.getTargetException() instanceof org.openide.util.UserCancelException) {
469                         executedOk = false;
470                     } else {
471                         ex.printStackTrace();
472                     }
473                 } catch (Exception JavaDoc ex) {
474                     // If exceptions are thrown, notify them - something is broken.
475
ex.printStackTrace();
476                 } catch (LinkageError JavaDoc ex) {
477                     // These too...
478
ex.printStackTrace();
479                 }
480             }
481             
482             public boolean canContinue () {
483                 if (shouldDisplayLicense()) {
484                     try {
485                         SwingUtilities.invokeAndWait(this);
486                         if (executedOk) {
487                             return true;
488                         } else {
489                             return false;
490                         }
491                     } catch (java.lang.reflect.InvocationTargetException JavaDoc ex) {
492                         return false;
493                     } catch (InterruptedException JavaDoc ex) {
494                         ex.printStackTrace();
495                         return false;
496                     }
497                 } else {
498                     // if there is no need to upgrade that every thing is good
499
return true;
500                 }
501             }
502         }
503                 
504         LicenseHandler handler = new LicenseHandler ();
505         
506         return handler.canContinue ();
507     }
508 }
509
Popular Tags