001 package de.mospace.lang;
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 Linux JVM */
149 private static final int LINUX = 7;
150
151 /** JVM constant for any other platform */
152 private static final int OTHER = -1;
153
154 /**
155 * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep non-U.S. English
156 * systems from working properly.
157 */
158 private static final String FINDER_TYPE = "FNDR";
159
160 /**
161 * The creator code of the Finder on a Macintosh, which is needed to send AppleEvents to the
162 * application.
163 */
164 private static final String FINDER_CREATOR = "MACS";
165
166 /** The name for the AppleEvent type corresponding to a GetURL event. */
167 private static final String GURL_EVENT = "GURL";
168
169 /**
170 * The first parameter that needs to be passed into Runtime.exec() to open the default web
171 * browser on Windows.
172 */
173 private static final String FIRST_WINDOWS_PARAMETER = "/c";
174
175 /** The second parameter for Runtime.exec() on Windows. */
176 private static final String SECOND_WINDOWS_PARAMETER = "start";
177
178 /**
179 * The third parameter for Runtime.exec() on Windows. This is a "title"
180 * parameter that the command line expects. Setting this parameter allows
181 * URLs containing spaces to work.
182 */
183 private static final String THIRD_WINDOWS_PARAMETER = "\"\"";
184
185 /**
186 * The shell parameters for Netscape that opens a given URL in an already-open copy of Netscape
187 * on many command-line systems.
188 */
189 private static final String NETSCAPE_REMOTE_PARAMETER = "-remote";
190 private static final String NETSCAPE_OPEN_PARAMETER_START = "'openURL(";
191 private static final String NETSCAPE_OPEN_PARAMETER_END = ")'";
192
193 /**
194 * The message from any exception thrown throughout the initialization process.
195 */
196 private static String errorMessage;
197
198 /**
199 * An initialization block that determines the operating system and loads the necessary
200 * runtime data.
201 */
202 static {
203 loadedWithoutErrors = true;
204 String osName = System.getProperty("os.name");
205 if (osName.startsWith("Mac OS")) {
206 String mrjVersion = System.getProperty("mrj.version");
207 String majorMRJVersion = mrjVersion.substring(0, 3);
208 try {
209 double version = Double.valueOf(majorMRJVersion).doubleValue();
210 if (version == 2) {
211 jvm = MRJ_2_0;
212 } else if (version >= 2.1 && version < 3) {
213 // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
214 // works via Runtime.exec() and 2.2 supports that but has an openURL() method
215 // as well that we currently ignore.
216 jvm = MRJ_2_1;
217 } else if (version == 3.0) {
218 jvm = MRJ_3_0;
219 } else if (version >= 3.1) {
220 // Assume that all 3.1 and later versions of MRJ work the same.
221 jvm = MRJ_3_1;
222 } else {
223 loadedWithoutErrors = false;
224 errorMessage = "Unsupported MRJ version: " + version;
225 }
226 } catch (NumberFormatException nfe) {
227 loadedWithoutErrors = false;
228 errorMessage = "Invalid MRJ version: " + mrjVersion;
229 }
230 } else if (osName.startsWith("Windows")) {
231 if (osName.indexOf("9") != -1) {
232 jvm = WINDOWS_9x;
233 } else {
234 jvm = WINDOWS_NT;
235 }
236 } else if (osName.startsWith("Linux")) {
237 jvm = LINUX;
238 }else {
239 jvm = OTHER;
240 }
241
242 if (loadedWithoutErrors) { // if we haven't hit any errors yet
243 loadedWithoutErrors = loadClasses();
244 }
245 }
246
247 /**
248 * This class should be never be instantiated; this just ensures so.
249 */
250 private BrowserLauncher() { }
251
252 /**
253 * Called by a static initializer to load any classes, fields, and methods required at runtime
254 * to locate the user's web browser.
255 * @return <code>true</code> if all intialization succeeded
256 * <code>false</code> if any portion of the initialization failed
257 */
258 private static boolean loadClasses() {
259 switch (jvm) {
260 case MRJ_2_0:
261 try {
262 Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
263 Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
264 Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
265 Class aeClass = Class.forName("com.apple.MacOS.ae");
266 aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
267
268 aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class [] { int.class });
269 appleEventConstructor = appleEventClass.getDeclaredConstructor(new Class[] { int.class, int.class, aeTargetClass, int.class, int.class });
270 aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[] { String.class });
271
272 makeOSType = osUtilsClass.getDeclaredMethod("makeOSType", new Class [] { String.class });
273 putParameter = appleEventClass.getDeclaredMethod("putParameter", new Class[] { int.class, aeDescClass });
274 sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply", new Class[] { });
275
276 Field keyDirectObjectField = aeClass.getDeclaredField("keyDirectObject");
277 keyDirectObject = (Integer) keyDirectObjectField.get(null);
278 Field autoGenerateReturnIDField = appleEventClass.getDeclaredField("kAutoGenerateReturnID");
279 kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField.get(null);
280 Field anyTransactionIDField = appleEventClass.getDeclaredField("kAnyTransactionID");
281 kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
282 } catch (ClassNotFoundException cnfe) {
283 errorMessage = cnfe.getMessage();
284 return false;
285 } catch (NoSuchMethodException nsme) {
286 errorMessage = nsme.getMessage();
287 return false;
288 } catch (NoSuchFieldException nsfe) {
289 errorMessage = nsfe.getMessage();
290 return false;
291 } catch (IllegalAccessException iae) {
292 errorMessage = iae.getMessage();
293 return false;
294 }
295 break;
296 case MRJ_2_1:
297 try {
298 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
299 mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
300 Field systemFolderField = mrjFileUtilsClass.getDeclaredField("kSystemFolderType");
301 kSystemFolderType = systemFolderField.get(null);
302 findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder", new Class[] { mrjOSTypeClass });
303 getFileCreator = mrjFileUtilsClass.getDeclaredMethod("getFileCreator", new Class[] { File.class });
304 getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType", new Class[] { File.class });
305 } catch (ClassNotFoundException cnfe) {
306 errorMessage = cnfe.getMessage();
307 return false;
308 } catch (NoSuchFieldException nsfe) {
309 errorMessage = nsfe.getMessage();
310 return false;
311 } catch (NoSuchMethodException nsme) {
312 errorMessage = nsme.getMessage();
313 return false;
314 } catch (SecurityException se) {
315 errorMessage = se.getMessage();
316 return false;
317 } catch (IllegalAccessException iae) {
318 errorMessage = iae.getMessage();
319 return false;
320 }
321 break;
322 case MRJ_3_0:
323 try {
324 Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
325 Constructor constructor = linker.getConstructor(new Class[]{ Class.class });
326 linkage = constructor.newInstance(new Object[] { BrowserLauncher.class });
327 } catch (ClassNotFoundException cnfe) {
328 errorMessage = cnfe.getMessage();
329 return false;
330 } catch (NoSuchMethodException nsme) {
331 errorMessage = nsme.getMessage();
332 return false;
333 } catch (InvocationTargetException ite) {
334 errorMessage = ite.getMessage();
335 return false;
336 } catch (InstantiationException ie) {
337 errorMessage = ie.getMessage();
338 return false;
339 } catch (IllegalAccessException iae) {
340 errorMessage = iae.getMessage();
341 return false;
342 }
343 break;
344 case MRJ_3_1:
345 try {
346 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
347 openURL = mrjFileUtilsClass.getDeclaredMethod("openURL", new Class[] { String.class });
348 } catch (ClassNotFoundException cnfe) {
349 errorMessage = cnfe.getMessage();
350 return false;
351 } catch (NoSuchMethodException nsme) {
352 errorMessage = nsme.getMessage();
353 return false;
354 }
355 break;
356 default:
357 break;
358 }
359 return true;
360 }
361
362 /**
363 * Attempts to locate the default web browser on the local system. Caches results so it
364 * only locates the browser once for each use of this class per JVM instance.
365 * @return The browser for the system. Note that this may not be what you would consider
366 * to be a standard web browser; instead, it's the application that gets called to
367 * open the default web browser. In some cases, this will be a non-String object
368 * that provides the means of calling the default browser.
369 */
370 private static Object locateBrowser() {
371 if (browser != null) {
372 return browser;
373 }
374 switch (jvm) {
375 case MRJ_2_0:
376 try {
377 Integer finderCreatorCode = (Integer) makeOSType.invoke(null, new Object[] { FINDER_CREATOR });
378 Object aeTarget = aeTargetConstructor.newInstance(new Object[] { finderCreatorCode });
379 Integer gurlType = (Integer) makeOSType.invoke(null, new Object[] { GURL_EVENT });
380 Object appleEvent = appleEventConstructor.newInstance(new Object[] { gurlType, gurlType, aeTarget, kAutoGenerateReturnID, kAnyTransactionID });
381 // Don't set browser = appleEvent because then the next time we call
382 // locateBrowser(), we'll get the same AppleEvent, to which we'll already have
383 // added the relevant parameter. Instead, regenerate the AppleEvent every time.
384 // There's probably a way to do this better; if any has any ideas, please let
385 // me know.
386 return appleEvent;
387 } catch (IllegalAccessException iae) {
388 browser = null;
389 errorMessage = iae.getMessage();
390 return browser;
391 } catch (InstantiationException ie) {
392 browser = null;
393 errorMessage = ie.getMessage();
394 return browser;
395 } catch (InvocationTargetException ite) {
396 browser = null;
397 errorMessage = ite.getMessage();
398 return browser;
399 }
400 case MRJ_2_1:
401 File systemFolder;
402 try {
403 systemFolder = (File) findFolder.invoke(null, new Object[] { kSystemFolderType });
404 } catch (IllegalArgumentException iare) {
405 browser = null;
406 errorMessage = iare.getMessage();
407 return browser;
408 } catch (IllegalAccessException iae) {
409 browser = null;
410 errorMessage = iae.getMessage();
411 return browser;
412 } catch (InvocationTargetException ite) {
413 browser = null;
414 errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
415 return browser;
416 }
417 String[] systemFolderFiles = systemFolder.list();
418 // Avoid a FilenameFilter because that can't be stopped mid-list
419 for(int i = 0; i < systemFolderFiles.length; i++) {
420 try {
421 File file = new File(systemFolder, systemFolderFiles[i]);
422 if (!file.isFile()) {
423 continue;
424 }
425 // We're looking for a file with a creator code of 'MACS' and
426 // a type of 'FNDR'. Only requiring the type results in non-Finder
427 // applications being picked up on certain Mac OS 9 systems,
428 // especially German ones, and sending a GURL event to those
429 // applications results in a logout under Multiple Users.
430 Object fileType = getFileType.invoke(null, new Object[] { file });
431 if (FINDER_TYPE.equals(fileType.toString())) {
432 Object fileCreator = getFileCreator.invoke(null, new Object[] { file });
433 if (FINDER_CREATOR.equals(fileCreator.toString())) {
434 browser = file.toString(); // Actually the Finder, but that's OK
435 return browser;
436 }
437 }
438 } catch (IllegalArgumentException iare) {
439 browser = browser;
440 errorMessage = iare.getMessage();
441 return null;
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() + ": " + ite.getTargetException().getMessage();
449 return browser;
450 }
451 }
452 browser = null;
453 break;
454 case MRJ_3_0:
455 case MRJ_3_1:
456 browser = ""; // Return something non-null
457 break;
458 case WINDOWS_NT:
459 browser = "cmd.exe";
460 break;
461 case WINDOWS_9x:
462 browser = "command.com";
463 break;
464 case LINUX:
465 if ((new File("/usr/bin/mozilla")).exists())
466 browser = "mozilla";
467 else if ((new File("/usr/bin/firefox")).exists())
468 browser = "firefox";
469 else
470 browser = "mozilla";
471 break;
472 case OTHER:
473 default:
474 browser = "netscape";
475 break;
476 }
477 return browser;
478 }
479
480 /**
481 * Attempts to open the default web browser to the given URL.
482 * @param url The URL to open
483 * @throws IOException If the web browser could not be located or does not run
484 */
485 public static void openURL(String url) throws IOException {
486 if (!loadedWithoutErrors) {
487 throw new IOException("Exception in finding browser: " + errorMessage);
488 }
489 Object browser = locateBrowser();
490 if (browser == null) {
491 throw new IOException("Unable to locate browser: " + errorMessage);
492 }
493
494 switch (jvm) {
495 case MRJ_2_0:
496 Object aeDesc = null;
497 try {
498 aeDesc = aeDescConstructor.newInstance(new Object[] { url });
499 putParameter.invoke(browser, new Object[] { keyDirectObject, aeDesc });
500 sendNoReply.invoke(browser, new Object[] { });
501 } catch (InvocationTargetException ite) {
502 throw new IOException("InvocationTargetException while creating AEDesc: " + ite.getMessage());
503 } catch (IllegalAccessException iae) {
504 throw new IOException("IllegalAccessException while building AppleEvent: " + iae.getMessage());
505 } catch (InstantiationException ie) {
506 throw new IOException("InstantiationException while creating AEDesc: " + ie.getMessage());
507 } finally {
508 aeDesc = null; // Encourage it to get disposed if it was created
509 browser = null; // Ditto
510 }
511 break;
512 case MRJ_2_1:
513 Runtime.getRuntime().exec(new String[] { (String) browser, url } );
514 break;
515 case MRJ_3_0:
516 int[] instance = new int[1];
517 int result = ICStart(instance, 0);
518 if (result == 0) {
519 int[] selectionStart = new int[] { 0 };
520 byte[] urlBytes = url.getBytes();
521 int[] selectionEnd = new int[] { urlBytes.length };
522 result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes,
523 urlBytes.length, selectionStart,
524 selectionEnd);
525 if (result == 0) {
526 // Ignore the return value; the URL was launched successfully
527 // regardless of what happens here.
528 ICStop(instance);
529 } else {
530 throw new IOException("Unable to launch URL: " + result);
531 }
532 } else {
533 throw new IOException("Unable to create an Internet Config instance: " + result);
534 }
535 break;
536 case MRJ_3_1:
537 try {
538 openURL.invoke(null, new Object[] { url });
539 } catch (InvocationTargetException ite) {
540 throw new IOException("InvocationTargetException while calling openURL: " + ite.getMessage());
541 } catch (IllegalAccessException iae) {
542 throw new IOException("IllegalAccessException while calling openURL: " + iae.getMessage());
543 }
544 break;
545 case WINDOWS_NT:
546 case WINDOWS_9x:
547 // Add quotes around the URL to allow ampersands and other special
548 // characters to work.
549 Process process = Runtime.getRuntime().exec(new String[] { (String) browser,
550 FIRST_WINDOWS_PARAMETER,
551 SECOND_WINDOWS_PARAMETER,
552 THIRD_WINDOWS_PARAMETER,
553 '"' + url + '"' });
554 // This avoids a memory leak on some versions of Java on Windows.
555 // That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
556 try {
557 process.waitFor();
558 process.exitValue();
559 } catch (InterruptedException ie) {
560 throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
561 }
562 break;
563 case OTHER:
564 // Assume that we're on Unix and that Netscape is installed
565
566 // First, attempt to open the URL in a currently running session of Netscape
567 process = Runtime.getRuntime().exec(new String[] { (String) browser,
568 NETSCAPE_REMOTE_PARAMETER,
569 NETSCAPE_OPEN_PARAMETER_START +
570 url +
571 NETSCAPE_OPEN_PARAMETER_END });
572 try {
573 int exitCode = process.waitFor();
574 if (exitCode != 0) { // if Netscape was not open
575 Runtime.getRuntime().exec(new String[] { (String) browser, url });
576 }
577 } catch (InterruptedException ie) {
578 throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
579 }
580 break;
581 default:
582 // This should never occur, but if it does, we'll try the simplest thing possible
583 Runtime.getRuntime().exec(new String[] { (String) browser, url });
584 break;
585 }
586 }
587
588 /**
589 * Methods required for Mac OS X. The presence of native methods does not cause
590 * any problems on other platforms.
591 */
592 private native static int ICStart(int[] instance, int signature);
593 private native static int ICStop(int[] instance);
594 private native static int ICLaunchURL(int instance, byte[] hint, byte[] data, int len,
595 int[] selectionStart, int[] selectionEnd);
596 }