4 import java.io.IOException;
5 import java.lang.reflect.Constructor;
6 import java.lang.reflect.Field;
7 import java.lang.reflect.InvocationTargetException;
8 import java.lang.reflect.Method;
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.
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.
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
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.
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.
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
51 * @author Eric Albert (<a href="mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu</a>)
52 * @version 1.4b1 (Released June 20, 2001)
54 public class BrowserLauncher {
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;
61 /** The browser for the system */
62 private static Object browser;
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.
68 * Note that if this is <code>false</code>, <code>openURL()</code> will always return an
71 private static boolean loadedWithoutErrors;
73 /** The com.apple.mrj.MRJFileUtils class */
74 private static Class mrjFileUtilsClass;
76 /** The com.apple.mrj.MRJOSType class */
77 private static Class mrjOSTypeClass;
79 /** The com.apple.MacOS.AEDesc class */
80 private static Class aeDescClass;
82 /** The <init>(int) method of com.apple.MacOS.AETarget */
83 private static Constructor aeTargetConstructor;
85 /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
86 private static Constructor appleEventConstructor;
88 /** The <init>(String) method of com.apple.MacOS.AEDesc */
89 private static Constructor aeDescConstructor;
91 /** The findFolder method of com.apple.mrj.MRJFileUtils */
92 private static Method findFolder;
94 /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
95 private static Method getFileCreator;
97 /** The getFileType method of com.apple.mrj.MRJFileUtils */
98 private static Method getFileType;
100 /** The openURL method of com.apple.mrj.MRJFileUtils */
101 private static Method openURLm;
103 /** The makeOSType method of com.apple.MacOS.OSUtils */
104 private static Method makeOSType;
106 /** The putParameter method of com.apple.MacOS.AppleEvent */
107 private static Method putParameter;
109 /** The sendNoReply method of com.apple.MacOS.AppleEvent */
110 private static Method sendNoReply;
112 /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
113 private static Object kSystemFolderType;
115 /** The keyDirectObject AppleEvent parameter type */
116 private static Integer keyDirectObject;
118 /** The kAutoGenerateReturnID AppleEvent code */
119 private static Integer kAutoGenerateReturnID;
121 /** The kAnyTransactionID AppleEvent code */
122 private static Integer kAnyTransactionID;
124 /** The linkage object required for JDirect 3 on Mac OS X. */
125 private static Object linkage;
127 /** The framework to reference on Mac OS X */
128 private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox";
130 /** JVM constant for MRJ 2.0 */
131 private static final int MRJ_2_0 = 0;
133 /** JVM constant for MRJ 2.1 or later */
134 private static final int MRJ_2_1 = 1;
136 /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
137 private static final int MRJ_3_0 = 3;
139 /** JVM constant for MRJ 3.1 */
140 private static final int MRJ_3_1 = 4;
142 /** JVM constant for any Windows NT JVM */
143 private static final int WINDOWS_NT = 5;
145 /** JVM constant for any Windows 9x JVM */
146 private static final int WINDOWS_9x = 6;
148 /** JVM constant for any other platform */
149 private static final int OTHER = -1;
152 * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep non-U.S. English
153 * systems from working properly.
155 private static final String FINDER_TYPE = "FNDR";
158 * The creator code of the Finder on a Macintosh, which is needed to send AppleEvents to the
161 private static final String FINDER_CREATOR = "MACS";
163 /** The name for the AppleEvent type corresponding to a GetURL event. */
164 private static final String GURL_EVENT = "GURL";
167 * The first parameter that needs to be passed into Runtime.exec() to open the default web
168 * browser on Windows.
170 private static final String FIRST_WINDOWS_PARAMETER = "/c";
172 /** The second parameter for Runtime.exec() on Windows. */
173 private static final String SECOND_WINDOWS_PARAMETER = "start";
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.
180 private static final String THIRD_WINDOWS_PARAMETER = "\"\"";
183 * The shell parameters for Netscape that opens a given URL in an already-open copy of Netscape
184 * on many command-line systems.
186 private static final String NETSCAPE_REMOTE_PARAMETER = "-remote";
187 private static final String NETSCAPE_OPEN_PARAMETER_START = "'openURL(";
188 private static final String NETSCAPE_OPEN_PARAMETER_END = ")'";
191 * The message from any exception thrown throughout the initialization process.
193 private static String errorMessage;
196 * An initialization block that determines the operating system and loads the necessary
200 loadedWithoutErrors = true;
201 String osName = System.getProperty("os.name");
202 if (osName.startsWith("Mac OS")) {
203 String mrjVersion = System.getProperty("mrj.version");
204 String majorMRJVersion = mrjVersion.substring(0, 3);
206 double version = Double.valueOf(majorMRJVersion).doubleValue();
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.
214 } else if (version == 3.0) {
216 } else if (version >= 3.1) {
217 // Assume that all 3.1 and later versions of MRJ work the same.
220 loadedWithoutErrors = false;
221 errorMessage = "Unsupported MRJ version: " + version;
223 } catch (NumberFormatException nfe) {
224 loadedWithoutErrors = false;
225 errorMessage = "Invalid MRJ version: " + mrjVersion;
227 } else if (osName.startsWith("Windows")) {
228 if (osName.indexOf("9") != -1) {
237 if (loadedWithoutErrors) { // if we haven't hit any errors yet
238 loadedWithoutErrors = loadClasses();
243 * This class should be never be instantiated; this just ensures so.
245 private BrowserLauncher() { }
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
253 private static boolean loadClasses() {
257 Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
258 Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
259 Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
260 Class aeClass = Class.forName("com.apple.MacOS.ae");
261 aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
263 aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class [] { int.class });
264 appleEventConstructor = appleEventClass.getDeclaredConstructor(new Class[] { int.class, int.class, aeTargetClass, int.class, int.class });
265 aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[] { String.class });
267 makeOSType = osUtilsClass.getDeclaredMethod("makeOSType", new Class [] { String.class });
268 putParameter = appleEventClass.getDeclaredMethod("putParameter", new Class[] { int.class, aeDescClass });
269 sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply", new Class[] { });
271 Field keyDirectObjectField = aeClass.getDeclaredField("keyDirectObject");
272 keyDirectObject = (Integer) keyDirectObjectField.get(null);
273 Field autoGenerateReturnIDField = appleEventClass.getDeclaredField("kAutoGenerateReturnID");
274 kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField.get(null);
275 Field anyTransactionIDField = appleEventClass.getDeclaredField("kAnyTransactionID");
276 kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
277 } catch (ClassNotFoundException cnfe) {
278 errorMessage = cnfe.getMessage();
280 } catch (NoSuchMethodException nsme) {
281 errorMessage = nsme.getMessage();
283 } catch (NoSuchFieldException nsfe) {
284 errorMessage = nsfe.getMessage();
286 } catch (IllegalAccessException iae) {
287 errorMessage = iae.getMessage();
293 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
294 mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
295 Field systemFolderField = mrjFileUtilsClass.getDeclaredField("kSystemFolderType");
296 kSystemFolderType = systemFolderField.get(null);
297 findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder", new Class[] { mrjOSTypeClass });
298 getFileCreator = mrjFileUtilsClass.getDeclaredMethod("getFileCreator", new Class[] { File.class });
299 getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType", new Class[] { File.class });
300 } catch (ClassNotFoundException cnfe) {
301 errorMessage = cnfe.getMessage();
303 } catch (NoSuchFieldException nsfe) {
304 errorMessage = nsfe.getMessage();
306 } catch (NoSuchMethodException nsme) {
307 errorMessage = nsme.getMessage();
309 } catch (SecurityException se) {
310 errorMessage = se.getMessage();
312 } catch (IllegalAccessException iae) {
313 errorMessage = iae.getMessage();
319 Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
320 Constructor constructor = linker.getConstructor(new Class[]{ Class.class });
321 linkage = constructor.newInstance(new Object[] { BrowserLauncher.class });
322 } catch (ClassNotFoundException cnfe) {
323 errorMessage = cnfe.getMessage();
325 } catch (NoSuchMethodException nsme) {
326 errorMessage = nsme.getMessage();
328 } catch (InvocationTargetException ite) {
329 errorMessage = ite.getMessage();
331 } catch (InstantiationException ie) {
332 errorMessage = ie.getMessage();
334 } catch (IllegalAccessException iae) {
335 errorMessage = iae.getMessage();
341 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
342 openURLm = mrjFileUtilsClass.getDeclaredMethod("openURL", new Class[] { String.class });
343 } catch (ClassNotFoundException cnfe) {
344 errorMessage = cnfe.getMessage();
346 } catch (NoSuchMethodException nsme) {
347 errorMessage = nsme.getMessage();
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.
365 private static Object locateBrowser() {
366 if (browser != null) {
372 Integer finderCreatorCode = (Integer) makeOSType.invoke(null, new Object[] { FINDER_CREATOR });
373 Object aeTarget = aeTargetConstructor.newInstance(new Object[] { finderCreatorCode });
374 Integer gurlType = (Integer) makeOSType.invoke(null, new Object[] { GURL_EVENT });
375 Object appleEvent = appleEventConstructor.newInstance(new Object[] { 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
382 } catch (IllegalAccessException iae) {
384 errorMessage = iae.getMessage();
386 } catch (InstantiationException ie) {
388 errorMessage = ie.getMessage();
390 } catch (InvocationTargetException ite) {
392 errorMessage = ite.getMessage();
398 systemFolder = (File) findFolder.invoke(null, new Object[] { kSystemFolderType });
399 } catch (IllegalArgumentException iare) {
401 errorMessage = iare.getMessage();
403 } catch (IllegalAccessException iae) {
405 errorMessage = iae.getMessage();
407 } catch (InvocationTargetException ite) {
409 errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
412 String[] systemFolderFiles = systemFolder.list();
413 // Avoid a FilenameFilter because that can't be stopped mid-list
414 for(int i = 0; i < systemFolderFiles.length; i++) {
416 File file = new File(systemFolder, systemFolderFiles[i]);
417 if (!file.isFile()) {
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 fileType = getFileType.invoke(null, new Object[] { file });
426 if (FINDER_TYPE.equals(fileType.toString())) {
427 Object fileCreator = getFileCreator.invoke(null, new Object[] { file });
428 if (FINDER_CREATOR.equals(fileCreator.toString())) {
429 browser = file.toString(); // Actually the Finder, but that's OK
433 } catch (IllegalArgumentException iare) {
434 errorMessage = iare.getMessage();
436 } catch (IllegalAccessException iae) {
438 errorMessage = iae.getMessage();
440 } catch (InvocationTargetException ite) {
442 errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
450 browser = ""; // Return something non-null
456 browser = "command.com";
460 browser = "netscape";
467 * Attempts to open the default web browser to the given URL.
468 * @param url The URL to open
469 * @throws IOException If the web browser could not be located or does not run
471 public static void openURL(String url) throws IOException {
472 if (!loadedWithoutErrors) {
473 throw new IOException("Exception in finding browser: " + errorMessage);
475 Object browser = locateBrowser();
476 if (browser == null) {
477 throw new IOException("Unable to locate browser: " + errorMessage);
482 Object aeDesc = null;
484 aeDesc = aeDescConstructor.newInstance(new Object[] { url });
485 putParameter.invoke(browser, new Object[] { keyDirectObject, aeDesc });
486 sendNoReply.invoke(browser, new Object[] { });
487 } catch (InvocationTargetException ite) {
488 throw new IOException("InvocationTargetException while creating AEDesc: " + ite.getMessage());
489 } catch (IllegalAccessException iae) {
490 throw new IOException("IllegalAccessException while building AppleEvent: " + iae.getMessage());
491 } catch (InstantiationException ie) {
492 throw new IOException("InstantiationException while creating AEDesc: " + ie.getMessage());
494 aeDesc = null; // Encourage it to get disposed if it was created
495 browser = null; // Ditto
499 Runtime.getRuntime().exec(new String[] { (String) browser, url } );
502 int[] instance = new int[1];
503 int result = ICStart(instance, 0);
505 int[] selectionStart = new int[] { 0 };
506 byte[] urlBytes = url.getBytes();
507 int[] selectionEnd = new int[] { urlBytes.length };
508 result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes,
509 urlBytes.length, selectionStart,
512 // Ignore the return value; the URL was launched successfully
513 // regardless of what happens here.
516 throw new IOException("Unable to launch URL: " + result);
519 throw new IOException("Unable to create an Internet Config instance: " + result);
524 openURLm.invoke(null, new Object[] { url });
525 } catch (InvocationTargetException ite) {
526 throw new IOException("InvocationTargetException while calling openURL: " + ite.getMessage());
527 } catch (IllegalAccessException iae) {
528 throw new IOException("IllegalAccessException while calling openURL: " + iae.getMessage());
533 // Add quotes around the URL to allow ampersands and other special
534 // characters to work.
535 Process process = Runtime.getRuntime().exec(new String[] { (String) browser,
536 FIRST_WINDOWS_PARAMETER,
537 SECOND_WINDOWS_PARAMETER,
538 THIRD_WINDOWS_PARAMETER,
540 // This avoids a memory leak on some versions of Java on Windows.
541 // That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
545 } catch (InterruptedException ie) {
546 throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
550 // Assume that we're on Unix and that Netscape is installed
552 // First, attempt to open the URL in a currently running session of Netscape
553 process = Runtime.getRuntime().exec(new String[] { (String) browser,
554 NETSCAPE_REMOTE_PARAMETER,
555 NETSCAPE_OPEN_PARAMETER_START +
557 NETSCAPE_OPEN_PARAMETER_END });
559 int exitCode = process.waitFor();
560 if (exitCode != 0) { // if Netscape was not open
561 Runtime.getRuntime().exec(new String[] { (String) browser, url });
563 } catch (InterruptedException ie) {
564 throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
568 // This should never occur, but if it does, we'll try the simplest thing possible
569 Runtime.getRuntime().exec(new String[] { (String) browser, url });
575 * Methods required for Mac OS X. The presence of native methods does not cause
576 * any problems on other platforms.
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);
584 private static int ICStart(int[] instance, int signature) { return 0; }
585 private static int ICStop(int[] instance) { return 0; }
586 private static int ICLaunchURL(int instance, byte[] hint, byte[] data, int len,
587 int[] selectionStart, int[] selectionEnd) { return 0; }