1 package tim.prune.function.browser;
4 import javax.swing.JOptionPane;
8 * Class to launch a browser window to show an external map
9 * Some code and ideas taken from BareBonesBrowserLaunch at centerkey.com
11 public abstract class BrowserLauncher
13 private static boolean _initialised = false;
14 private static String[] _browserCommand = null;
15 private static boolean _urlNeedsQuotes = false;
19 * Init method to set up browser
21 private static void init()
23 _browserCommand = null;
24 // First check if "which" command is available
25 if (commandExists("which"))
27 // which exists, so try browsers in turn
28 String[] browsersToTry = {"firefox", "iceweasel", "konqueror", "opera", "epiphany",
29 "mozilla", "safari", "google-chrome", "lynx"};
30 String browserFound = null;
31 for (int i=0; i<browsersToTry.length && browserFound == null; i++)
33 if (commandExists(browsersToTry[i]))
34 browserFound = browsersToTry[i];
36 if (browserFound != null) {
37 _browserCommand = new String[] {browserFound, null};
41 if (_browserCommand == null)
43 // no which command (or none of the browsers found), so check if os name looks like a mac
44 String osName = System.getProperty("os.name").toLowerCase();
45 boolean isMacOsx = osName.indexOf("mac os") >= 0 || osName.indexOf("darwin") >= 0;
47 // for Mac Osx just use "open" command
48 _browserCommand = new String[] {"open", null};
51 // assume it's not linux or mac, so try windows method using "start" command
52 _browserCommand = new String[] {"cmd.exe", "/C", "start", "\"\"", null};
53 _urlNeedsQuotes = true;
61 * Check if the specified command exists on the system
62 * @param inCommand command to check
63 * @return true if the command exists
65 private static boolean commandExists(String inCommand)
69 String[] commands = {"which", inCommand};
70 if (Runtime.getRuntime().exec(commands).waitFor() == 0)
75 catch (Exception e) {} // failed
81 * Launch a browser window to show the given url
82 * @param inUrl url to show
84 public static void launchBrowser(String inUrl)
86 // First choice is to try the Desktop library from java 6, if available
88 Class<?> d = Class.forName("java.awt.Desktop");
89 d.getDeclaredMethod("browse", new Class[] {URI.class}).invoke(
90 d.getDeclaredMethod("getDesktop").invoke(null), new Object[] {URI.create(inUrl)});
91 //above code mimics: Desktop.getDesktop().browse(URI.create(inUrl));
93 catch (Exception ignore)
95 // The Desktop call failed, need to try backup methods
96 if (!_initialised) {init();}
97 if (_browserCommand == null) {
98 JOptionPane.showMessageDialog(null, "Cannot show url: " + inUrl);
104 // enclose url in quotes if necessary
106 if (_urlNeedsQuotes) {url = "\"" + url + "\"";}
107 // Fill in url in last element of command array
108 _browserCommand[_browserCommand.length - 1] = url;
109 // execute command to launch browser
110 Runtime.getRuntime().exec(_browserCommand);
112 catch (Exception e) {
113 JOptionPane.showMessageDialog(null, "Failed to show url: " + inUrl);