KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > antlr > xjlib > appkit > utils > BrowserLauncher


1 package org.antlr.xjlib.appkit.utils;
2
3 import java.io.File JavaDoc;
4 import java.io.IOException JavaDoc;
5 import java.lang.reflect.Constructor JavaDoc;
6 import java.lang.reflect.Field JavaDoc;
7 import java.lang.reflect.InvocationTargetException JavaDoc;
8 import java.lang.reflect.Method JavaDoc;
9
10 /**
11  * BrowserLauncher is a class that provides one static method, openURL, which opens the default
12  * web browser for the current user of the system to the given URL. It may support other
13  * protocols depending on the system -- mailto, ftp, etc. -- but that has not been rigorously
14  * tested and is not guaranteed to work.
15  * <p>
16  * Yes, this is platform-specific code, and yes, it may rely on classes on certain platforms
17  * that are not part of the standard JDK. What we're trying to do, though, is to take something
18  * that's frequently desirable but inherently platform-specific -- opening a default browser --
19  * and allow programmers (you, for example) to do so without worrying about dropping into native
20  * code or doing anything else similarly evil.
21  * <p>
22  * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant systems without
23  * modification or a need for additional libraries. All classes that are required on certain
24  * platforms to allow this to run are dynamically loaded at runtime via reflection and, if not
25  * found, will not cause this to do anything other than returning an error when opening the
26  * browser.
27  * <p>
28  * There are certain system requirements for this class, as it's running through Runtime.exec(),
29  * which is Java's way of making a native system call. Currently, this requires that a Macintosh
30  * have a Finder which supports the GURL event, which is true for Mac OS 8.0 and 8.1 systems that
31  * have the Internet Scripting AppleScript dictionary installed in the Scripting Additions folder
32  * in the Extensions folder (which is installed by default as far as I know under Mac OS 8.0 and
33  * 8.1), and for all Mac OS 8.5 and later systems. On Windows, it only runs under Win32 systems
34  * (Windows 95, 98, and NT 4.0, as well as later versions of all). On other systems, this drops
35  * back from the inherently platform-sensitive concept of a default browser and simply attempts
36  * to launch Netscape via a shell command.
37  * <p>
38  * This code is Copyright 1999-2001 by Eric Albert (ejalbert@cs.stanford.edu) and may be
39  * redistributed or modified in any form without restrictions as long as the portion of this
40  * comment from this paragraph through the end of the comment is not removed. The author
41  * requests that he be notified of any application, applet, or other binary that makes use of
42  * this code, but that's more out of curiosity than anything and is not required. This software
43  * includes no warranty. The author is not repsonsible for any loss of data or functionality
44  * or any adverse or unexpected effects of using this software.
45  * <p>
46  * Credits:
47  * <br>Steven Spencer, JavaWorld magazine (<a HREF="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java Tip 66</a>)
48  * <br>Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore,
49  * Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
50  *
51  * @author Eric Albert (<a HREF="mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu</a>)
52  * @version 1.4b1 (Released June 20, 2001)
53  */

54 public class BrowserLauncher {
55
56     /**
57      * The Java virtual machine that we are running on. Actually, in most cases we only care
58      * about the operating system, but some operating systems require us to switch on the VM. */

59     private static int jvm;
60
61     /** The browser for the system */
62     private static Object JavaDoc browser;
63
64     /**
65      * Caches whether any classes, methods, and fields that are not part of the JDK and need to
66      * be dynamically loaded at runtime loaded successfully.
67      * <p>
68      * Note that if this is <code>false</code>, <code>openURL()</code> will always return an
69      * IOException.
70      */

71     private static boolean loadedWithoutErrors;
72
73     /** The com.apple.mrj.MRJFileUtils class */
74     private static Class JavaDoc mrjFileUtilsClass;
75
76     /** The com.apple.mrj.MRJOSType class */
77     private static Class JavaDoc mrjOSTypeClass;
78
79     /** The com.apple.MacOS.AEDesc class */
80     private static Class JavaDoc<?> aeDescClass;
81     
82     /** The <init>(int) method of com.apple.MacOS.AETarget */
83     private static Constructor JavaDoc<?> aeTargetConstructor;
84     
85     /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
86     private static Constructor JavaDoc<?> appleEventConstructor;
87     
88     /** The <init>(String) method of com.apple.MacOS.AEDesc */
89     private static Constructor JavaDoc<?> aeDescConstructor;
90     
91     /** The findFolder method of com.apple.mrj.MRJFileUtils */
92     private static Method JavaDoc findFolder;
93
94     /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
95     private static Method JavaDoc getFileCreator;
96     
97     /** The getFileType method of com.apple.mrj.MRJFileUtils */
98     private static Method JavaDoc getFileType;
99     
100     /** The openURL method of com.apple.mrj.MRJFileUtils */
101     private static Method JavaDoc openURL;
102     
103     /** The makeOSType method of com.apple.MacOS.OSUtils */
104     private static Method JavaDoc makeOSType;
105     
106     /** The putParameter method of com.apple.MacOS.AppleEvent */
107     private static Method JavaDoc putParameter;
108     
109     /** The sendNoReply method of com.apple.MacOS.AppleEvent */
110     private static Method JavaDoc sendNoReply;
111     
112     /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
113     private static Object JavaDoc kSystemFolderType;
114
115     /** The keyDirectObject AppleEvent parameter type */
116     private static Integer JavaDoc keyDirectObject;
117
118     /** The kAutoGenerateReturnID AppleEvent code */
119     private static Integer JavaDoc kAutoGenerateReturnID;
120     
121     /** The kAnyTransactionID AppleEvent code */
122     private static Integer JavaDoc kAnyTransactionID;
123
124     /** The linkage object required for JDirect 3 on Mac OS X. */
125     private static Object JavaDoc linkage;
126     
127     /** The framework to reference on Mac OS X */
128     private static final String JavaDoc JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox";
129
130     /** JVM constant for MRJ 2.0 */
131     private static final int MRJ_2_0 = 0;
132     
133     /** JVM constant for MRJ 2.1 or later */
134     private static final int MRJ_2_1 = 1;
135
136     /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
137     private static final int MRJ_3_0 = 3;
138     
139     /** JVM constant for MRJ 3.1 */
140     private static final int MRJ_3_1 = 4;
141
142     /** JVM constant for any Windows NT JVM */
143     private static final int WINDOWS_NT = 5;
144     
145     /** JVM constant for any Windows 9x JVM */
146     private static final int WINDOWS_9x = 6;
147
148     private static final int LINUX = 7;
149
150     /** JVM constant for any other platform */
151     private static final int OTHER = -1;
152
153     /**
154      * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep non-U.S. English
155      * systems from working properly.
156      */

157     private static final String JavaDoc FINDER_TYPE = "FNDR";
158
159     /**
160      * The creator code of the Finder on a Macintosh, which is needed to send AppleEvents to the
161      * application.
162      */

163     private static final String JavaDoc FINDER_CREATOR = "MACS";
164
165     /** The name for the AppleEvent type corresponding to a GetURL event. */
166     private static final String JavaDoc GURL_EVENT = "GURL";
167
168     /**
169      * The first parameter that needs to be passed into Runtime.exec() to open the default web
170      * browser on Windows.
171      */

172     private static final String JavaDoc FIRST_WINDOWS_PARAMETER = "/c";
173     
174     /** The second parameter for Runtime.exec() on Windows. */
175     private static final String JavaDoc SECOND_WINDOWS_PARAMETER = "start";
176     
177     /**
178      * The third parameter for Runtime.exec() on Windows. This is a "title"
179      * parameter that the command line expects. Setting this parameter allows
180      * URLs containing spaces to work.
181      */

182     private static final String JavaDoc THIRD_WINDOWS_PARAMETER = "\"\"";
183     
184     /**
185      * The shell parameters for Netscape that opens a given URL in an already-open copy of Netscape
186      * on many command-line systems.
187      */

188     private static final String JavaDoc NETSCAPE_REMOTE_PARAMETER = "-remote";
189     private static final String JavaDoc NETSCAPE_OPEN_PARAMETER_START = "'openURL(";
190     private static final String JavaDoc NETSCAPE_OPEN_PARAMETER_END = ")'";
191     
192     /**
193      * The message from any exception thrown throughout the initialization process.
194      */

195     private static String JavaDoc errorMessage;
196
197     /**
198      * An initialization block that determines the operating system and loads the necessary
199      * runtime data.
200      */

201     static {
202         loadedWithoutErrors = true;
203         String JavaDoc osName = System.getProperty("os.name");
204         if (osName.startsWith("Mac OS")) {
205             String JavaDoc mrjVersion = System.getProperty("mrj.version");
206             String JavaDoc majorMRJVersion = mrjVersion.substring(0, 3);
207             try {
208                 double version = Double.valueOf(majorMRJVersion).doubleValue();
209                 if (version == 2) {
210                     jvm = MRJ_2_0;
211                 } else if (version >= 2.1 && version < 3) {
212                     // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
213
// works via Runtime.exec() and 2.2 supports that but has an openURL() method
214
// as well that we currently ignore.
215
jvm = MRJ_2_1;
216                 } else if (version == 3.0) {
217                     jvm = MRJ_3_0;
218                 } else if (version >= 3.1) {
219                     // Assume that all 3.1 and later versions of MRJ work the same.
220
jvm = MRJ_3_1;
221                 } else {
222                     loadedWithoutErrors = false;
223                     errorMessage = "Unsupported MRJ version: " + version;
224                 }
225             } catch (NumberFormatException JavaDoc nfe) {
226                 loadedWithoutErrors = false;
227                 errorMessage = "Invalid MRJ version: " + mrjVersion;
228             }
229         } else if (osName.startsWith("Windows")) {
230             if (osName.indexOf("9") != -1) {
231                 jvm = WINDOWS_9x;
232             } else {
233                 jvm = WINDOWS_NT;
234             }
235         } else if (osName.startsWith("Linux")) {
236             jvm = LINUX;
237         } else {
238             jvm = OTHER;
239         }
240         
241         if (loadedWithoutErrors) { // if we haven't hit any errors yet
242
loadedWithoutErrors = loadClasses();
243         }
244     }
245
246     /**
247      * This class should be never be instantiated; this just ensures so.
248      */

249     private BrowserLauncher() { }
250     
251     /**
252      * Called by a static initializer to load any classes, fields, and methods required at runtime
253      * to locate the user's web browser.
254      * @return <code>true</code> if all intialization succeeded
255      * <code>false</code> if any portion of the initialization failed
256      */

257     private static boolean loadClasses() {
258         switch (jvm) {
259             case MRJ_2_0:
260                 try {
261                     Class JavaDoc<?> aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
262                     Class JavaDoc osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
263                     Class JavaDoc<?> appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
264                     Class JavaDoc aeClass = Class.forName("com.apple.MacOS.ae");
265                     aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
266
267                     aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class JavaDoc [] { int.class });
268                     appleEventConstructor = appleEventClass.getDeclaredConstructor(new Class JavaDoc[] { int.class, int.class, aeTargetClass, int.class, int.class });
269                     aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class JavaDoc[] { String JavaDoc.class });
270
271                     makeOSType = osUtilsClass.getDeclaredMethod("makeOSType", new Class JavaDoc [] { String JavaDoc.class });
272                     putParameter = appleEventClass.getDeclaredMethod("putParameter", new Class JavaDoc[] { int.class, aeDescClass });
273                     sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply", new Class JavaDoc[] { });
274
275                     Field JavaDoc keyDirectObjectField = aeClass.getDeclaredField("keyDirectObject");
276                     keyDirectObject = (Integer JavaDoc) keyDirectObjectField.get(null);
277                     Field JavaDoc autoGenerateReturnIDField = appleEventClass.getDeclaredField("kAutoGenerateReturnID");
278                     kAutoGenerateReturnID = (Integer JavaDoc) autoGenerateReturnIDField.get(null);
279                     Field JavaDoc anyTransactionIDField = appleEventClass.getDeclaredField("kAnyTransactionID");
280                     kAnyTransactionID = (Integer JavaDoc) anyTransactionIDField.get(null);
281                 } catch (ClassNotFoundException JavaDoc cnfe) {
282                     errorMessage = cnfe.getMessage();
283                     return false;
284                 } catch (NoSuchMethodException JavaDoc nsme) {
285                     errorMessage = nsme.getMessage();
286                     return false;
287                 } catch (NoSuchFieldException JavaDoc nsfe) {
288                     errorMessage = nsfe.getMessage();
289                     return false;
290                 } catch (IllegalAccessException JavaDoc iae) {
291                     errorMessage = iae.getMessage();
292                     return false;
293                 }
294                 break;
295             case MRJ_2_1:
296                 try {
297                     mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
298                     mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
299                     Field JavaDoc systemFolderField = mrjFileUtilsClass.getDeclaredField("kSystemFolderType");
300                     kSystemFolderType = systemFolderField.get(null);
301                     findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder", new Class JavaDoc[] { mrjOSTypeClass });
302                     getFileCreator = mrjFileUtilsClass.getDeclaredMethod("getFileCreator", new Class JavaDoc[] { File JavaDoc.class });
303                     getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType", new Class JavaDoc[] { File JavaDoc.class });
304                 } catch (ClassNotFoundException JavaDoc cnfe) {
305                     errorMessage = cnfe.getMessage();
306                     return false;
307                 } catch (NoSuchFieldException JavaDoc nsfe) {
308                     errorMessage = nsfe.getMessage();
309                     return false;
310                 } catch (NoSuchMethodException JavaDoc nsme) {
311                     errorMessage = nsme.getMessage();
312                     return false;
313                 } catch (SecurityException JavaDoc se) {
314                     errorMessage = se.getMessage();
315                     return false;
316                 } catch (IllegalAccessException JavaDoc iae) {
317                     errorMessage = iae.getMessage();
318                     return false;
319                 }
320                 break;
321             case MRJ_3_0:
322                 try {
323                     Class JavaDoc<?> linker = Class.forName("com.apple.mrj.jdirect.Linker");
324                     Constructor JavaDoc<?> constructor = linker.getConstructor(new Class JavaDoc[]{ Class JavaDoc.class });
325                     linkage = constructor.newInstance(new Object JavaDoc[] { BrowserLauncher.class });
326                 } catch (ClassNotFoundException JavaDoc cnfe) {
327                     errorMessage = cnfe.getMessage();
328                     return false;
329                 } catch (NoSuchMethodException JavaDoc nsme) {
330                     errorMessage = nsme.getMessage();
331                     return false;
332                 } catch (InvocationTargetException JavaDoc ite) {
333                     errorMessage = ite.getMessage();
334                     return false;
335                 } catch (InstantiationException JavaDoc ie) {
336                     errorMessage = ie.getMessage();
337                     return false;
338                 } catch (IllegalAccessException JavaDoc iae) {
339                     errorMessage = iae.getMessage();
340                     return false;
341                 }
342                 break;
343             case MRJ_3_1:
344                 try {
345                     mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
346                     openURL = mrjFileUtilsClass.getDeclaredMethod("openURL", new Class JavaDoc[] { String JavaDoc.class });
347                 } catch (ClassNotFoundException JavaDoc cnfe) {
348                     errorMessage = cnfe.getMessage();
349                     return false;
350                 } catch (NoSuchMethodException JavaDoc nsme) {
351                     errorMessage = nsme.getMessage();
352                     return false;
353                 }
354                 break;
355             default:
356                 break;
357         }
358         return true;
359     }
360
361     /**
362      * Attempts to locate the default web browser on the local system. Caches results so it
363      * only locates the browser once for each use of this class per JVM instance.
364      * @return The browser for the system. Note that this may not be what you would consider
365      * to be a standard web browser; instead, it's the application that gets called to
366      * open the default web browser. In some cases, this will be a non-String object
367      * that provides the means of calling the default browser.
368      */

369     private static Object JavaDoc locateBrowser() {
370         if (browser != null) {
371             return browser;
372         }
373
374         switch (jvm) {
375             case MRJ_2_0:
376                 try {
377                     Integer JavaDoc finderCreatorCode = (Integer JavaDoc) makeOSType.invoke(null, new Object JavaDoc[] { FINDER_CREATOR });
378                     Object JavaDoc aeTarget = aeTargetConstructor.newInstance(new Object JavaDoc[] { finderCreatorCode });
379                     Integer JavaDoc gurlType = (Integer JavaDoc) makeOSType.invoke(null, new Object JavaDoc[] { GURL_EVENT });
380                     Object JavaDoc appleEvent = appleEventConstructor.newInstance(new Object JavaDoc[] { gurlType, gurlType, aeTarget, kAutoGenerateReturnID, kAnyTransactionID });
381                     // Don't set browser = appleEvent because then the next time we call
382
// locateBrowser(), we'll get the same AppleEvent, to which we'll already have
383
// added the relevant parameter. Instead, regenerate the AppleEvent every time.
384
// There's probably a way to do this better; if any has any ideas, please let
385
// me know.
386
return appleEvent;
387                 } catch (IllegalAccessException JavaDoc iae) {
388                     browser = null;
389                     errorMessage = iae.getMessage();
390                     return browser;
391                 } catch (InstantiationException JavaDoc ie) {
392                     browser = null;
393                     errorMessage = ie.getMessage();
394                     return browser;
395                 } catch (InvocationTargetException JavaDoc ite) {
396                     browser = null;
397                     errorMessage = ite.getMessage();
398                     return browser;
399                 }
400             case MRJ_2_1:
401                 File JavaDoc systemFolder;
402                 try {
403                     systemFolder = (File JavaDoc) findFolder.invoke(null, new Object JavaDoc[] { kSystemFolderType });
404                 } catch (IllegalArgumentException JavaDoc iare) {
405                     browser = null;
406                     errorMessage = iare.getMessage();
407                     return browser;
408                 } catch (IllegalAccessException JavaDoc iae) {
409                     browser = null;
410                     errorMessage = iae.getMessage();
411                     return browser;
412                 } catch (InvocationTargetException JavaDoc ite) {
413                     browser = null;
414                     errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
415                     return browser;
416                 }
417                 String JavaDoc[] systemFolderFiles = systemFolder.list();
418                 // Avoid a FilenameFilter because that can't be stopped mid-list
419
for(int i = 0; i < systemFolderFiles.length; i++) {
420                     try {
421                         File JavaDoc file = new File JavaDoc(systemFolder, systemFolderFiles[i]);
422                         if (!file.isFile()) {
423                             continue;
424                         }
425                         // We're looking for a file with a creator code of 'MACS' and
426
// a type of 'FNDR'. Only requiring the type results in non-Finder
427
// applications being picked up on certain Mac OS 9 systems,
428
// especially German ones, and sending a GURL event to those
429
// applications results in a logout under Multiple Users.
430
Object JavaDoc fileType = getFileType.invoke(null, new Object JavaDoc[] { file });
431                         if (FINDER_TYPE.equals(fileType.toString())) {
432                             Object JavaDoc fileCreator = getFileCreator.invoke(null, new Object JavaDoc[] { file });
433                             if (FINDER_CREATOR.equals(fileCreator.toString())) {
434                                 browser = file.toString(); // Actually the Finder, but that's OK
435
return browser;
436                             }
437                         }
438                     } catch (IllegalArgumentException JavaDoc iare) {
439                         errorMessage = iare.getMessage();
440                         return null;
441                     } catch (IllegalAccessException JavaDoc iae) {
442                         browser = null;
443                         errorMessage = iae.getMessage();
444                         return browser;
445                     } catch (InvocationTargetException JavaDoc ite) {
446                         browser = null;
447                         errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
448                         return browser;
449                     }
450                 }
451                 browser = null;
452                 break;
453             case MRJ_3_0:
454             case MRJ_3_1:
455                 browser = ""; // Return something non-null
456
break;
457             case WINDOWS_NT:
458                 browser = "cmd.exe";
459                 break;
460             case WINDOWS_9x:
461                 browser = "command.com";
462                 break;
463             case LINUX:
464             case OTHER:
465             default:
466                 // Jean Bovet: look for multiple browser in case netscape is not installed
467
browser = new String JavaDoc[] {"firefox", "mozilla", "netscape", "opera", "konqueror", "galeon", "firebird"};
468                 break;
469         }
470         return browser;
471     }
472
473     /**
474      * Attempts to open the default web browser to the given URL.
475      * @param url The URL to open
476      * @throws IOException If the web browser could not be located or does not run
477      */

478     public static void openURL(String JavaDoc url) throws IOException JavaDoc {
479         if (!loadedWithoutErrors) {
480             throw new IOException JavaDoc("Exception in finding browser: " + errorMessage);
481         }
482         Object JavaDoc browser = locateBrowser();
483         if (browser == null) {
484             throw new IOException JavaDoc("Unable to locate browser: " + errorMessage);
485         }
486         
487         switch (jvm) {
488             case MRJ_2_0:
489                 Object JavaDoc aeDesc;
490                 try {
491                     aeDesc = aeDescConstructor.newInstance(new Object JavaDoc[] { url });
492                     putParameter.invoke(browser, new Object JavaDoc[] { keyDirectObject, aeDesc });
493                     sendNoReply.invoke(browser, new Object JavaDoc[] { });
494                 } catch (InvocationTargetException JavaDoc ite) {
495                     throw new IOException JavaDoc("InvocationTargetException while creating AEDesc: " + ite.getMessage());
496                 } catch (IllegalAccessException JavaDoc iae) {
497                     throw new IOException JavaDoc("IllegalAccessException while building AppleEvent: " + iae.getMessage());
498                 } catch (InstantiationException JavaDoc ie) {
499                     throw new IOException JavaDoc("InstantiationException while creating AEDesc: " + ie.getMessage());
500                 } finally {
501                     aeDesc = null; // Encourage it to get disposed if it was created
502
browser = null; // Ditto
503
}
504                 break;
505             case MRJ_2_1:
506                 Runtime.getRuntime().exec(new String JavaDoc[] { (String JavaDoc) browser, url } );
507                 break;
508             case MRJ_3_0:
509                 int[] instance = new int[1];
510                 int result = ICStart(instance, 0);
511                 if (result == 0) {
512                     int[] selectionStart = new int[] { 0 };
513                     byte[] urlBytes = url.getBytes();
514                     int[] selectionEnd = new int[] { urlBytes.length };
515                     result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes,
516                                             urlBytes.length, selectionStart,
517                                             selectionEnd);
518                     if (result == 0) {
519                         // Ignore the return value; the URL was launched successfully
520
// regardless of what happens here.
521
ICStop(instance);
522                     } else {
523                         throw new IOException JavaDoc("Unable to launch URL: " + result);
524                     }
525                 } else {
526                     throw new IOException JavaDoc("Unable to create an Internet Config instance: " + result);
527                 }
528                 break;
529             case MRJ_3_1:
530                 try {
531                     openURL.invoke(null, new Object JavaDoc[] { url });
532                 } catch (InvocationTargetException JavaDoc ite) {
533                     throw new IOException JavaDoc("InvocationTargetException while calling openURL: " + ite.getMessage());
534                 } catch (IllegalAccessException JavaDoc iae) {
535                     throw new IOException JavaDoc("IllegalAccessException while calling openURL: " + iae.getMessage());
536                 }
537                 break;
538             case WINDOWS_NT:
539             case WINDOWS_9x:
540                 // Add quotes around the URL to allow ampersands and other special
541
// characters to work.
542
Process JavaDoc process = Runtime.getRuntime().exec(new String JavaDoc[] { (String JavaDoc) browser,
543                                                                 FIRST_WINDOWS_PARAMETER,
544                                                                 SECOND_WINDOWS_PARAMETER,
545                                                                 THIRD_WINDOWS_PARAMETER,
546                                                                 '"' + url + '"' });
547                 // This avoids a memory leak on some versions of Java on Windows.
548
// That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
549
try {
550                     process.waitFor();
551                     process.exitValue();
552                 } catch (InterruptedException JavaDoc ie) {
553                     throw new IOException JavaDoc("InterruptedException while launching browser: " + ie.getMessage());
554                 }
555                 break;
556             case LINUX:
557             case OTHER:
558                 // Assume that we're on Unix and that Netscape is installed
559
String JavaDoc[] array = (String JavaDoc[])browser;
560                 for (int i = 0; i < array.length; i++) {
561                     if(openUnixBrowser(array[i], url))
562                         return;
563                 }
564                 throw new IOException JavaDoc("Unable to locate browser");
565             default:
566                 // This should never occur, but if it does, we'll try the simplest thing possible
567
Runtime.getRuntime().exec(new String JavaDoc[] { (String JavaDoc) browser, url });
568                 break;
569         }
570     }
571
572     private static boolean openUnixBrowser(String JavaDoc browser, String JavaDoc url) {
573         boolean success = false;
574         Process JavaDoc process;
575         try {
576             // First, attempt to open the URL in a currently running session of Netscape
577
process = Runtime.getRuntime().exec(new String JavaDoc[] { (String JavaDoc) browser,
578                                                                NETSCAPE_REMOTE_PARAMETER,
579                                                                NETSCAPE_OPEN_PARAMETER_START +
580                     url +
581                     NETSCAPE_OPEN_PARAMETER_END });
582             try {
583                 int exitCode = process.waitFor();
584                 if (exitCode != 0) { // if Netscape was not open
585
Runtime.getRuntime().exec(new String JavaDoc[] { (String JavaDoc) browser, url });
586                     exitCode = 0;
587                 }
588                 success = (exitCode == 0);
589             } catch (InterruptedException JavaDoc ie) {
590                 //throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
591
}
592         } catch(IOException JavaDoc e) {
593
594         }
595         return success;
596     }
597
598     /**
599      * Methods required for Mac OS X. The presence of native methods does not cause
600      * any problems on other platforms.
601      */

602     private native static int ICStart(int[] instance, int signature);
603     private native static int ICStop(int[] instance);
604     private native static int ICLaunchURL(int instance, byte[] hint, byte[] data, int len,
605                                             int[] selectionStart, int[] selectionEnd);
606 }
607
Popular Tags