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", "chromium", "midori", "safari", "lynx"};
30 String browserFound = null;
31 for (String browser : browsersToTry)
33 if (commandExists(browser))
35 browserFound = browser;
39 if (browserFound != null) {
40 _browserCommand = new String[] {browserFound, null};
44 if (_browserCommand == null)
46 // no which command (or none of the browsers found), so check if os name looks like a mac
47 String osName = System.getProperty("os.name").toLowerCase();
48 boolean isMacOsx = osName.indexOf("mac os") >= 0 || osName.indexOf("darwin") >= 0;
50 // for Mac Osx just use "open" command
51 _browserCommand = new String[] {"open", null};
54 // assume it's not linux or mac, so try windows method using "start" command
55 _browserCommand = new String[] {"cmd.exe", "/C", "start", "\"\"", null};
56 _urlNeedsQuotes = true;
64 * Check if the specified command exists on the system
65 * @param inCommand command to check
66 * @return true if the command exists
68 private static boolean commandExists(String inCommand)
72 String[] commands = {"which", inCommand};
73 if (Runtime.getRuntime().exec(commands).waitFor() == 0)
78 catch (Exception e) {} // failed
84 * Launch a browser window to show the given url
85 * @param inUrl url to show
87 public static void launchBrowser(String inUrl)
89 if (inUrl == null) {return;}
90 // First choice is to try the Desktop library from java 6, if available
92 Class<?> d = Class.forName("java.awt.Desktop");
93 d.getDeclaredMethod("browse", new Class[] {URI.class}).invoke(
94 d.getDeclaredMethod("getDesktop").invoke(null), new Object[] {URI.create(inUrl)});
95 //above code mimics: Desktop.getDesktop().browse(URI.create(inUrl));
97 catch (Exception ignore)
99 // The Desktop call failed, need to try backup methods
100 if (!_initialised) {init();}
101 if (_browserCommand == null) {
102 JOptionPane.showMessageDialog(null, "Cannot show url: " + inUrl);
108 // enclose url in quotes if necessary
110 if (_urlNeedsQuotes) {url = "\"" + url + "\"";}
111 // Fill in url in last element of command array
112 _browserCommand[_browserCommand.length - 1] = url;
113 // execute command to launch browser
114 Runtime.getRuntime().exec(_browserCommand);
116 catch (Exception e) {
117 JOptionPane.showMessageDialog(null, "Failed to show url: " + inUrl);