001: package workbench.util;
002:
003: import java.io.File;
004: import java.io.IOException;
005: import java.lang.reflect.Constructor;
006: import java.lang.reflect.Field;
007: import java.lang.reflect.InvocationTargetException;
008: import java.lang.reflect.Method;
009:
010: /**
011: * BrowserLauncher is a class that provides one static method, openURL, which opens the default
012: * web browser for the current user of the system to the given URL. It may support other
013: * protocols depending on the system -- mailto, ftp, etc. -- but that has not been rigorously
014: * tested and is not guaranteed to work.
015: * <p>
016: * Yes, this is platform-specific code, and yes, it may rely on classes on certain platforms
017: * that are not part of the standard JDK. What we're trying to do, though, is to take something
018: * that's frequently desirable but inherently platform-specific -- opening a default browser --
019: * and allow programmers (you, for example) to do so without worrying about dropping into native
020: * code or doing anything else similarly evil.
021: * <p>
022: * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant systems without
023: * modification or a need for additional libraries. All classes that are required on certain
024: * platforms to allow this to run are dynamically loaded at runtime via reflection and, if not
025: * found, will not cause this to do anything other than returning an error when opening the
026: * browser.
027: * <p>
028: * There are certain system requirements for this class, as it's running through Runtime.exec(),
029: * which is Java's way of making a native system call. Currently, this requires that a Macintosh
030: * have a Finder which supports the GURL event, which is true for Mac OS 8.0 and 8.1 systems that
031: * have the Internet Scripting AppleScript dictionary installed in the Scripting Additions folder
032: * in the Extensions folder (which is installed by default as far as I know under Mac OS 8.0 and
033: * 8.1), and for all Mac OS 8.5 and later systems. On Windows, it only runs under Win32 systems
034: * (Windows 95, 98, and NT 4.0, as well as later versions of all). On other systems, this drops
035: * back from the inherently platform-sensitive concept of a default browser and simply attempts
036: * to launch Netscape via a shell command.
037: * <p>
038: * This code is Copyright 1999-2001 by Eric Albert (ejalbert@cs.stanford.edu) and may be
039: * redistributed or modified in any form without restrictions as long as the portion of this
040: * comment from this paragraph through the end of the comment is not removed. The author
041: * requests that he be notified of any application, applet, or other binary that makes use of
042: * this code, but that's more out of curiosity than anything and is not required. This software
043: * includes no warranty. The author is not repsonsible for any loss of data or functionality
044: * or any adverse or unexpected effects of using this software.
045: * <p>
046: * Credits:
047: * <br>Steven Spencer, JavaWorld magazine (<a href="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java Tip 66</a>)
048: * <br>Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore,
049: * Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
050: *
051: * @author Eric Albert (<a href="mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu</a>)
052: * @version 1.4b1 (Released June 20, 2001)
053: */
054: public class BrowserLauncher {
055:
056: /**
057: * The Java virtual machine that we are running on. Actually, in most cases we only care
058: * about the operating system, but some operating systems require us to switch on the VM. */
059: private static int jvm;
060:
061: /** The browser for the system */
062: private static Object browser;
063:
064: /**
065: * Caches whether any classes, methods, and fields that are not part of the JDK and need to
066: * be dynamically loaded at runtime loaded successfully.
067: * <p>
068: * Note that if this is <code>false</code>, <code>openURL()</code> will always return an
069: * IOException.
070: */
071: private static boolean loadedWithoutErrors;
072:
073: /** The com.apple.mrj.MRJFileUtils class */
074: private static Class mrjFileUtilsClass;
075:
076: /** The com.apple.mrj.MRJOSType class */
077: private static Class mrjOSTypeClass;
078:
079: /** The com.apple.MacOS.AEDesc class */
080: private static Class aeDescClass;
081:
082: /** The <init>(int) method of com.apple.MacOS.AETarget */
083: private static Constructor aeTargetConstructor;
084:
085: /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
086: private static Constructor appleEventConstructor;
087:
088: /** The <init>(String) method of com.apple.MacOS.AEDesc */
089: private static Constructor aeDescConstructor;
090:
091: /** The findFolder method of com.apple.mrj.MRJFileUtils */
092: private static Method findFolder;
093:
094: /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
095: private static Method getFileCreator;
096:
097: /** The getFileType method of com.apple.mrj.MRJFileUtils */
098: private static Method getFileType;
099:
100: /** The openURL method of com.apple.mrj.MRJFileUtils */
101: private static Method openURL;
102:
103: /** The makeOSType method of com.apple.MacOS.OSUtils */
104: private static Method makeOSType;
105:
106: /** The putParameter method of com.apple.MacOS.AppleEvent */
107: private static Method putParameter;
108:
109: /** The sendNoReply method of com.apple.MacOS.AppleEvent */
110: private static Method sendNoReply;
111:
112: /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
113: private static Object kSystemFolderType;
114:
115: /** The keyDirectObject AppleEvent parameter type */
116: private static Integer keyDirectObject;
117:
118: /** The kAutoGenerateReturnID AppleEvent code */
119: private static Integer kAutoGenerateReturnID;
120:
121: /** The kAnyTransactionID AppleEvent code */
122: private static Integer kAnyTransactionID;
123:
124: /** The linkage object required for JDirect 3 on Mac OS X. */
125: private static Object linkage;
126:
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";
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 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 FINDER_CREATOR = "MACS";
162:
163: /** The name for the AppleEvent type corresponding to a GetURL event. */
164: private static final String 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 FIRST_WINDOWS_PARAMETER = "/c";
171:
172: /** The second parameter for Runtime.exec() on Windows. */
173: private static final String 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 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 NETSCAPE_REMOTE_PARAMETER = "-remote";
187: private static final String NETSCAPE_OPEN_PARAMETER_START = "'openURL(";
188: private static final String NETSCAPE_OPEN_PARAMETER_END = ")'";
189:
190: /**
191: * The message from any exception thrown throughout the initialization process.
192: */
193: private static String 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 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);
205: try {
206: double version = Double.valueOf(majorMRJVersion)
207: .doubleValue();
208: if (version == 2) {
209: jvm = MRJ_2_0;
210: } else if (version >= 2.1 && version < 3) {
211: // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
212: // works via Runtime.exec() and 2.2 supports that but has an openURL() method
213: // as well that we currently ignore.
214: jvm = MRJ_2_1;
215: } else if (version == 3.0) {
216: jvm = MRJ_3_0;
217: } else if (version >= 3.1) {
218: // Assume that all 3.1 and later versions of MRJ work the same.
219: jvm = MRJ_3_1;
220: } else {
221: loadedWithoutErrors = false;
222: errorMessage = "Unsupported MRJ version: "
223: + version;
224: }
225: } catch (NumberFormatException 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 {
236: jvm = OTHER;
237: }
238:
239: if (loadedWithoutErrors) { // if we haven't hit any errors yet
240: loadedWithoutErrors = loadClasses();
241: }
242: }
243:
244: /**
245: * This class should be never be instantiated; this just ensures so.
246: */
247: private BrowserLauncher() {
248: }
249:
250: /**
251: * Called by a static initializer to load any classes, fields, and methods required at runtime
252: * to locate the user's web browser.
253: * @return <code>true</code> if all intialization succeeded
254: * <code>false</code> if any portion of the initialization failed
255: */
256: private static boolean loadClasses() {
257: switch (jvm) {
258: case MRJ_2_0:
259: try {
260: Class aeTargetClass = Class
261: .forName("com.apple.MacOS.AETarget");
262: Class osUtilsClass = Class
263: .forName("com.apple.MacOS.OSUtils");
264: Class appleEventClass = Class
265: .forName("com.apple.MacOS.AppleEvent");
266: Class aeClass = Class.forName("com.apple.MacOS.ae");
267: aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
268:
269: aeTargetConstructor = aeTargetClass
270: .getDeclaredConstructor(new Class[] { int.class });
271: appleEventConstructor = appleEventClass
272: .getDeclaredConstructor(new Class[] {
273: int.class, int.class, aeTargetClass,
274: int.class, int.class });
275: aeDescConstructor = aeDescClass
276: .getDeclaredConstructor(new Class[] { String.class });
277:
278: makeOSType = osUtilsClass.getDeclaredMethod(
279: "makeOSType", new Class[] { String.class });
280: putParameter = appleEventClass.getDeclaredMethod(
281: "putParameter", new Class[] { int.class,
282: aeDescClass });
283: sendNoReply = appleEventClass.getDeclaredMethod(
284: "sendNoReply", new Class[] {});
285:
286: Field keyDirectObjectField = aeClass
287: .getDeclaredField("keyDirectObject");
288: keyDirectObject = (Integer) keyDirectObjectField
289: .get(null);
290: Field autoGenerateReturnIDField = appleEventClass
291: .getDeclaredField("kAutoGenerateReturnID");
292: kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField
293: .get(null);
294: Field anyTransactionIDField = appleEventClass
295: .getDeclaredField("kAnyTransactionID");
296: kAnyTransactionID = (Integer) anyTransactionIDField
297: .get(null);
298: } catch (ClassNotFoundException cnfe) {
299: errorMessage = cnfe.getMessage();
300: return false;
301: } catch (NoSuchMethodException nsme) {
302: errorMessage = nsme.getMessage();
303: return false;
304: } catch (NoSuchFieldException nsfe) {
305: errorMessage = nsfe.getMessage();
306: return false;
307: } catch (IllegalAccessException iae) {
308: errorMessage = iae.getMessage();
309: return false;
310: }
311: break;
312: case MRJ_2_1:
313: try {
314: mrjFileUtilsClass = Class
315: .forName("com.apple.mrj.MRJFileUtils");
316: mrjOSTypeClass = Class
317: .forName("com.apple.mrj.MRJOSType");
318: Field systemFolderField = mrjFileUtilsClass
319: .getDeclaredField("kSystemFolderType");
320: kSystemFolderType = systemFolderField.get(null);
321: findFolder = mrjFileUtilsClass.getDeclaredMethod(
322: "findFolder", new Class[] { mrjOSTypeClass });
323: getFileCreator = mrjFileUtilsClass.getDeclaredMethod(
324: "getFileCreator", new Class[] { File.class });
325: getFileType = mrjFileUtilsClass.getDeclaredMethod(
326: "getFileType", new Class[] { File.class });
327: } catch (ClassNotFoundException cnfe) {
328: errorMessage = cnfe.getMessage();
329: return false;
330: } catch (NoSuchFieldException nsfe) {
331: errorMessage = nsfe.getMessage();
332: return false;
333: } catch (NoSuchMethodException nsme) {
334: errorMessage = nsme.getMessage();
335: return false;
336: } catch (SecurityException se) {
337: errorMessage = se.getMessage();
338: return false;
339: } catch (IllegalAccessException iae) {
340: errorMessage = iae.getMessage();
341: return false;
342: }
343: break;
344: case MRJ_3_0:
345: try {
346: Class linker = Class
347: .forName("com.apple.mrj.jdirect.Linker");
348: Constructor constructor = linker
349: .getConstructor(new Class[] { Class.class });
350: linkage = constructor
351: .newInstance(new Object[] { BrowserLauncher.class });
352: } catch (ClassNotFoundException cnfe) {
353: errorMessage = cnfe.getMessage();
354: return false;
355: } catch (NoSuchMethodException nsme) {
356: errorMessage = nsme.getMessage();
357: return false;
358: } catch (InvocationTargetException ite) {
359: errorMessage = ite.getMessage();
360: return false;
361: } catch (InstantiationException ie) {
362: errorMessage = ie.getMessage();
363: return false;
364: } catch (IllegalAccessException iae) {
365: errorMessage = iae.getMessage();
366: return false;
367: }
368: break;
369: case MRJ_3_1:
370: try {
371: mrjFileUtilsClass = Class
372: .forName("com.apple.mrj.MRJFileUtils");
373: openURL = mrjFileUtilsClass.getDeclaredMethod(
374: "openURL", new Class[] { String.class });
375: } catch (ClassNotFoundException cnfe) {
376: errorMessage = cnfe.getMessage();
377: return false;
378: } catch (NoSuchMethodException nsme) {
379: errorMessage = nsme.getMessage();
380: return false;
381: }
382: break;
383: default:
384: break;
385: }
386: return true;
387: }
388:
389: /**
390: * Attempts to locate the default web browser on the local system. Caches results so it
391: * only locates the browser once for each use of this class per JVM instance.
392: * @return The browser for the system. Note that this may not be what you would consider
393: * to be a standard web browser; instead, it's the application that gets called to
394: * open the default web browser. In some cases, this will be a non-String object
395: * that provides the means of calling the default browser.
396: */
397: private static Object locateBrowser() {
398: if (browser != null) {
399: return browser;
400: }
401: switch (jvm) {
402: case MRJ_2_0:
403: try {
404: Integer finderCreatorCode = (Integer) makeOSType
405: .invoke(null, new Object[] { FINDER_CREATOR });
406: Object aeTarget = aeTargetConstructor
407: .newInstance(new Object[] { finderCreatorCode });
408: Integer gurlType = (Integer) makeOSType.invoke(null,
409: new Object[] { GURL_EVENT });
410: Object appleEvent = appleEventConstructor
411: .newInstance(new Object[] { gurlType, gurlType,
412: aeTarget, kAutoGenerateReturnID,
413: kAnyTransactionID });
414: // Don't set browser = appleEvent because then the next time we call
415: // locateBrowser(), we'll get the same AppleEvent, to which we'll already have
416: // added the relevant parameter. Instead, regenerate the AppleEvent every time.
417: // There's probably a way to do this better; if any has any ideas, please let
418: // me know.
419: return appleEvent;
420: } catch (IllegalAccessException iae) {
421: browser = null;
422: errorMessage = iae.getMessage();
423: return browser;
424: } catch (InstantiationException ie) {
425: browser = null;
426: errorMessage = ie.getMessage();
427: return browser;
428: } catch (InvocationTargetException ite) {
429: browser = null;
430: errorMessage = ite.getMessage();
431: return browser;
432: }
433: case MRJ_2_1:
434: File systemFolder;
435: try {
436: systemFolder = (File) findFolder.invoke(null,
437: new Object[] { kSystemFolderType });
438: } catch (IllegalArgumentException iare) {
439: browser = null;
440: errorMessage = iare.getMessage();
441: return browser;
442: } catch (IllegalAccessException iae) {
443: browser = null;
444: errorMessage = iae.getMessage();
445: return browser;
446: } catch (InvocationTargetException ite) {
447: browser = null;
448: errorMessage = ite.getTargetException().getClass()
449: + ": " + ite.getTargetException().getMessage();
450: return browser;
451: }
452: String[] systemFolderFiles = systemFolder.list();
453: // Avoid a FilenameFilter because that can't be stopped mid-list
454: for (int i = 0; i < systemFolderFiles.length; i++) {
455: try {
456: File file = new File(systemFolder,
457: systemFolderFiles[i]);
458: if (!file.isFile()) {
459: continue;
460: }
461: // We're looking for a file with a creator code of 'MACS' and
462: // a type of 'FNDR'. Only requiring the type results in non-Finder
463: // applications being picked up on certain Mac OS 9 systems,
464: // especially German ones, and sending a GURL event to those
465: // applications results in a logout under Multiple Users.
466: Object fileType = getFileType.invoke(null,
467: new Object[] { file });
468: if (FINDER_TYPE.equals(fileType.toString())) {
469: Object fileCreator = getFileCreator.invoke(
470: null, new Object[] { file });
471: if (FINDER_CREATOR.equals(fileCreator
472: .toString())) {
473: browser = file.toString(); // Actually the Finder, but that's OK
474: return browser;
475: }
476: }
477: } catch (IllegalArgumentException iare) {
478: errorMessage = iare.getMessage();
479: return null;
480: } catch (IllegalAccessException iae) {
481: browser = null;
482: errorMessage = iae.getMessage();
483: return browser;
484: } catch (InvocationTargetException ite) {
485: browser = null;
486: errorMessage = ite.getTargetException().getClass()
487: + ": "
488: + ite.getTargetException().getMessage();
489: return browser;
490: }
491: }
492: browser = null;
493: break;
494: case MRJ_3_0:
495: case MRJ_3_1:
496: browser = ""; // Return something non-null
497: break;
498: case WINDOWS_NT:
499: browser = "cmd.exe";
500: break;
501: case WINDOWS_9x:
502: browser = "command.com";
503: break;
504: case OTHER:
505: default:
506: browser = "netscape";
507: break;
508: }
509: return browser;
510: }
511:
512: /**
513: * Attempts to open the default web browser to the given URL.
514: * @param url The URL to open
515: * @throws IOException If the web browser could not be located or does not run
516: */
517: public static void openURL(String url) throws IOException {
518: if (!loadedWithoutErrors) {
519: throw new IOException("Exception in finding browser: "
520: + errorMessage);
521: }
522: Object theBrowser = locateBrowser();
523: if (theBrowser == null) {
524: throw new IOException("Unable to locate browser: "
525: + errorMessage);
526: }
527:
528: switch (jvm) {
529: case MRJ_2_0:
530: Object aeDesc = null;
531: try {
532: aeDesc = aeDescConstructor
533: .newInstance(new Object[] { url });
534: putParameter.invoke(theBrowser, new Object[] {
535: keyDirectObject, aeDesc });
536: sendNoReply.invoke(theBrowser, new Object[] {});
537: } catch (InvocationTargetException ite) {
538: throw new IOException(
539: "InvocationTargetException while creating AEDesc: "
540: + ite.getMessage());
541: } catch (IllegalAccessException iae) {
542: throw new IOException(
543: "IllegalAccessException while building AppleEvent: "
544: + iae.getMessage());
545: } catch (InstantiationException ie) {
546: throw new IOException(
547: "InstantiationException while creating AEDesc: "
548: + ie.getMessage());
549: } finally {
550: aeDesc = null; // Encourage it to get disposed if it was created
551: browser = null; // Ditto
552: }
553: break;
554: case MRJ_2_1:
555: Runtime.getRuntime().exec(
556: new String[] { (String) browser, url });
557: break;
558: case MRJ_3_0:
559: int[] instance = new int[1];
560: int result = ICStart(instance, 0);
561: if (result == 0) {
562: int[] selectionStart = new int[] { 0 };
563: byte[] urlBytes = url.getBytes();
564: int[] selectionEnd = new int[] { urlBytes.length };
565: result = ICLaunchURL(instance[0], new byte[] { 0 },
566: urlBytes, urlBytes.length, selectionStart,
567: selectionEnd);
568: if (result == 0) {
569: // Ignore the return value; the URL was launched successfully
570: // regardless of what happens here.
571: ICStop(instance);
572: } else {
573: throw new IOException("Unable to launch URL: "
574: + result);
575: }
576: } else {
577: throw new IOException(
578: "Unable to create an Internet Config instance: "
579: + result);
580: }
581: break;
582: case MRJ_3_1:
583: try {
584: openURL.invoke(null, new Object[] { url });
585: } catch (InvocationTargetException ite) {
586: throw new IOException(
587: "InvocationTargetException while calling openURL: "
588: + ite.getMessage());
589: } catch (IllegalAccessException iae) {
590: throw new IOException(
591: "IllegalAccessException while calling openURL: "
592: + iae.getMessage());
593: }
594: break;
595: case WINDOWS_NT:
596: case WINDOWS_9x:
597: // Add quotes around the URL to allow ampersands and other special
598: // characters to work.
599: Process process = Runtime.getRuntime().exec(
600: new String[] { (String) theBrowser,
601: FIRST_WINDOWS_PARAMETER,
602: SECOND_WINDOWS_PARAMETER,
603: THIRD_WINDOWS_PARAMETER, '"' + url + '"' });
604: // This avoids a memory leak on some versions of Java on Windows.
605: // That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
606: try {
607: process.waitFor();
608: process.exitValue();
609: } catch (InterruptedException ie) {
610: throw new IOException(
611: "InterruptedException while launching browser: "
612: + ie.getMessage());
613: }
614: break;
615: case OTHER:
616: // Assume that we're on Unix and that Netscape is installed
617:
618: // First, attempt to open the URL in a currently running session of Netscape
619: process = Runtime.getRuntime().exec(
620: new String[] {
621: (String) theBrowser,
622: NETSCAPE_REMOTE_PARAMETER,
623: NETSCAPE_OPEN_PARAMETER_START + url
624: + NETSCAPE_OPEN_PARAMETER_END });
625: try {
626: int exitCode = process.waitFor();
627: if (exitCode != 0) { // if Netscape was not open
628: Runtime.getRuntime().exec(
629: new String[] { (String) theBrowser, url });
630: }
631: } catch (InterruptedException ie) {
632: throw new IOException(
633: "InterruptedException while launching browser: "
634: + ie.getMessage());
635: }
636: break;
637: default:
638: // This should never occur, but if it does, we'll try the simplest thing possible
639: Runtime.getRuntime().exec(
640: new String[] { (String) theBrowser, url });
641: break;
642: }
643: }
644:
645: /**
646: * Methods required for Mac OS X. The presence of native methods does not cause
647: * any problems on other platforms.
648: */
649: private native static int ICStart(int[] instance, int signature);
650:
651: private native static int ICStop(int[] instance);
652:
653: private native static int ICLaunchURL(int instance, byte[] hint,
654: byte[] data, int len, int[] selectionStart,
655: int[] selectionEnd);
656: }
|