PageRenderTime 42ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/src/e/util/BrowserLauncher.java

https://github.com/orph/jujitsu
Java | 507 lines | 308 code | 45 blank | 154 comment | 39 complexity | a88963f48e5f254c632a9be5abb26326 MD5 | raw file
Possible License(s): GPL-2.0
  1. package e.util;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.lang.reflect.Constructor;
  5. import java.lang.reflect.InvocationTargetException;
  6. import java.lang.reflect.Method;
  7. /**
  8. * BrowserLauncher is a class that provides one static method, openURL, which opens the default
  9. * web browser for the current user of the system to the given URL. It may support other
  10. * protocols depending on the system -- mailto, ftp, etc. -- but that has not been rigorously
  11. * tested and is not guaranteed to work.
  12. * <p>
  13. * Yes, this is platform-specific code, and yes, it may rely on classes on certain platforms
  14. * that are not part of the standard JDK. What we're trying to do, though, is to take something
  15. * that's frequently desirable but inherently platform-specific -- opening a default browser --
  16. * and allow programmers (you, for example) to do so without worrying about dropping into native
  17. * code or doing anything else similarly evil.
  18. * <p>
  19. * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant systems without
  20. * modification or a need for additional libraries. All classes that are required on certain
  21. * platforms to allow this to run are dynamically loaded at runtime via reflection and, if not
  22. * found, will not cause this to do anything other than returning an error when opening the
  23. * browser.
  24. * <p>
  25. * There are certain system requirements for this class, as it's running through Runtime.exec(),
  26. * which is Java's way of making a native system call. Currently, this requires that a Macintosh
  27. * have a Finder which supports the GURL event, which is true for Mac OS 8.0 and 8.1 systems that
  28. * have the Internet Scripting AppleScript dictionary installed in the Scripting Additions folder
  29. * in the Extensions folder (which is installed by default as far as I know under Mac OS 8.0 and
  30. * 8.1), and for all Mac OS 8.5 and later systems. On Windows, it only runs under Win32 systems
  31. * (Windows 95, 98, and NT 4.0, as well as later versions of all). On other systems, we assume
  32. * the /usr/bin/sensible-browser command is available.
  33. * <p>
  34. * This code is Copyright 1999-2001 by Eric Albert (ejalbert@cs.stanford.edu) and may be
  35. * redistributed or modified in any form without restrictions as long as the portion of this
  36. * comment from this paragraph through the end of the comment is not removed. The author
  37. * requests that he be notified of any application, applet, or other binary that makes use of
  38. * this code, but that's more out of curiosity than anything and is not required. This software
  39. * includes no warranty. The author is not repsonsible for any loss of data or functionality
  40. * or any adverse or unexpected effects of using this software.
  41. * <p>
  42. * Credits:
  43. * <br>Steven Spencer, JavaWorld magazine (<a href="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java Tip 66</a>)
  44. * <br>Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore,
  45. * Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
  46. *
  47. * @author Eric Albert (<a href="mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu</a>)
  48. * @version 1.4b1 (Released June 20, 2001)
  49. */
  50. public class BrowserLauncher {
  51. /**
  52. * The Java virtual machine that we are running on. Actually, in most cases we only care
  53. * about the operating system, but some operating systems require us to switch on the VM. */
  54. private static int jvm;
  55. /** The browser for the system */
  56. private static Object browser;
  57. /**
  58. * Caches whether any classes, methods, and fields that are not part of the JDK and need to
  59. * be dynamically loaded at runtime loaded successfully.
  60. * <p>
  61. * Note that if this is <code>false</code>, <code>openURL()</code> will always return an
  62. * IOException.
  63. */
  64. private static boolean loadedWithoutErrors;
  65. /** The com.apple.mrj.MRJFileUtils class */
  66. private static Class<?> mrjFileUtilsClass;
  67. /** The com.apple.MacOS.AEDesc class */
  68. private static Class aeDescClass;
  69. /** The <init>(int) method of com.apple.MacOS.AETarget */
  70. private static Constructor aeTargetConstructor;
  71. /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
  72. private static Constructor appleEventConstructor;
  73. /** The <init>(String) method of com.apple.MacOS.AEDesc */
  74. private static Constructor aeDescConstructor;
  75. /** The findFolder method of com.apple.mrj.MRJFileUtils */
  76. private static Method findFolder;
  77. /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
  78. private static Method getFileCreator;
  79. /** The getFileType method of com.apple.mrj.MRJFileUtils */
  80. private static Method getFileType;
  81. /** The openURL method of com.apple.mrj.MRJFileUtils */
  82. private static Method openURL;
  83. /** The makeOSType method of com.apple.MacOS.OSUtils */
  84. private static Method makeOSType;
  85. /** The putParameter method of com.apple.MacOS.AppleEvent */
  86. private static Method putParameter;
  87. /** The sendNoReply method of com.apple.MacOS.AppleEvent */
  88. private static Method sendNoReply;
  89. /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
  90. private static Object kSystemFolderType;
  91. /** The keyDirectObject AppleEvent parameter type */
  92. private static Integer keyDirectObject;
  93. /** The kAutoGenerateReturnID AppleEvent code */
  94. private static Integer kAutoGenerateReturnID;
  95. /** The kAnyTransactionID AppleEvent code */
  96. private static Integer kAnyTransactionID;
  97. /** The linkage object required for JDirect 3 on Mac OS X. */
  98. private static Object linkage;
  99. /** The framework to reference on Mac OS X */
  100. private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox";
  101. /** JVM constant for MRJ 2.0 */
  102. private static final int MRJ_2_0 = 0;
  103. /** JVM constant for MRJ 2.1 or later */
  104. private static final int MRJ_2_1 = 1;
  105. /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
  106. private static final int MRJ_3_0 = 3;
  107. /** JVM constant for MRJ 3.1 */
  108. private static final int MRJ_3_1 = 4;
  109. /** JVM constant for any Windows NT JVM */
  110. private static final int WINDOWS_NT = 5;
  111. /** JVM constant for any Windows 9x JVM */
  112. private static final int WINDOWS_9x = 6;
  113. /** JVM constant for any other platform */
  114. private static final int OTHER = -1;
  115. /**
  116. * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep non-U.S. English
  117. * systems from working properly.
  118. */
  119. private static final String FINDER_TYPE = "FNDR";
  120. /**
  121. * The creator code of the Finder on a Macintosh, which is needed to send AppleEvents to the
  122. * application.
  123. */
  124. private static final String FINDER_CREATOR = "MACS";
  125. /** The name for the AppleEvent type corresponding to a GetURL event. */
  126. private static final String GURL_EVENT = "GURL";
  127. /**
  128. * The first parameter that needs to be passed into Runtime.exec() to open the default web
  129. * browser on Windows.
  130. */
  131. private static final String FIRST_WINDOWS_PARAMETER = "/c";
  132. /** The second parameter for Runtime.exec() on Windows. */
  133. private static final String SECOND_WINDOWS_PARAMETER = "start";
  134. /**
  135. * The third parameter for Runtime.exec() on Windows. This is a "title"
  136. * parameter that the command line expects. Setting this parameter allows
  137. * URLs containing spaces to work.
  138. */
  139. private static final String THIRD_WINDOWS_PARAMETER = "\"\"";
  140. /**
  141. * The message from any exception thrown throughout the initialization process.
  142. */
  143. private static String errorMessage;
  144. /**
  145. * An initialization block that determines the operating system and loads the necessary
  146. * runtime data.
  147. */
  148. static {
  149. loadedWithoutErrors = true;
  150. String osName = System.getProperty("os.name");
  151. if (osName.startsWith("Mac OS")) {
  152. String mrjVersion = System.getProperty("mrj.version");
  153. String majorMRJVersion = mrjVersion.substring(0, 3);
  154. try {
  155. double version = Double.valueOf(majorMRJVersion).doubleValue();
  156. if (version == 2) {
  157. jvm = MRJ_2_0;
  158. } else if (version >= 2.1 && version < 3) {
  159. // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
  160. // works via Runtime.exec() and 2.2 supports that but has an openURL() method
  161. // as well that we currently ignore.
  162. jvm = MRJ_2_1;
  163. } else if (version == 3.0) {
  164. jvm = MRJ_3_0;
  165. } else if (version >= 3.1) {
  166. // Assume that all 3.1 and later versions of MRJ work the same.
  167. jvm = MRJ_3_1;
  168. } else {
  169. loadedWithoutErrors = false;
  170. errorMessage = "Unsupported MRJ version: " + version;
  171. }
  172. } catch (NumberFormatException nfe) {
  173. loadedWithoutErrors = false;
  174. errorMessage = "Invalid MRJ version: " + mrjVersion;
  175. }
  176. } else if (osName.startsWith("Windows")) {
  177. if (osName.contains("9")) {
  178. jvm = WINDOWS_9x;
  179. } else {
  180. jvm = WINDOWS_NT;
  181. }
  182. } else {
  183. jvm = OTHER;
  184. }
  185. if (loadedWithoutErrors) { // if we haven't hit any errors yet
  186. loadedWithoutErrors = loadClasses();
  187. }
  188. }
  189. /**
  190. * This class should be never be instantiated; this just ensures so.
  191. */
  192. private BrowserLauncher() { }
  193. /**
  194. * Called by a static initializer to load any classes, fields, and methods required at runtime
  195. * to locate the user's web browser.
  196. * @return <code>true</code> if all intialization succeeded
  197. * <code>false</code> if any portion of the initialization failed
  198. */
  199. private static boolean loadClasses() {
  200. switch (jvm) {
  201. case MRJ_3_0:
  202. try {
  203. Class<?> linker = Class.forName("com.apple.mrj.jdirect.Linker");
  204. Constructor constructor = linker.getConstructor(Class.class);
  205. linkage = constructor.newInstance(new Object[] { BrowserLauncher.class });
  206. } catch (ClassNotFoundException cnfe) {
  207. errorMessage = cnfe.getMessage();
  208. return false;
  209. } catch (NoSuchMethodException nsme) {
  210. errorMessage = nsme.getMessage();
  211. return false;
  212. } catch (InvocationTargetException ite) {
  213. errorMessage = ite.getMessage();
  214. return false;
  215. } catch (InstantiationException ie) {
  216. errorMessage = ie.getMessage();
  217. return false;
  218. } catch (IllegalAccessException iae) {
  219. errorMessage = iae.getMessage();
  220. return false;
  221. }
  222. break;
  223. case MRJ_3_1:
  224. try {
  225. mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
  226. openURL = mrjFileUtilsClass.getDeclaredMethod("openURL", String.class);
  227. } catch (ClassNotFoundException cnfe) {
  228. errorMessage = cnfe.getMessage();
  229. return false;
  230. } catch (NoSuchMethodException nsme) {
  231. errorMessage = nsme.getMessage();
  232. return false;
  233. }
  234. break;
  235. default:
  236. break;
  237. }
  238. return true;
  239. }
  240. /**
  241. * Attempts to locate the default web browser on the local system. Caches results so it
  242. * only locates the browser once for each use of this class per JVM instance.
  243. * @return The browser for the system. Note that this may not be what you would consider
  244. * to be a standard web browser; instead, it's the application that gets called to
  245. * open the default web browser. In some cases, this will be a non-String object
  246. * that provides the means of calling the default browser.
  247. */
  248. private static Object locateBrowser() {
  249. if (browser != null) {
  250. return browser;
  251. }
  252. switch (jvm) {
  253. case MRJ_2_0:
  254. try {
  255. Integer finderCreatorCode = (Integer) makeOSType.invoke(null, new Object[] { FINDER_CREATOR });
  256. Object aeTarget = aeTargetConstructor.newInstance(new Object[] { finderCreatorCode });
  257. Integer gurlType = (Integer) makeOSType.invoke(null, new Object[] { GURL_EVENT });
  258. Object appleEvent = appleEventConstructor.newInstance(new Object[] { gurlType, gurlType, aeTarget, kAutoGenerateReturnID, kAnyTransactionID });
  259. // Don't set browser = appleEvent because then the next time we call
  260. // locateBrowser(), we'll get the same AppleEvent, to which we'll already have
  261. // added the relevant parameter. Instead, regenerate the AppleEvent every time.
  262. // There's probably a way to do this better; if any has any ideas, please let
  263. // me know.
  264. return appleEvent;
  265. } catch (IllegalAccessException iae) {
  266. browser = null;
  267. errorMessage = iae.getMessage();
  268. return browser;
  269. } catch (InstantiationException ie) {
  270. browser = null;
  271. errorMessage = ie.getMessage();
  272. return browser;
  273. } catch (InvocationTargetException ite) {
  274. browser = null;
  275. errorMessage = ite.getMessage();
  276. return browser;
  277. }
  278. case MRJ_2_1:
  279. File systemFolder;
  280. try {
  281. systemFolder = (File) findFolder.invoke(null, new Object[] { kSystemFolderType });
  282. } catch (IllegalArgumentException iare) {
  283. browser = null;
  284. errorMessage = iare.getMessage();
  285. return browser;
  286. } catch (IllegalAccessException iae) {
  287. browser = null;
  288. errorMessage = iae.getMessage();
  289. return browser;
  290. } catch (InvocationTargetException ite) {
  291. browser = null;
  292. errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
  293. return browser;
  294. }
  295. String[] systemFolderFiles = systemFolder.list();
  296. // Avoid a FilenameFilter because that can't be stopped mid-list
  297. for(int i = 0; i < systemFolderFiles.length; i++) {
  298. try {
  299. File file = new File(systemFolder, systemFolderFiles[i]);
  300. if (!file.isFile()) {
  301. continue;
  302. }
  303. // We're looking for a file with a creator code of 'MACS' and
  304. // a type of 'FNDR'. Only requiring the type results in non-Finder
  305. // applications being picked up on certain Mac OS 9 systems,
  306. // especially German ones, and sending a GURL event to those
  307. // applications results in a logout under Multiple Users.
  308. Object fileType = getFileType.invoke(null, new Object[] { file });
  309. if (FINDER_TYPE.equals(fileType.toString())) {
  310. Object fileCreator = getFileCreator.invoke(null, new Object[] { file });
  311. if (FINDER_CREATOR.equals(fileCreator.toString())) {
  312. browser = file.toString(); // Actually the Finder, but that's OK
  313. return browser;
  314. }
  315. }
  316. } catch (IllegalArgumentException iare) {
  317. browser = browser;
  318. errorMessage = iare.getMessage();
  319. return null;
  320. } catch (IllegalAccessException iae) {
  321. browser = null;
  322. errorMessage = iae.getMessage();
  323. return browser;
  324. } catch (InvocationTargetException ite) {
  325. browser = null;
  326. errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
  327. return browser;
  328. }
  329. }
  330. browser = null;
  331. break;
  332. case MRJ_3_0:
  333. case MRJ_3_1:
  334. browser = ""; // Return something non-null
  335. break;
  336. case WINDOWS_NT:
  337. browser = "cmd.exe";
  338. break;
  339. case WINDOWS_9x:
  340. browser = "command.com";
  341. break;
  342. case OTHER:
  343. default:
  344. browser = "";
  345. for (String candidateBrowser : new String[] { "gnome-open", "sensible-browser" }) {
  346. if (FileUtilities.findOnPath(candidateBrowser) != null) {
  347. browser = candidateBrowser;
  348. break;
  349. }
  350. }
  351. break;
  352. }
  353. return browser;
  354. }
  355. /**
  356. * Attempts to open the default web browser to the given URL.
  357. * @param url The URL to open
  358. * @throws IOException If the web browser could not be located or does not run
  359. */
  360. public static void openURL(String url) throws IOException {
  361. // FIXME: when we switch to Java 6, this whole class can be replaced with "Desktop.getDesktop().browse(new URI(url));"
  362. try {
  363. java.lang.reflect.Method Desktop_getDesktop_method = Class.forName("java.awt.Desktop").getDeclaredMethod("getDesktop", new Class[0]);
  364. java.lang.reflect.Method Desktop_browse_method = Class.forName("java.awt.Desktop").getDeclaredMethod("browse", new Class[] { java.net.URI.class });
  365. Object desktop = Desktop_getDesktop_method.invoke(null);
  366. Desktop_browse_method.invoke(desktop, new java.net.URI(url));
  367. return;
  368. } catch (Throwable ex) {
  369. ex = ex;
  370. }
  371. if (!loadedWithoutErrors) {
  372. throw new IOException("Exception in finding browser: " + errorMessage);
  373. }
  374. Object browser = locateBrowser();
  375. if (browser == null) {
  376. throw new IOException("Unable to locate browser: " + errorMessage);
  377. }
  378. switch (jvm) {
  379. case MRJ_2_0:
  380. Object aeDesc = null;
  381. try {
  382. aeDesc = aeDescConstructor.newInstance(new Object[] { url });
  383. putParameter.invoke(browser, new Object[] { keyDirectObject, aeDesc });
  384. sendNoReply.invoke(browser, new Object[] { });
  385. } catch (InvocationTargetException ite) {
  386. throw new IOException("InvocationTargetException while creating AEDesc: " + ite.getMessage());
  387. } catch (IllegalAccessException iae) {
  388. throw new IOException("IllegalAccessException while building AppleEvent: " + iae.getMessage());
  389. } catch (InstantiationException ie) {
  390. throw new IOException("InstantiationException while creating AEDesc: " + ie.getMessage());
  391. } finally {
  392. aeDesc = null; // Encourage it to get disposed if it was created
  393. browser = null; // Ditto
  394. }
  395. break;
  396. case MRJ_2_1:
  397. Runtime.getRuntime().exec(new String[] { (String) browser, url } );
  398. break;
  399. case MRJ_3_0:
  400. int[] instance = new int[1];
  401. int result = ICStart(instance, 0);
  402. if (result == 0) {
  403. int[] selectionStart = new int[] { 0 };
  404. byte[] urlBytes = url.getBytes();
  405. int[] selectionEnd = new int[] { urlBytes.length };
  406. result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes,
  407. urlBytes.length, selectionStart,
  408. selectionEnd);
  409. if (result == 0) {
  410. // Ignore the return value; the URL was launched successfully
  411. // regardless of what happens here.
  412. ICStop(instance);
  413. } else {
  414. throw new IOException("Unable to launch URL: " + result);
  415. }
  416. } else {
  417. throw new IOException("Unable to create an Internet Config instance: " + result);
  418. }
  419. break;
  420. case MRJ_3_1:
  421. try {
  422. openURL.invoke(null, new Object[] { url });
  423. } catch (InvocationTargetException ite) {
  424. throw new IOException("InvocationTargetException while calling openURL: " + ite.getMessage());
  425. } catch (IllegalAccessException iae) {
  426. throw new IOException("IllegalAccessException while calling openURL: " + iae.getMessage());
  427. }
  428. break;
  429. case WINDOWS_NT:
  430. case WINDOWS_9x:
  431. // Add quotes around the URL to allow ampersands and other special
  432. // characters to work.
  433. Process process = Runtime.getRuntime().exec(new String[] { (String) browser,
  434. FIRST_WINDOWS_PARAMETER,
  435. SECOND_WINDOWS_PARAMETER,
  436. THIRD_WINDOWS_PARAMETER,
  437. '"' + url + '"' });
  438. // This avoids a memory leak on some versions of Java on Windows.
  439. // That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
  440. try {
  441. process.waitFor();
  442. process.exitValue();
  443. } catch (InterruptedException ie) {
  444. throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
  445. }
  446. break;
  447. case OTHER:
  448. default:
  449. // Try the simplest thing possible
  450. Runtime.getRuntime().exec(new String[] { (String) browser, url });
  451. break;
  452. }
  453. }
  454. /**
  455. * Methods required for Mac OS X. The presence of native methods does not cause
  456. * any problems on other platforms.
  457. */
  458. private native static int ICStart(int[] instance, int signature);
  459. private native static int ICStop(int[] instance);
  460. private native static int ICLaunchURL(int instance, byte[] hint, byte[] data, int len,
  461. int[] selectionStart, int[] selectionEnd);
  462. }