KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lucane > applications > rssreader > BrowserLauncher


1 package org.lucane.applications.rssreader;
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     /** JVM constant for any other platform */
149     private static final int OTHER = -1;
150
151     /**
152      * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep non-U.S. English
153      * systems from working properly.
154      */

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

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

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

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

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

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

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

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

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

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

472     public static void openURL(String JavaDoc url) throws IOException JavaDoc {
473         if (!loadedWithoutErrors) {
474             throw new IOException JavaDoc("Exception in finding browser: " + errorMessage);
475         }
476         Object JavaDoc browser = locateBrowser();
477         if (browser == null) {
478             throw new IOException JavaDoc("Unable to locate browser: " + errorMessage);
479         }
480         
481         switch (jvm) {
482             case MRJ_2_0:
483                 Object JavaDoc aeDesc = null;
484                 try {
485                     aeDesc = aeDescConstructor.newInstance(new Object JavaDoc[] { url });
486                     putParameter.invoke(browser, new Object JavaDoc[] { keyDirectObject, aeDesc });
487                     sendNoReply.invoke(browser, new Object JavaDoc[] { });
488                 } catch (InvocationTargetException JavaDoc ite) {
489                     throw new IOException JavaDoc("InvocationTargetException while creating AEDesc: " + ite.getMessage());
490                 } catch (IllegalAccessException JavaDoc iae) {
491                     throw new IOException JavaDoc("IllegalAccessException while building AppleEvent: " + iae.getMessage());
492                 } catch (InstantiationException JavaDoc ie) {
493                     throw new IOException JavaDoc("InstantiationException while creating AEDesc: " + ie.getMessage());
494                 } finally {
495                     aeDesc = null; // Encourage it to get disposed if it was created
496
browser = null; // Ditto
497
}
498                 break;
499             case MRJ_2_1:
500                 Runtime.getRuntime().exec(new String JavaDoc[] { (String JavaDoc) browser, url } );
501                 break;
502             case MRJ_3_0:
503                 int[] instance = new int[1];
504                 int result = ICStart(instance, 0);
505                 if (result == 0) {
506                     int[] selectionStart = new int[] { 0 };
507                     byte[] urlBytes = url.getBytes();
508                     int[] selectionEnd = new int[] { urlBytes.length };
509                     result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes,
510                                             urlBytes.length, selectionStart,
511                                             selectionEnd);
512                     if (result == 0) {
513                         // Ignore the return value; the URL was launched successfully
514
// regardless of what happens here.
515
ICStop(instance);
516                     } else {
517                         throw new IOException JavaDoc("Unable to launch URL: " + result);
518                     }
519                 } else {
520                     throw new IOException JavaDoc("Unable to create an Internet Config instance: " + result);
521                 }
522                 break;
523             case MRJ_3_1:
524                 try {
525                     openURL.invoke(null, new Object JavaDoc[] { url });
526                 } catch (InvocationTargetException JavaDoc ite) {
527                     throw new IOException JavaDoc("InvocationTargetException while calling openURL: " + ite.getMessage());
528                 } catch (IllegalAccessException JavaDoc iae) {
529                     throw new IOException JavaDoc("IllegalAccessException while calling openURL: " + iae.getMessage());
530                 }
531                 break;
532             case WINDOWS_NT:
533             case WINDOWS_9x:
534                 // Add quotes around the URL to allow ampersands and other special
535
// characters to work.
536
Process JavaDoc process = Runtime.getRuntime().exec(new String JavaDoc[] { (String JavaDoc) browser,
537                                                                 FIRST_WINDOWS_PARAMETER,
538                                                                 SECOND_WINDOWS_PARAMETER,
539                                                                 THIRD_WINDOWS_PARAMETER,
540                                                                 '"' + url + '"' });
541                 // This avoids a memory leak on some versions of Java on Windows.
542
// That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
543
try {
544                     process.waitFor();
545                     process.exitValue();
546                 } catch (InterruptedException JavaDoc ie) {
547                     throw new IOException JavaDoc("InterruptedException while launching browser: " + ie.getMessage());
548                 }
549                 break;
550             case OTHER:
551                 // Assume that we're on Unix and that Netscape is installed
552

553                 // First, attempt to open the URL in a currently running session of Netscape
554
process = Runtime.getRuntime().exec(new String JavaDoc[] { (String JavaDoc) browser,
555                                                     NETSCAPE_REMOTE_PARAMETER,
556                                                     NETSCAPE_OPEN_PARAMETER_START +
557                                                     url +
558                                                     NETSCAPE_OPEN_PARAMETER_END });
559                 try {
560                     int exitCode = process.waitFor();
561                     if (exitCode != 0) { // if Netscape was not open
562
Runtime.getRuntime().exec(new String JavaDoc[] { (String JavaDoc) browser, url });
563                     }
564                 } catch (InterruptedException JavaDoc ie) {
565                     throw new IOException JavaDoc("InterruptedException while launching browser: " + ie.getMessage());
566                 }
567                 break;
568             default:
569                 // This should never occur, but if it does, we'll try the simplest thing possible
570
Runtime.getRuntime().exec(new String JavaDoc[] { (String JavaDoc) browser, url });
571                 break;
572         }
573     }
574
575     /**
576      * Methods required for Mac OS X. The presence of native methods does not cause
577      * any problems on other platforms.
578      */

579     private native static int ICStart(int[] instance, int signature);
580     private native static int ICStop(int[] instance);
581     private native static int ICLaunchURL(int instance, byte[] hint, byte[] data, int len,
582                                             int[] selectionStart, int[] selectionEnd);
583 }
584
Popular Tags