package com.Ostermiller.util;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.lang.reflect.Method;
import java.net.*;
import java.text.MessageFormat;
import java.util.*;
import javax.swing.*;
public class Browser {
protected static BrowserDialog dialog;
protected static ResourceBundle labels = ResourceBundle.getBundle("com.Ostermiller.util.Browser", Locale.getDefault());
public static void setLocale(Locale locale){
labels = ResourceBundle.getBundle("com.Ostermiller.util.Browser", locale);
}
public static String[] exec = null;
public static void init(){
exec = defaultCommands();
}
public static String[] defaultCommands(){
String[] execLocal = null;
if ( System.getProperty("os.name").startsWith("Windows")){
execLocal = new String[]{
"rundll32 url.dll,FileProtocolHandler {0}",
};
} else if (System.getProperty("os.name").startsWith("Mac")){
ArrayList<String> browsers = new ArrayList<String>();
try {
Process p = Runtime.getRuntime().exec("which open");
if (p.waitFor() == 0){
browsers.add("open {0}");
}
} catch (IOException e){
} catch (InterruptedException e){
}
if (browsers.size() == 0){
execLocal = null;
} else {
execLocal = browsers.toArray(new String[0]);
}
} else if (System.getProperty("os.name").startsWith("SunOS")) {
execLocal = new String[]{"/usr/dt/bin/sdtwebclient {0}"};
} else {
ArrayList<String> browsers = new ArrayList<String>();
try {
Process p = Runtime.getRuntime().exec("which firefox");
if (p.waitFor() == 0){
browsers.add("firefox -remote openURL({0})");
browsers.add("firefox {0}");
}
} catch (IOException e){
} catch (InterruptedException e){
}
try {
Process p = Runtime.getRuntime().exec("which mozilla");
if (p.waitFor() == 0){
browsers.add("mozilla -remote openURL({0})");
browsers.add("mozilla {0}");
}
} catch (IOException e){
} catch (InterruptedException e){
}
try {
Process p = Runtime.getRuntime().exec("which opera");
if (p.waitFor() == 0){
browsers.add("opera -remote openURL({0})");
browsers.add("opera {0}");
}
} catch (IOException e){
} catch (InterruptedException e){
}
try {
Process p = Runtime.getRuntime().exec("which galeon");
if (p.waitFor() == 0){
browsers.add("galeon {0}");
}
} catch (IOException e){
} catch (InterruptedException e){
}
try {
Process p = Runtime.getRuntime().exec("which konqueror");
if (p.waitFor() == 0){
browsers.add("konqueror {0}");
}
} catch (IOException e){
} catch (InterruptedException e){
}
try {
Process p = Runtime.getRuntime().exec("which netscape");
if (p.waitFor() == 0){
browsers.add("netscape -remote openURL({0})");
browsers.add("netscape {0}");
}
} catch (IOException e){
} catch (InterruptedException e){
}
try {
Process p = Runtime.getRuntime().exec("which xterm");
if (p.waitFor() == 0){
p = Runtime.getRuntime().exec("which lynx");
if (p.waitFor() == 0){
browsers.add("xterm -e lynx {0}");
}
}
} catch (IOException e){
} catch (InterruptedException e){
}
if (browsers.size() == 0){
execLocal = null;
} else {
execLocal = browsers.toArray(new String[0]);
}
}
return execLocal;
}
public static void save(Properties props){
boolean saveBrowser = false;
if (Browser.exec != null && Browser.exec.length > 0){
String[] execLocal = Browser.defaultCommands();
if (execLocal != null && execLocal.length == Browser.exec.length){
for (int i=0; i<execLocal.length; i++){
if (!execLocal[i].equals(Browser.exec[i])){
saveBrowser = true;
}
}
} else {
saveBrowser = true;
}
}
if (saveBrowser){
StringBuffer sb = new StringBuffer();
for (int i=0; Browser.exec != null && i < Browser.exec.length; i++){
sb.append(Browser.exec[i]).append('\n');
}
props.put("com.Ostermiller.util.Browser.open", sb.toString());
} else {
props.remove("com.Ostermiller.util.Browser.open");
}
}
public static void load(Properties props){
if (props.containsKey("com.Ostermiller.util.Browser.open")){
java.util.StringTokenizer tok = new java.util.StringTokenizer(
props.getProperty("com.Ostermiller.util.Browser.open"),
"\r\n",
false
);
int count = tok.countTokens();
String[] exec = new String[count];
for (int i=0; i < count; i++){
exec[i] = tok.nextToken();
}
Browser.exec = exec;
} else {
Browser.init();
}
}
public static void displayURL(String url) throws IOException {
if (exec == null || exec.length == 0){
if (System.getProperty("os.name").startsWith("Mac")){
boolean success = false;
try {
Class<?> nSWorkspace;
if (new File("/System/Library/Java/com/apple/cocoa/application/NSWorkspace.class").exists()){
ClassLoader classLoader = new URLClassLoader(new URL[]{new File("/System/Library/Java").toURL()});
nSWorkspace = Class.forName("com.apple.cocoa.application.NSWorkspace", true, classLoader);
} else {
nSWorkspace = Class.forName("com.apple.cocoa.application.NSWorkspace");
}
Method sharedWorkspace = nSWorkspace.getMethod("sharedWorkspace", new Class[] {});
Object workspace = sharedWorkspace.invoke(null, new Object[] {});
Method openURL = nSWorkspace.getMethod("openURL", new Class[] {Class.forName("java.net.URL")});
success = ((Boolean)openURL.invoke(workspace, new Object[] {new java.net.URL(url)})).booleanValue();
} catch (Exception x) {
success = false;
}
if (!success){
try {
Class<?> mrjFileUtils = Class.forName("com.apple.mrj.MRJFileUtils");
Method openURL = mrjFileUtils.getMethod("openURL", new Class[] {Class.forName("java.lang.String")});
openURL.invoke(null, new Object[] {url});
} catch (Exception x){
System.err.println(x.getMessage());
throw new IOException(labels.getString("failed"));
}
}
} else {
throw new IOException(labels.getString("nocommand"));
}
} else {
new URL(url);
StringBuffer sb = new StringBuffer(url.length());
for (int i=0; i<url.length(); i++){
char c = url.charAt(i);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
|| c == '.' || c == ':' || c == '&' || c == '@' || c == '/' || c == '?'
|| c == '%' || c =='+' || c == '=' || c == '#' || c == '-' || c == '\\'){
sb.append(c);
} else {
c = (char)(c & 0xFF); if (c < 0x10){
sb.append("%0" + Integer.toHexString(c));
} else {
sb.append("%" + Integer.toHexString(c));
}
}
}
String[] messageArray = new String[1];
messageArray[0] = sb.toString();
String command = null;
boolean found = false;
try {
for (int i=0; i<exec.length && !found; i++){
try {
command = MessageFormat.format(exec[i], (Object[])messageArray);
ArrayList<String> argumentList = new ArrayList<String>();
BrowserCommandLexer lex = new BrowserCommandLexer(new StringReader(command));
String t;
while ((t = lex.getNextToken()) != null) {
argumentList.add(t);
}
String[] args = new String[argumentList.size()];
args = argumentList.toArray(args);
boolean useShortCut = false;
if (args[0].equals("rundll32") && args[1].equals("url.dll,FileProtocolHandler")){
if (args[2].startsWith("file:/")){
if (args[2].charAt(6) != '/'){
args[2] = "file://" + args[2].substring(6);
}
if (args[2].charAt(7) != '/'){
args[2] = "file:///" + args[2].substring(7);
}
useShortCut = true;
} else if (args[2].toLowerCase().endsWith("html") || args[2].toLowerCase().endsWith("htm")){
useShortCut = true;
}
}
if (useShortCut){
File shortcut = File.createTempFile("OpenInBrowser", ".url");
shortcut = shortcut.getCanonicalFile();
shortcut.deleteOnExit();
PrintWriter out = new PrintWriter(new FileWriter(shortcut));
out.println("[InternetShortcut]");
out.println("URL=" + args[2]);
out.close();
args[2] = shortcut.getCanonicalPath();
}
Process p = Runtime.getRuntime().exec(args);
for (int j=0; j<2; j++){
try {
Thread.sleep(1000);
} catch (InterruptedException ix){
throw new RuntimeException(ix);
}
}
if (p.exitValue() == 0){
found = true;
}
} catch (IOException x){
System.err.println(labels.getString("warning") + " " + x.getMessage());
}
}
if (!found){
throw new IOException(labels.getString("failed"));
}
} catch (IllegalThreadStateException e){
}
}
}
public static void displayURLs(String[] urls) throws IOException {
if (urls == null || urls.length == 0){
return;
}
if (urls.length == 1){
displayURL(urls[0]);
return;
}
File shortcut = File.createTempFile("DisplayURLs", ".html");
shortcut = shortcut.getCanonicalFile();
shortcut.deleteOnExit();
PrintWriter out = new PrintWriter(new FileWriter(shortcut));
out.println("<!-- saved from url=(0014)about:internet -->");
out.println("<html>");
out.println("<head>");
out.println("<title>" + labels.getString("html.openurls") + "</title>");
out.println("<script language=\"javascript\" type=\"text/javascript\">");
out.println("function displayURLs(){");
for (int i=1; i<urls.length; i++){
out.println("window.open(\"" + urls[i] + "\", \"_blank\", \"toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes\");");
}
out.println("location.href=\"" + urls[0] + "\";");
out.println("}");
out.println("</script>");
out.println("</head>");
out.println("<body onload=\"javascript:displayURLs()\">");
out.println("<noscript>");
for (String element: urls) {
out.println("<a target=\"_blank\" href=\"" + element + "\">" + element + "</a><br>");
}
out.println("</noscript>");
out.println("</body>");
out.println("</html>");
out.close();
displayURL(shortcut.toURL().toString());
}
public static void displayURLinNew(String url) throws IOException {
displayURLsinNew (new String[] {url});
}
public static void displayURLsinNew(String[] urls) throws IOException {
if (urls == null || urls.length == 0){
return;
}
File shortcut = File.createTempFile("DisplayURLs", ".html");
shortcut.deleteOnExit();
shortcut = shortcut.getCanonicalFile();
PrintWriter out = new PrintWriter(new FileWriter(shortcut));
out.println("<!-- saved from url=(0014)about:internet -->");
out.println("<html>");
out.println("<head>");
out.println("<title>" + labels.getString("html.openurls") + "</title>");
out.println("<script language=\"javascript\" type=\"text/javascript\">");
out.println("function displayURLs(){");
out.println("var hlength = 0;");
out.println("try {");
out.println("hlength = history.length;");
out.println("} catch (e) {}");
out.println("if (hlength>0) {");
out.println("window.open(\"" + urls[0] + "\", \"_blank\", \"toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes\");");
out.println("}");
for (int i=1; i<urls.length; i++){
out.println("window.open(\"" + urls[i] + "\", \"_blank\", \"toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes\");");
}
out.println("if (hlength==0) {");
out.println("location.href=\"" + urls[0] + "\";");
out.println("} else {");
out.println("history.back()");
out.println("}");
out.println("}");
out.println("</script>");
out.println("</head>");
out.println("<body onload=\"javascript:displayURLs()\">");
out.println("<noscript>");
for (String element: urls) {
out.println("<a target=\"_blank\" href=\"" + element + "\">" + element + "</a><br>");
}
out.println("</noscript>");
out.println("</body>");
out.println("</html>");
out.close();
displayURL(shortcut.toURL().toString());
}
public static void displayURL(String url, String namedWindow) throws IOException {
displayURLs (new String[] {url}, new String[] {namedWindow});
}
public static void displayURLs(String[] urls, String[] namedWindows) throws IOException {
if (urls == null || urls.length == 0){
return;
}
File shortcut = File.createTempFile("DisplayURLs", ".html");
shortcut.deleteOnExit();
shortcut = shortcut.getCanonicalFile();
PrintWriter out = new PrintWriter(new FileWriter(shortcut));
out.println("<!-- saved from url=(0014)about:internet -->");
out.println("<html>");
out.println("<head>");
out.println("<title>" + labels.getString("html.openurls") + "</title>");
out.println("<base target=\"" + ((namedWindows==null||namedWindows.length==0||namedWindows[0]==null)?"_blank":namedWindows[0]) + "\">");
out.println("<script language=\"javascript\" type=\"text/javascript\">");
for (int i=1; i<urls.length; i++){
out.println("window.open(\"" + urls[i] + "\", \"" + ((namedWindows==null||namedWindows.length<=i||namedWindows[i]==null)?"_blank":namedWindows[i]) + "\", \"toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes\");");
}
out.println("location.href=\"" + urls[0] + "\";");
out.println("</script>");
out.println("</head>");
out.println("<body onload=\"javascript:displayURLs()\">");
out.println("<noscript>");
for (String element: urls) {
out.println("<a target=\"" + ((namedWindows==null||namedWindows.length==0||namedWindows[0]==null)?"_blank":namedWindows[0]) + "\" href=\"" + element + "\">" + element + "</a><br>");
}
out.println("</noscript>");
out.println("</body>");
out.println("</html>");
out.close();
displayURL(shortcut.toURL().toString());
}
public static void displayURLs(String[] urls, String namedWindow) throws IOException {
displayURLs(urls, new String[] {namedWindow});
}
public static void main(String[] args){
try {
Browser.init();
if (Browser.dialogConfiguration(null)){
if (args.length == 0){
Browser.displayURLs(new String[]{
"http://www.google.com/",
"http://dmoz.org/",
"http://ostermiller.org",
}, "fun");
} else if (args.length == 1){
Browser.displayURL(args[0], "fun");
} else {
Browser.displayURLs(args, "fun");
}
}
try {
Thread.sleep(10000);
} catch (InterruptedException ix){
throw new RuntimeException(ix);
}
} catch (IOException e){
System.err.println(e.getMessage());
}
System.exit(0);
}
public static boolean dialogConfiguration(Frame owner){
dialogConfiguration(owner, null);
return Browser.dialog.changed();
}
@Deprecated public static boolean dialogConfiguration(Frame owner, Properties props){
if (Browser.dialog == null){
Browser.dialog = new BrowserDialog(owner);
}
if (props != null){
Browser.dialog.setProps(props);
}
Browser.dialog.show();
return Browser.dialog.changed();
}
private static JTextArea description;
private static JTextArea commandLinesArea;
private static JButton resetButton;
private static JButton browseButton;
private static JLabel commandLinesLabel;
private static JFileChooser fileChooser;
private static JPanel dialogPanel = null;
private static Window dialogParent = null;
public static JPanel getDialogPanel(Window parent){
dialogParent = parent;
if (dialogPanel == null){
commandLinesArea = new JTextArea("", 8, 40);
JScrollPane scrollpane = new JScrollPane(commandLinesArea);
resetButton = new JButton(labels.getString("dialog.reset"));
browseButton = new JButton(labels.getString("dialog.browse"));
commandLinesLabel = new JLabel(labels.getString("dialog.commandLines"));
description = new JTextArea(labels.getString("dialog.description"));
description.setEditable(false);
description.setOpaque( false );
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
if (source == resetButton){
setCommands(Browser.defaultCommands());
} else if (source == browseButton){
if (fileChooser == null){
fileChooser = new JFileChooser();
}
if (fileChooser.showOpenDialog(dialogParent) == JFileChooser.APPROVE_OPTION){
String app = fileChooser.getSelectedFile().getPath();
StringBuffer sb = new StringBuffer(2 * app.length());
for (int i=0; i<app.length(); i++){
char c = app.charAt(i);
if (c == '\"' || c == '\\') {
sb.append('\\');
}
sb.append(c);
}
app = sb.toString();
if (app.indexOf(" ") != -1){
app = '"' + app + '"';
}
String commands = commandLinesArea.getText();
if (commands.length() != 0 && !commands.endsWith("\n") && !commands.endsWith("\r")){
commands += "\n";
}
commandLinesArea.setText(commands + app + " {0}");
}
}
}
};
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
c.insets.top = 5;
c.insets.bottom = 5;
dialogPanel = new JPanel(gridbag);
dialogPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 5, 20));
c.gridwidth = GridBagConstraints.REMAINDER;
c.anchor = GridBagConstraints.WEST;
gridbag.setConstraints(description, c);
dialogPanel.add(description);
c.gridy = 1;
c.gridwidth = GridBagConstraints.RELATIVE;
gridbag.setConstraints(commandLinesLabel, c);
dialogPanel.add(commandLinesLabel);
JPanel buttonPanel = new JPanel();
c.anchor = GridBagConstraints.EAST;
browseButton.addActionListener(actionListener);
buttonPanel.add(browseButton);
resetButton.addActionListener(actionListener);
buttonPanel.add(resetButton);
gridbag.setConstraints(buttonPanel, c);
dialogPanel.add(buttonPanel);
c.gridy = 2;
c.gridwidth = GridBagConstraints.REMAINDER