KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jnlp > sample > JreInstaller > Main


1 /*
2  * @(#)Main.java 1.11 05/11/30
3  *
4  * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * -Redistribution of source code must retain the above copyright notice, this
10  * list of conditions and the following disclaimer.
11  *
12  * -Redistribution in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution.
15  *
16  * Neither the name of Sun Microsystems, Inc. or the names of contributors may
17  * be used to endorse or promote products derived from this software without
18  * specific prior written permission.
19  *
20  * This software is provided "AS IS," without a warranty of any kind. ALL
21  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
22  * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
23  * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
24  * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
25  * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
26  * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
27  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
28  * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
29  * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
30  * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
31  *
32  * You acknowledge that this software is not designed, licensed or intended
33  * for use in the design, construction, operation or maintenance of any
34  * nuclear facility.
35  */

36
37 package jnlp.sample.JreInstaller;
38 import java.io.*;
39 import java.net.*;
40 import java.awt.*;
41 import java.util.*;
42 import java.awt.event.*;
43 import javax.swing.*;
44 import javax.swing.event.*;
45 import java.text.MessageFormat JavaDoc;
46 import javax.jnlp.DownloadService;
47 import javax.jnlp.DownloadServiceListener;
48 import javax.jnlp.ExtensionInstallerService;
49 import java.security.*;
50
51 /**
52  * Main class for JRE installer
53  */

54 public class Main {
55     private static final String JavaDoc JAVAWS_MERLIN_KEY = "Software\\JavaSoft\\Java Web Start\\1.0.1_02";
56     private static final String JavaDoc JAVAWS_HOPPER_KEY = "Software\\JavaSoft\\Java Web Start\\1.2";
57     private static final int BUFFER_SIZE = 32 * 1024;
58     
59     // Keep track of installer window
60
private static JFrame _installerFrame;
61     private static JLabel[] _stepLabels = null;
62     
63     private static final int STEP_LICENSE = 0;
64     private static final int STEP_DOWNLOAD = 1;
65     private static final int STEP_UNPACK = 2;
66     private static final int STEP_INSTALL = 3;
67     private static final int STEP_DONE = 4;
68     
69     /** Does install of JRE */
70     public static void install() {
71     
72         // Hide the JNLP Clients installer window and show own
73
Config.getInstallService().hideStatusWindow();
74     showInstallerWindow();
75         
76     
77         // Make sure the destination exists.
78
String JavaDoc path = Config.getInstallService().getInstallPath();
79     if (Config.isWindowsInstall()) {
80         String JavaDoc defaultLocation = "C:\\Program Files\\Java\\j2re" +
81         Config.getJavaVersion() + "\\";
82         File defaultDir = new File(defaultLocation);
83             if (!defaultDir.exists()) {
84             defaultDir.mkdirs();
85         }
86         if (defaultDir.exists() && defaultDir.canWrite()) {
87         path = defaultLocation; // use default if you can
88
}
89     }
90
91         File installDir = new File(path);
92
93         if (!installDir.exists()) {
94         installDir.mkdirs();
95         if (!installDir.exists()) {
96         // The installFailed string is only for debugging. No localization needed
97
installFailed("couldntCreateDirectory", null);
98         return;
99         }
100         }
101     
102     // Show license if neccesary
103
enableStep(STEP_LICENSE);
104     if (!showLicensing()) {
105         // The installFailed string is only for debugging. No localization needed
106
installFailed("Licensing was not accepted", null);
107     };
108     
109     // Make sure that the data JAR is downloaded
110
enableStep(STEP_DOWNLOAD);
111     if (!downloadInstallerComponent()) {
112         // The installFailed string is only for debugging. No localization needed
113
installFailed("Unable to download data component", null);
114     }
115     
116         String JavaDoc nativeLibName = Config.getNativeLibName();
117         File installerFile = null;
118     
119         try {
120         // Load native library into process if found
121
if (nativeLibName != null && !Config.isSolarisInstall()) {
122         System.loadLibrary(nativeLibName);
123         }
124         
125         // Unpack installer
126
enableStep(STEP_UNPACK);
127         String JavaDoc installResource = Config.getInstallerResource();
128         Config.trace("Installer resource: " + installResource);
129         installerFile = unpackInstaller(installResource);
130         
131         // To clean-up downloaded files
132
Config.trace("Unpacked installer to: " + installerFile);
133         if (installerFile == null) {
134         // The installFailed string is only for debugging. No localization needed
135
installFailed("Could not unpack installer components", null);
136         return;
137         }
138         
139         enableStep(STEP_INSTALL);
140         setStepText(STEP_INSTALL, Config.getWindowStepWait(STEP_INSTALL));
141         
142         boolean success = false;
143         if (Config.isSolarisInstall()) {
144         success = runSolarisInstaller(path, installerFile);
145         } else {
146         success = runWindowsInstaller(path, installerFile);
147         }
148         
149         if (!success) {
150         // The installFailed string is only for debugging. No localization needed
151
installFailed("Could not run installer", null);
152         return;
153         }
154         } catch(UnsatisfiedLinkError JavaDoc ule) {
155         // The installFailed string is only for debugging. No localization needed
156
installFailed("Unable to load library: " + nativeLibName, null);
157         return;
158         } finally {
159         if (installerFile != null) {
160         installerFile.delete();
161         }
162         }
163         
164         setStepText(STEP_INSTALL, Config.getWindowStep(STEP_INSTALL));
165         enableStep(STEP_DONE);
166         
167         String JavaDoc execPath = path + Config.getJavaPath();
168         Config.trace(execPath);
169     
170         /** Remove installer JAR from cache */
171         removeInstallerComponent();
172         
173     // If we're running anything after 1.0.1 or not on Windows, just call
174
// finishedInstall. Otherwise, deny ExitVM permission so that we can
175
// return here and do a reboot. We have to do this because we need to
176
// call ExtensionInstallerService.finishedInstall(), which registers
177
// that our extension (the JRE) is installed. Unfortunately pre-1.2 it
178
// also does not understand that we are requesting a reboot, and calls
179
// System.exit(). So for pre 1.2 we want to deny the permission to
180
// exit the VM so we can return here and perform a reboot.
181
boolean ispre12 = false;
182     String JavaDoc version = Config.getJavaWSVersion();
183     // get first tuple
184
String JavaDoc v = version.substring(version.indexOf('-')+1);
185     int i2 = v.indexOf('.');
186     int v1 = Integer.parseInt(v.substring(0, i2));
187     // get second tuple
188
v = v.substring(i2+1);
189     i2 = v.indexOf('.');
190     if (i2 == -1) i2 = v.indexOf('-');
191         if (i2 == -1) i2 = v.indexOf('[');
192     if (i2 == -1) i2 = v.length();
193     int v2 = Integer.parseInt(v.substring(0,i2));
194     // are we pre 1.2?
195
if (v1 < 1 || (v1 == 1 && v2 < 2)) ispre12 = true;
196
197     if (Config.isWindowsInstall() && ispre12 && Config.isHopper()) {
198         // deny ExitVM permission then call finishedInstall
199
ProtectionDomain pd = (new Object JavaDoc()).getClass().getProtectionDomain();
200         CodeSource cs = pd.getCodeSource();
201         AllPermissionExceptExitVM perm = new AllPermissionExceptExitVM();
202         PermissionCollection newpc = perm.newPermissionCollection();
203         newpc.add (perm);
204         
205         // run finishedInstall within the new context which excluded
206
// just the ExitVM permission
207
ProtectionDomain newpd = new ProtectionDomain(cs, newpc);
208         AccessControlContext newacc =
209         new AccessControlContext(new ProtectionDomain[] {newpd});
210         final String JavaDoc fExecPath = execPath;
211         try {
212         AccessController.doPrivileged(new PrivilegedExceptionAction() {
213             public Object JavaDoc run() throws SecurityException JavaDoc {
214             finishedInstall(fExecPath);
215             return null;
216             }
217         }, newacc);
218         } catch (PrivilegedActionException pae) {
219         // swallow the exception because we want ExitVM to fail silent
220
} catch (SecurityException JavaDoc se) {
221         // swallow the exception because we want ExitVM to fail silent
222
}
223     } else {
224         // just call finished Install
225
finishedInstall(execPath);
226     }
227
228     if (Config.isWindowsInstall() &&
229         WindowsInstaller.IsRebootNecessary()) {
230         // reboot
231
if (!WindowsInstaller.askUserForReboot()) System.exit(0);
232     } else {
233         System.exit(0);
234     }
235     }
236
237     private static final Permission exitVMPermission = new RuntimePermission JavaDoc("exitVM");
238     
239     private static final class AllPermissionExceptExitVM extends Permission {
240     public AllPermissionExceptExitVM() {
241         super("<all permissions except Exit VM>");
242     }
243
244     public AllPermissionExceptExitVM(String JavaDoc name, String JavaDoc actions) {
245         this();
246     }
247
248     public boolean implies(Permission p) {
249         if (p instanceof RuntimePermission JavaDoc &&
250         p.equals(exitVMPermission)) {
251         return false;
252         } else return true;
253     }
254     
255     public boolean equals(Object JavaDoc o) {
256         return (o instanceof AllPermissionExceptExitVM);
257     }
258
259     public String JavaDoc getActions() {
260         return new String JavaDoc("<all actions>");
261     }
262
263     public int hashCode() {
264         return 1;
265     }
266
267     public PermissionCollection newPermissionCollection() {
268         return new AllPermissionExceptExitVMCollection();
269     }
270
271
272     }
273
274     private static final class AllPermissionExceptExitVMCollection
275     extends PermissionCollection implements java.io.Serializable JavaDoc
276     {
277     private boolean all_allowed; // true if any all permissions have been added
278

279     /**
280      * Create an empty AllPermissions object.
281      *
282      */

283
284     public AllPermissionExceptExitVMCollection() {
285         all_allowed = false;
286     }
287
288     /**
289      * Adds a permission to the AllPermissions. The key for the hash is
290      * permission.path.
291      *
292      * @param permission the Permission object to add.
293      *
294      * @exception IllegalArgumentException - if the permission is not a
295      * AllPermission
296      *
297      * @exception SecurityException - if this AllPermissionCollection object
298      * has been marked readonly
299      */

300
301     public void add(Permission permission)
302     {
303         if (! (permission instanceof AllPermissionExceptExitVM))
304         throw new IllegalArgumentException JavaDoc("invalid permission: "+
305                            permission);
306         if (isReadOnly())
307         throw new SecurityException JavaDoc("attempt to add a Permission to a readonly PermissionCollection");
308
309         all_allowed = true;
310     }
311
312     /**
313      * Check and see if this set of permissions implies the permissions
314      * expressed in "permission".
315      *
316      * @param p the Permission object to compare
317      *
318      * @return always returns true.
319      */

320
321     public boolean implies(Permission permission)
322     {
323         return ((permission instanceof RuntimePermission JavaDoc &&
324             permission.equals(exitVMPermission)) ?
325             false : all_allowed);
326     }
327
328     /**
329      * Returns an enumeration of all the AllPermission objects in the
330      * container.
331      *
332      * @return an enumeration of all the AllPermission objects.
333      */

334     public Enumeration elements()
335     {
336         return new Enumeration() {
337         private boolean hasMore = all_allowed;
338
339         public boolean hasMoreElements() {
340             return hasMore;
341         }
342
343         public Object JavaDoc nextElement() {
344             hasMore = false;
345             return new AllPermissionExceptExitVM();
346         }
347         };
348     }
349     }
350
351     /** Download data component JAR */
352     static public boolean downloadInstallerComponent() {
353         DownloadService downloadService = Config.getDownloadService();
354         DownloadServiceListener listener = downloadService.getDefaultProgressWindow();
355         String JavaDoc compName = Config.getInstallerLocation();
356         String JavaDoc compVer = Config.getInstallerVersion();
357         try {
358         URL codebase = Config.getBasicService().getCodeBase();
359         URL url = new URL(codebase, compName);
360         String JavaDoc urlstr = url.toString();
361      
362         if (!downloadService.isResourceCached(url, compVer)) {
363         // The installFailed string is only for debugging. No localization needed
364
Config.trace("Downloading: " + urlstr);
365         // Do download
366
downloadService.loadResource(url, compVer, listener);
367         }
368         } catch(IOException ioe) {
369         Config.trace("Unable to download: " + compName + "/" + compVer);
370         return false;
371         }
372     return true;
373     }
374     
375     /** Remove data component data JAR from cache */
376     static public void removeInstallerComponent() {
377     DownloadService downloadService = Config.getDownloadService();
378     if (downloadService != null) {
379         String JavaDoc component = Config.getInstallerLocation();
380         String JavaDoc version = Config.getInstallerVersion();
381         try {
382         URL codebase = Config.getBasicService().getCodeBase();
383         URL url = new URL(codebase, component);
384         component = url.toString();
385         Config.trace("Removing: " + component + "/" + version);
386         downloadService.removeResource(url, version);
387         } catch(IOException ioe) {
388         Config.trace("Unable to remove " + component + "/" + version);
389         }
390     } else {
391         Config.trace("No download service found");
392     }
393     }
394     
395     /** Runs a Solaris installer */
396     static public boolean runSolarisInstaller(String JavaDoc installPath, File installFile) {
397     
398     /** Build temp. script file */
399     File script = null;
400     boolean success = false;
401     try {
402         script = SolarisInstaller.createTempShellScript();
403         
404         String JavaDoc[] args = new String JavaDoc[3];
405         args[0] = installPath;
406         args[1] = script.getAbsolutePath();
407         args[2] = installFile.getAbsolutePath();
408         String JavaDoc execString = getExecuteString(args);
409         success = SolarisInstaller.execute(execString);
410     } catch(IOException ioe) {
411         Config.trace("Got ioe: " + ioe);
412         return false;
413     } finally {
414         if (script != null) script.delete();
415     }
416     return success;
417     }
418     
419     
420     /** Runs a Windows installer */
421     static public boolean runWindowsInstaller(String JavaDoc installPath, File installFile) {
422     boolean deleteHopperKey = false;
423     boolean deleteMerlinKey = false;
424     // If Hopper, and JavaWS can update, ask the user if they want
425
// to update.
426
if (Config.isHopper() &&
427         !WinRegistry.doesSubKeyExist(WinRegistry.HKEY_LOCAL_MACHINE,
428                      JAVAWS_HOPPER_KEY)) {
429         int res =
430         JOptionPane.showConfirmDialog(_installerFrame,
431                           Config.getJavaWSConfirmMessage(),
432                           Config.getJavaWSConfirmTitle(),
433                           JOptionPane.YES_NO_OPTION);
434         if (res == JOptionPane.NO_OPTION) {
435         // create the registry key so that JavaWS will not install
436
WinRegistry.setStringValue(WinRegistry.HKEY_LOCAL_MACHINE,
437                        JAVAWS_HOPPER_KEY,
438                        "Home", "");
439         // flag to delete the key later
440
deleteHopperKey = true;
441         }
442     }
443
444     // If Merlin, never update JavaWS. 1.0.1_02 bundled with Merlin does
445
// not have the ability to update while JavaWS is running. So just
446
// prevent the update by spoofing the registry key.
447
if (Config.isMerlin()) {
448         WinRegistry.setStringValue(WinRegistry.HKEY_LOCAL_MACHINE,
449                        JAVAWS_MERLIN_KEY,
450                        "Home", "");
451         deleteMerlinKey = true;
452     }
453         
454     /** Build temp. script file */
455     boolean success = false;
456     File iss = null;
457     try {
458         String JavaDoc[] args = new String JavaDoc[2];
459         args[0] = installFile.getAbsolutePath();
460         if (Config.getJavaVersion().startsWith("1.4.2")) {
461             args[1] = "/s /v\"/qn WEBSTARTICON=1 INSTALLDIR=\\\""+installPath +"\\\"\"";
462
463         }
464         else {
465         iss = WindowsInstaller.createTempISSScript(
466             installPath,
467             Config.getJavaVersion());
468             args[1] = iss.getAbsolutePath();
469         }
470         String JavaDoc execString = getExecuteString(args);
471         success = WindowsInstaller.execute(execString);
472     } catch(IOException ioe) {
473         return false;
474     } finally {
475         if (iss != null) iss.delete();
476     }
477
478     // delete any spoofed keys we created earlier
479
if (deleteHopperKey) {
480         WinRegistry.deleteKey(WinRegistry.HKEY_LOCAL_MACHINE,
481                   JAVAWS_HOPPER_KEY);
482     }
483     if (deleteMerlinKey) {
484         WinRegistry.deleteKey(WinRegistry.HKEY_LOCAL_MACHINE,
485                   JAVAWS_MERLIN_KEY);
486     }
487
488     // 4662215 cannot reboot here because the config hasn't been written
489
// by JavaWS yet. Reboot later, after installSucceeded has been
490
// called.
491
// WindowsInstaller.rebootIfNecessary();
492

493     return success;
494     }
495     
496     /**
497      * Returns the string to execute, which is determined
498      * from the property <code>install.execString</code>. MessageFormat
499      * is used to reformat the string. The first argument is the
500      * the install path, with the remaining arguments the paths to the
501      * extracted files that were downloaded.
502      */

503     static private String JavaDoc getExecuteString(String JavaDoc[] args) {
504     String JavaDoc execString = Config.getExecString();
505     if (execString == null) {
506         Config.trace("No exec string specified");
507         return null;
508     }
509     String JavaDoc apply = MessageFormat.format(execString, args);
510     Config.trace("exec string !" + apply + "!");
511     return apply;
512     }
513     
514     /** Unpacks a resource to a temp. file
515      */

516     static public File unpackInstaller(String JavaDoc resourceName) {
517     // Array to hold all results (this code is slightly more
518
// generally that it needs to be)
519
File[] results = new File[1];
520     URL[] urls = new URL[1];
521     
522     // Determine size of download
523
ClassLoader JavaDoc cl = Main.class.getClassLoader();
524     urls[0] = cl.getResource(Config.getInstallerResource());
525     if (urls[0] == null) {
526         Config.trace("Could not find resource: " + Config.getInstallerResource());
527         return null;
528     }
529     
530     int totalSize = 0;
531     int totalRead = 0;
532     for(int i = 0; i < urls.length; i++) {
533         if (urls[i] != null) {
534         try {
535             URLConnection connection = urls[i].openConnection();
536             totalSize += connection.getContentLength();
537         } catch(IOException ioe) {
538             Config.trace("Got exception: " + ioe);
539             return null;
540         }
541         }
542     }
543     
544     // Unpack each file
545
for(int i = 0; i < urls.length; i++) {
546         if (urls[i] != null) {
547         // Create temp. file to store unpacked file in
548
InputStream in = null;
549         OutputStream out = null;
550         try {
551             // Use extension from URL (important for dll files)
552
String JavaDoc extension = new File(urls[i].getFile()).getName();
553             int lastdotidx = (extension != null) ? extension.lastIndexOf('.') : -1;
554             if (lastdotidx == -1) {
555             extension = ".dat";
556             } else {
557             extension = extension.substring(lastdotidx);
558             }
559             
560             // Create output stream
561
results[i] = File.createTempFile("jre", extension);
562             results[i].deleteOnExit();
563             out = new FileOutputStream(results[i]);
564             
565             // Create inputstream
566
URLConnection connection = urls[i].openConnection();
567             in = connection.getInputStream();
568             
569             int read = 0;
570             byte[] buf = new byte[BUFFER_SIZE];
571             while ((read = in.read(buf)) != -1) {
572             out.write(buf, 0, read);
573             // Notify delegate
574
totalRead += read;
575             if (totalRead > totalSize && totalSize != 0) totalSize = totalRead;
576             
577             // Update UI
578
if (totalSize != 0) {
579                 int percent = (100 * totalRead) / totalSize;
580                 setStepText(STEP_UNPACK,
581                     Config.getWindowStepProgress(STEP_UNPACK, percent));
582             }
583             }
584         } catch(IOException ie) {
585             Config.trace("Got exception while downloading resource: " + ie);
586             for(int j = 0; j < results.length; j++) {
587             if (results[j] != null) results[j].delete();
588             }
589             return null;
590         } finally {
591             try {
592             if (in != null) in.close();
593             if (out != null) out.close();
594             } catch(IOException io) { /* ignore */ }
595         }
596         }
597     }
598     
599     setStepText(STEP_UNPACK, Config.getWindowStep(STEP_UNPACK));
600     return results[0];
601     }
602     
603     /**
604      * Invoked when the install finishes.
605      */

606     public static void finishedInstall(final String JavaDoc execPath) {
607     // Use a runnable as more than likely we've queued up a bunch of
608
// Runnables
609
try {
610         SwingUtilities.invokeAndWait(new Runnable JavaDoc() {
611         public void run() {
612             // do nothing
613
}
614         });
615     } catch(java.lang.reflect.InvocationTargetException JavaDoc ite) {
616         Config.trace("Unexpected exception: " + ite);
617     } catch(InterruptedException JavaDoc ie) {
618         Config.trace("Unexpected exception: " + ie);
619     }
620     String JavaDoc platformVersion = Config.getPlatformVersion();
621     Config.getInstallService().setJREInfo(platformVersion, execPath);
622     Config.getInstallService().
623         installSucceeded(Config.isWindowsInstall() &&
624                  WindowsInstaller.IsRebootNecessary());
625     }
626     
627     /**
628      * Invoked when the installer has failed.
629      */

630     public static void installFailed(final String JavaDoc description, Throwable JavaDoc th) {
631     Config.trace("installFailed: " + description + " " + th);
632     if (SwingUtilities.isEventDispatchThread()) {
633         Config.getInstallService().installFailed();
634         System.exit(-1);
635     } else {
636         try {
637         SwingUtilities.invokeAndWait(new Runnable JavaDoc() {
638                 public void run() {
639                 Config.getInstallService().installFailed();
640                 System.exit(-1);
641                 }
642             });
643         } catch(java.lang.reflect.InvocationTargetException JavaDoc ite) {
644         Config.trace("Unexpected exception: " + ite);
645         } catch(InterruptedException JavaDoc ie) {
646         Config.trace("Unexpected exception: " + ie);
647         }
648     }
649     }
650     
651     /** Main method. Invokes installer or uninstaller */
652     public static void main(String JavaDoc[] args) {
653     // Only supports install
654
if (args.length > 0 && args[0].equals("install")) {
655         install();
656     }
657     }
658     
659     public static boolean showLicensing() {
660     if (Config.getLicenseResource() == null) return true;
661     ClassLoader JavaDoc cl = Main.class.getClassLoader();
662     URL url = cl.getResource(Config.getLicenseResource());
663     if (url == null) return true;
664     
665     String JavaDoc license = null;
666     try {
667         URLConnection con = url.openConnection();
668         int size = con.getContentLength();
669         byte[] content = new byte[size];
670         InputStream in = new BufferedInputStream(con.getInputStream());
671         in.read(content);
672         license = new String JavaDoc(content);
673     } catch(IOException ioe) {
674         Config.trace("Got exception when reading " + Config.getLicenseResource() + ": " + ioe);
675         return false;
676     }
677     
678     // Build dialog
679
JTextArea ta = new JTextArea(license);
680     ta.setEditable(false);
681     final JDialog jd = new JDialog(_installerFrame, true);
682         Container comp = jd.getContentPane();
683         jd.setTitle(Config.getLicenseDialogTitle());
684     comp.setLayout(new BorderLayout(10, 10));
685     comp.add(new JScrollPane(ta), "Center");
686     Box box = new Box(BoxLayout.X_AXIS);
687     box.add(box.createHorizontalStrut(10));
688     box.add(new JLabel(Config.getLicenseDialogQuestionString()));
689     box.add(box.createHorizontalGlue());
690     JButton acceptButton = new JButton(Config.getLicenseDialogAcceptString());
691     JButton exitButton = new JButton(Config.getLicenseDialogExitString());
692     box.add(acceptButton);
693     box.add(box.createHorizontalStrut(10));
694     box.add(exitButton);
695     box.add(box.createHorizontalStrut(10));
696     jd.getRootPane().setDefaultButton(acceptButton);
697     Box box2 = new Box(BoxLayout.Y_AXIS);
698     box2.add(box);
699     box2.add(box2.createVerticalStrut(5));
700     comp.add(box2, "South");
701     jd.pack();
702     
703     final boolean accept[] = new boolean[1];
704     acceptButton.addActionListener(new ActionListener() {
705             public void actionPerformed(ActionEvent e) {
706             accept[0] = true;
707             jd.hide();
708             jd.dispose();
709             }
710         });
711     
712     exitButton.addActionListener(new ActionListener() {
713             public void actionPerformed(ActionEvent e) {
714             accept[0] = false;
715             jd.hide();
716             jd.dispose();
717             }
718         });
719     
720     // Apply any defaults the user may have, constraining to the size
721
// of the screen, and default (packed) size.
722
Rectangle size = new Rectangle(0, 0, 500, 300);
723     Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
724     size.width = Math.min(screenSize.width, size.width);
725     size.height = Math.min(screenSize.height, size.height);
726     // Center the window
727
jd.setBounds((screenSize.width - size.width) / 2,
728              (screenSize.height - size.height) / 2,
729              size.width, size.height);
730     
731     // Show dialog
732
jd.show();
733     
734     return accept[0];
735     }
736     
737     //
738
// Build installer window
739
//
740
static public void showInstallerWindow() {
741     _installerFrame = new JFrame(Config.getWindowTitle());
742     
743     Container cont = _installerFrame.getContentPane();
744     cont.setLayout(new BorderLayout());
745     
746     // North pane
747
Box topPane = new Box(BoxLayout.X_AXIS);
748     JLabel title = new JLabel(Config.getWindowHeading());
749     Font titleFont = new Font("SansSerif", Font.BOLD, 22);
750     title.setFont(titleFont);
751     title.setForeground(Color.black);
752     
753         // Create Sun logo
754
URL urlLogo = Main.class.getResource(Config.getWindowLogo());
755     Image img = Toolkit.getDefaultToolkit().getImage(urlLogo);
756     MediaTracker md = new MediaTracker(_installerFrame);
757     md.addImage(img, 0);
758     try { md.waitForAll();
759     } catch(Exception JavaDoc ioe) { Config.trace(ioe.toString()); }
760     if (md.isErrorID(0)) Config.trace("Error loading image");
761     Icon sunLogo = new ImageIcon(img);
762     JLabel logoLabel = new JLabel(sunLogo);
763     logoLabel.setOpaque(true);
764     topPane.add(topPane.createHorizontalStrut(5));
765     topPane.add(title);
766     topPane.add(topPane.createHorizontalGlue());
767     topPane.add(logoLabel);
768     topPane.add(topPane.createHorizontalStrut(5));
769     
770     // West Pane
771
Box westPane = new Box(BoxLayout.X_AXIS);
772     westPane.add(westPane.createHorizontalStrut(10));
773     
774     // South Pane
775
Box bottomPane = new Box(BoxLayout.X_AXIS);
776     bottomPane.add(bottomPane.createHorizontalGlue());
777     JButton abortButton = new JButton(Config.getWindowAbortButton());
778     abortButton.setMnemonic(Config.getWindowAbortMnemonic());
779     bottomPane.add(abortButton);
780     bottomPane.add(bottomPane.createHorizontalGlue());
781     bottomPane.setBorder(BorderFactory.createEmptyBorder(0,0,5,0));
782     
783     // Center Pane
784
Box centerPane = new Box(BoxLayout.Y_AXIS);
785         JLabel hidden = new JLabel(Config.getWindowHiddenLabel());
786         hidden.setVisible(false);
787         centerPane.add(hidden);
788     _stepLabels = new JLabel[5];
789     for(int i = 0; i < _stepLabels.length; i++) {
790         _stepLabels[i] = new JLabel(Config.getWindowStep(i));
791         _stepLabels[i].setEnabled(false);
792         centerPane.add(_stepLabels[i]);
793
794         // install label's length will expand,so set a longer size.
795
if(i == STEP_INSTALL) {
796                 Dimension dim = new JLabel(Config.
797                         getWindowStepWait(STEP_INSTALL)).getPreferredSize();
798                 _stepLabels[i].setPreferredSize(dim);
799             }
800     }
801         hidden = new JLabel(Config.getWindowHiddenLabel());
802         hidden.setVisible(false);
803         centerPane.add(hidden);
804         
805     // Setup box layout
806
cont.add(topPane, "North");
807     cont.add(westPane, "West");
808     cont.add(bottomPane, "South");
809     cont.add(centerPane, "Center");
810     
811     _installerFrame.pack();
812     Dimension dim = _installerFrame.getSize();
813
814         // hard code to ensure title is completely visible on Sol/lin.
815
if(dim.width < 400) {
816             dim.width = 400;
817             _installerFrame.setSize(dim);
818         }
819     
820     Rectangle size = _installerFrame.getBounds();
821         Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
822         size.width = Math.min(screenSize.width, size.width);
823         size.height = Math.min(screenSize.height, size.height);
824         // Put window at 1/4, 1/4 of screen resoluion
825
_installerFrame.setBounds((screenSize.width - size.width) / 4,
826                       (screenSize.height - size.height) / 4,
827                   size.width, size.height);
828     
829     // Setup event listners
830
_installerFrame.addWindowListener(new WindowAdapter() {
831             public void windowClosing(WindowEvent we) {
832             installFailed("Window closed", null);
833             }
834         });
835     
836     abortButton.addActionListener(new ActionListener() {
837             public void actionPerformed(ActionEvent ae) {
838             installFailed("Abort pressed", null);
839             }
840         });
841     
842     // Show window
843
_installerFrame.show();
844     }
845     
846     
847     public static void enableStep(final int s) {
848     SwingUtilities.invokeLater(new Runnable JavaDoc() {
849             public void run() {
850             for(int i = 0; i < _stepLabels.length; i++) {
851                 _stepLabels[i].setEnabled(i == s);
852             }
853             }
854         });
855     }
856     
857     public static void setStepText(final int step, final String JavaDoc text) {
858     SwingUtilities.invokeLater(new Runnable JavaDoc() {
859             public void run() {
860             _stepLabels[step].setText(text);
861             }
862         });
863     }
864 }
865
866
867
Popular Tags