2 * 2004 Jalview Reengineered
12 import java.io.IOException;
13 import java.lang.reflect.Constructor;
14 import java.lang.reflect.Field;
15 import java.lang.reflect.InvocationTargetException;
16 import java.lang.reflect.Method;
19 * BrowserLauncher is a class that provides one static method, openURL, which opens the default
20 * web browser for the current user of the system to the given URL. It may support other
21 * protocols depending on the system -- mailto, ftp, etc. -- but that has not been rigorously
22 * tested and is not guaranteed to work.
24 * Yes, this is platform-specific code, and yes, it may rely on classes on certain platforms
25 * that are not part of the standard JDK. What we're trying to do, though, is to take something
26 * that's frequently desirable but inherently platform-specific -- opening a default browser --
27 * and allow programmers (you, for example) to do so without worrying about dropping into native
28 * code or doing anything else similarly evil.
30 * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant systems without
31 * modification or a need for additional libraries. All classes that are required on certain
32 * platforms to allow this to run are dynamically loaded at runtime via reflection and, if not
33 * found, will not cause this to do anything other than returning an error when opening the
36 * There are certain system requirements for this class, as it's running through Runtime.exec(),
37 * which is Java's way of making a native system call. Currently, this requires that a Macintosh
38 * have a Finder which supports the GURL event, which is true for Mac OS 8.0 and 8.1 systems that
39 * have the Internet Scripting AppleScript dictionary installed in the Scripting Additions folder
40 * in the Extensions folder (which is installed by default as far as I know under Mac OS 8.0 and
41 * 8.1), and for all Mac OS 8.5 and later systems. On Windows, it only runs under Win32 systems
42 * (Windows 95, 98, and NT 4.0, as well as later versions of all). On other systems, this drops
43 * back from the inherently platform-sensitive concept of a default browser and simply attempts
44 * to launch Netscape via a shell command.
46 * This code is Copyright 1999-2001 by Eric Albert (ejalbert@cs.stanford.edu) and may be
47 * redistributed or modified in any form without restrictions as long as the portion of this
48 * comment from this paragraph through the end of the comment is not removed. The author
49 * requests that he be notified of any application, applet, or other binary that makes use of
50 * this code, but that's more out of curiosity than anything and is not required. This software
51 * includes no warranty. The author is not repsonsible for any loss of data or functionality
52 * or any adverse or unexpected effects of using this software.
55 * <br>Steven Spencer, JavaWorld magazine (<a href="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java Tip 66</a>)
56 * <br>Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore,
57 * Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
59 * @author Eric Albert (<a href="mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu</a>)
60 * @version 1.4b1 (Released June 20, 2001)
62 public class BrowserLauncher {
65 * The Java virtual machine that we are running on. Actually, in most cases we only care
66 * about the operating system, but some operating systems require us to switch on the VM. */
67 private static int jvm;
69 /** The browser for the system */
70 private static Object browser;
73 * Caches whether any classes, methods, and fields that are not part of the JDK and need to
74 * be dynamically loaded at runtime loaded successfully.
76 * Note that if this is <code>false</code>, <code>openURL()</code> will always return an
79 private static boolean loadedWithoutErrors;
81 /** The com.apple.mrj.MRJFileUtils class */
82 private static Class mrjFileUtilsClass;
84 /** The com.apple.mrj.MRJOSType class */
85 private static Class mrjOSTypeClass;
87 /** The com.apple.MacOS.AEDesc class */
88 private static Class aeDescClass;
90 /** The <init>(int) method of com.apple.MacOS.AETarget */
91 private static Constructor aeTargetConstructor;
93 /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
94 private static Constructor appleEventConstructor;
96 /** The <init>(String) method of com.apple.MacOS.AEDesc */
97 private static Constructor aeDescConstructor;
99 /** The findFolder method of com.apple.mrj.MRJFileUtils */
100 private static Method findFolder;
102 /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
103 private static Method getFileCreator;
105 /** The getFileType method of com.apple.mrj.MRJFileUtils */
106 private static Method getFileType;
108 /** The openURL method of com.apple.mrj.MRJFileUtils */
109 private static Method openURL;
111 /** The makeOSType method of com.apple.MacOS.OSUtils */
112 private static Method makeOSType;
114 /** The putParameter method of com.apple.MacOS.AppleEvent */
115 private static Method putParameter;
117 /** The sendNoReply method of com.apple.MacOS.AppleEvent */
118 private static Method sendNoReply;
120 /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
121 private static Object kSystemFolderType;
123 /** The keyDirectObject AppleEvent parameter type */
124 private static Integer keyDirectObject;
126 /** The kAutoGenerateReturnID AppleEvent code */
127 private static Integer kAutoGenerateReturnID;
129 /** The kAnyTransactionID AppleEvent code */
130 private static Integer kAnyTransactionID;
132 /** The linkage object required for JDirect 3 on Mac OS X. */
133 private static Object linkage;
135 /** The framework to reference on Mac OS X */
136 private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox";
138 /** JVM constant for MRJ 2.0 */
139 private static final int MRJ_2_0 = 0;
141 /** JVM constant for MRJ 2.1 or later */
142 private static final int MRJ_2_1 = 1;
144 /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
145 private static final int MRJ_3_0 = 3;
147 /** JVM constant for MRJ 3.1 */
148 private static final int MRJ_3_1 = 4;
150 /** JVM constant for any Windows NT JVM */
151 private static final int WINDOWS_NT = 5;
153 /** JVM constant for any Windows 9x JVM */
154 private static final int WINDOWS_9x = 6;
156 /** JVM constant for any other platform */
157 private static final int OTHER = -1;
160 * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep non-U.S. English
161 * systems from working properly.
163 private static final String FINDER_TYPE = "FNDR";
166 * The creator code of the Finder on a Macintosh, which is needed to send AppleEvents to the
169 private static final String FINDER_CREATOR = "MACS";
171 /** The name for the AppleEvent type corresponding to a GetURL event. */
172 private static final String GURL_EVENT = "GURL";
175 * The first parameter that needs to be passed into Runtime.exec() to open the default web
176 * browser on Windows.
178 private static final String FIRST_WINDOWS_PARAMETER = "/c";
180 /** The second parameter for Runtime.exec() on Windows. */
181 private static final String SECOND_WINDOWS_PARAMETER = "start";
184 * The third parameter for Runtime.exec() on Windows. This is a "title"
185 * parameter that the command line expects. Setting this parameter allows
186 * URLs containing spaces to work.
188 private static final String THIRD_WINDOWS_PARAMETER = "\"\"";
191 * The shell parameters for Netscape that opens a given URL in an already-open copy of Netscape
192 * on many command-line systems.
194 private static final String NETSCAPE_REMOTE_PARAMETER = "-remote";
195 private static final String NETSCAPE_OPEN_PARAMETER_START = "openURL(";
196 private static final String NETSCAPE_OPEN_PARAMETER_END = ")";
199 * The message from any exception thrown throughout the initialization process.
201 private static String errorMessage;
204 * An initialization block that determines the operating system and loads the necessary
208 loadedWithoutErrors = true;
209 String osName = System.getProperty("os.name");
210 if (osName.startsWith("Mac OS")) {
211 String mrjVersion = System.getProperty("mrj.version");
212 String majorMRJVersion = mrjVersion.substring(0, 3);
214 double version = Double.valueOf(majorMRJVersion).doubleValue();
217 } else if (version >= 2.1 && version < 3) {
218 // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
219 // works via Runtime.exec() and 2.2 supports that but has an openURL() method
220 // as well that we currently ignore.
222 } else if (version == 3.0) {
224 } else if (version >= 3.1) {
225 // Assume that all 3.1 and later versions of MRJ work the same.
228 loadedWithoutErrors = false;
229 errorMessage = "Unsupported MRJ version: " + version;
231 } catch (NumberFormatException nfe) {
232 loadedWithoutErrors = false;
233 errorMessage = "Invalid MRJ version: " + mrjVersion;
235 } else if (osName.startsWith("Windows")) {
236 if (osName.indexOf("9") != -1) {
245 if (loadedWithoutErrors) { // if we haven't hit any errors yet
246 loadedWithoutErrors = loadClasses();
251 * This class should be never be instantiated; this just ensures so.
253 private BrowserLauncher() { }
256 * Called by a static initializer to load any classes, fields, and methods required at runtime
257 * to locate the user's web browser.
258 * @return <code>true</code> if all intialization succeeded
259 * <code>false</code> if any portion of the initialization failed
261 private static boolean loadClasses() {
265 Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
266 Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
267 Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
268 Class aeClass = Class.forName("com.apple.MacOS.ae");
269 aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
271 aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class [] { int.class });
272 appleEventConstructor = appleEventClass.getDeclaredConstructor(new Class[] { int.class, int.class, aeTargetClass, int.class, int.class });
273 aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[] { String.class });
275 makeOSType = osUtilsClass.getDeclaredMethod("makeOSType", new Class [] { String.class });
276 putParameter = appleEventClass.getDeclaredMethod("putParameter", new Class[] { int.class, aeDescClass });
277 sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply", new Class[] { });
279 Field keyDirectObjectField = aeClass.getDeclaredField("keyDirectObject");
280 keyDirectObject = (Integer) keyDirectObjectField.get(null);
281 Field autoGenerateReturnIDField = appleEventClass.getDeclaredField("kAutoGenerateReturnID");
282 kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField.get(null);
283 Field anyTransactionIDField = appleEventClass.getDeclaredField("kAnyTransactionID");
284 kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
285 } catch (ClassNotFoundException cnfe) {
286 errorMessage = cnfe.getMessage();
288 } catch (NoSuchMethodException nsme) {
289 errorMessage = nsme.getMessage();
291 } catch (NoSuchFieldException nsfe) {
292 errorMessage = nsfe.getMessage();
294 } catch (IllegalAccessException iae) {
295 errorMessage = iae.getMessage();
301 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
302 mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
303 Field systemFolderField = mrjFileUtilsClass.getDeclaredField("kSystemFolderType");
304 kSystemFolderType = systemFolderField.get(null);
305 findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder", new Class[] { mrjOSTypeClass });
306 getFileCreator = mrjFileUtilsClass.getDeclaredMethod("getFileCreator", new Class[] { File.class });
307 getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType", new Class[] { File.class });
308 } catch (ClassNotFoundException cnfe) {
309 errorMessage = cnfe.getMessage();
311 } catch (NoSuchFieldException nsfe) {
312 errorMessage = nsfe.getMessage();
314 } catch (NoSuchMethodException nsme) {
315 errorMessage = nsme.getMessage();
317 } catch (SecurityException se) {
318 errorMessage = se.getMessage();
320 } catch (IllegalAccessException iae) {
321 errorMessage = iae.getMessage();
327 Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
328 Constructor constructor = linker.getConstructor(new Class[]{ Class.class });
329 linkage = constructor.newInstance(new Object[] { BrowserLauncher.class });
330 } catch (ClassNotFoundException cnfe) {
331 errorMessage = cnfe.getMessage();
333 } catch (NoSuchMethodException nsme) {
334 errorMessage = nsme.getMessage();
336 } catch (InvocationTargetException ite) {
337 errorMessage = ite.getMessage();
339 } catch (InstantiationException ie) {
340 errorMessage = ie.getMessage();
342 } catch (IllegalAccessException iae) {
343 errorMessage = iae.getMessage();
349 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
350 openURL = mrjFileUtilsClass.getDeclaredMethod("openURL", new Class[] { String.class });
351 } catch (ClassNotFoundException cnfe) {
352 errorMessage = cnfe.getMessage();
354 } catch (NoSuchMethodException nsme) {
355 errorMessage = nsme.getMessage();
366 * Attempts to locate the default web browser on the local system. Caches results so it
367 * only locates the browser once for each use of this class per JVM instance.
368 * @return The browser for the system. Note that this may not be what you would consider
369 * to be a standard web browser; instead, it's the application that gets called to
370 * open the default web browser. In some cases, this will be a non-String object
371 * that provides the means of calling the default browser.
373 private static Object locateBrowser() {
374 if (browser != null) {
380 Integer finderCreatorCode = (Integer) makeOSType.invoke(null, new Object[] { FINDER_CREATOR });
381 Object aeTarget = aeTargetConstructor.newInstance(new Object[] { finderCreatorCode });
382 Integer gurlType = (Integer) makeOSType.invoke(null, new Object[] { GURL_EVENT });
383 Object appleEvent = appleEventConstructor.newInstance(new Object[] { gurlType, gurlType, aeTarget, kAutoGenerateReturnID, kAnyTransactionID });
384 // Don't set browser = appleEvent because then the next time we call
385 // locateBrowser(), we'll get the same AppleEvent, to which we'll already have
386 // added the relevant parameter. Instead, regenerate the AppleEvent every time.
387 // There's probably a way to do this better; if any has any ideas, please let
390 } catch (IllegalAccessException iae) {
392 errorMessage = iae.getMessage();
394 } catch (InstantiationException ie) {
396 errorMessage = ie.getMessage();
398 } catch (InvocationTargetException ite) {
400 errorMessage = ite.getMessage();
406 systemFolder = (File) findFolder.invoke(null, new Object[] { kSystemFolderType });
407 } catch (IllegalArgumentException iare) {
409 errorMessage = iare.getMessage();
411 } catch (IllegalAccessException iae) {
413 errorMessage = iae.getMessage();
415 } catch (InvocationTargetException ite) {
417 errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
420 String[] systemFolderFiles = systemFolder.list();
421 // Avoid a FilenameFilter because that can't be stopped mid-list
422 for(int i = 0; i < systemFolderFiles.length; i++) {
424 File file = new File(systemFolder, systemFolderFiles[i]);
425 if (!file.isFile()) {
428 // We're looking for a file with a creator code of 'MACS' and
429 // a type of 'FNDR'. Only requiring the type results in non-Finder
430 // applications being picked up on certain Mac OS 9 systems,
431 // especially German ones, and sending a GURL event to those
432 // applications results in a logout under Multiple Users.
433 Object fileType = getFileType.invoke(null, new Object[] { file });
434 if (FINDER_TYPE.equals(fileType.toString())) {
435 Object fileCreator = getFileCreator.invoke(null, new Object[] { file });
436 if (FINDER_CREATOR.equals(fileCreator.toString())) {
437 browser = file.toString(); // Actually the Finder, but that's OK
441 } catch (IllegalArgumentException iare) {
443 errorMessage = iare.getMessage();
445 } catch (IllegalAccessException iae) {
447 errorMessage = iae.getMessage();
449 } catch (InvocationTargetException ite) {
451 errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
459 browser = ""; // Return something non-null
465 browser = "command.com";
469 browser = "netscape";
476 * Attempts to open the default web browser to the given URL.
477 * @param url The URL to open
478 * @throws IOException If the web browser could not be located or does not run
480 public static void openURL(String url) throws IOException {
481 if (!loadedWithoutErrors) {
482 throw new IOException("Exception in finding browser: " + errorMessage);
484 Object browser = locateBrowser();
485 if (browser == null) {
486 throw new IOException("Unable to locate browser: " + errorMessage);
491 Object aeDesc = null;
493 aeDesc = aeDescConstructor.newInstance(new Object[] { url });
494 putParameter.invoke(browser, new Object[] { keyDirectObject, aeDesc });
495 sendNoReply.invoke(browser, new Object[] { });
496 } catch (InvocationTargetException ite) {
497 throw new IOException("InvocationTargetException while creating AEDesc: " + ite.getMessage());
498 } catch (IllegalAccessException iae) {
499 throw new IOException("IllegalAccessException while building AppleEvent: " + iae.getMessage());
500 } catch (InstantiationException ie) {
501 throw new IOException("InstantiationException while creating AEDesc: " + ie.getMessage());
503 aeDesc = null; // Encourage it to get disposed if it was created
504 browser = null; // Ditto
508 Runtime.getRuntime().exec(new String[] { (String) browser, url } );
511 int[] instance = new int[1];
512 int result = ICStart(instance, 0);
514 int[] selectionStart = new int[] { 0 };
515 byte[] urlBytes = url.getBytes();
516 int[] selectionEnd = new int[] { urlBytes.length };
517 result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes,
518 urlBytes.length, selectionStart,
521 // Ignore the return value; the URL was launched successfully
522 // regardless of what happens here.
525 throw new IOException("Unable to launch URL: " + result);
528 throw new IOException("Unable to create an Internet Config instance: " + result);
533 openURL.invoke(null, new Object[] { url });
534 } catch (InvocationTargetException ite) {
535 throw new IOException("InvocationTargetException while calling openURL: " + ite.getMessage());
536 } catch (IllegalAccessException iae) {
537 throw new IOException("IllegalAccessException while calling openURL: " + iae.getMessage());
542 // Add quotes around the URL to allow ampersands and other special
543 // characters to work.
544 Process process = Runtime.getRuntime().exec(new String[] { (String) browser,
545 FIRST_WINDOWS_PARAMETER,
546 SECOND_WINDOWS_PARAMETER,
547 THIRD_WINDOWS_PARAMETER,
549 // This avoids a memory leak on some versions of Java on Windows.
550 // That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
554 } catch (InterruptedException ie) {
555 throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
559 // Assume that we're on Unix and that Netscape is installed
561 // First, attempt to open the URL in a currently running session of Netscape
562 process = Runtime.getRuntime().exec(new String[] { (String) browser,
563 NETSCAPE_REMOTE_PARAMETER,
564 NETSCAPE_OPEN_PARAMETER_START +
566 NETSCAPE_OPEN_PARAMETER_END });
568 int exitCode = process.waitFor();
569 if (exitCode != 0) { // if Netscape was not open
570 Runtime.getRuntime().exec(new String[] { (String) browser, url });
572 } catch (InterruptedException ie) {
573 throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
577 // This should never occur, but if it does, we'll try the simplest thing possible
578 Runtime.getRuntime().exec(new String[] { (String) browser, url });
584 * Methods required for Mac OS X. The presence of native methods does not cause
585 * any problems on other platforms.
587 private native static int ICStart(int[] instance, int signature);
588 private native static int ICStop(int[] instance);
589 private native static int ICLaunchURL(int instance, byte[] hint, byte[] data, int len,
590 int[] selectionStart, int[] selectionEnd);