📄 browser.java
字号:
/* * Control a web browser from your java application. * Copyright (C) 2001-2002 Stephen Ostermiller * http://ostermiller.org/contact.pl?regarding=Java+Utilities * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * See COPYING.TXT for details. */package com.Ostermiller.util;import java.io.*;import java.text.MessageFormat;import java.net.URL;import java.net.URLDecoder;import java.net.URLClassLoader;import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.util.Properties;import java.util.Vector;import java.util.ResourceBundle;import java.util.Locale;import java.io.StringReader;import java.lang.reflect.*;/** * Allows URLs to be opened in the system browser on Windows and Unix. * More information about this class is available from <a target="_top" href= * "http://ostermiller.org/utils/Browser.html">ostermiller.org</a>. * * @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities * @since ostermillerutils 1.00.00 */public class Browser { /** * The dialog that allows user configuration of the options for this class. * * @since ostermillerutils 1.00.00 */ protected static BrowserDialog dialog; /** * Locale specific strings displayed to the user. * * @since ostermillerutils 1.00.00 */ protected static ResourceBundle labels = ResourceBundle.getBundle("com.Ostermiller.util.Browser", Locale.getDefault()); /** * Set the locale used for getting localized * strings. * * @param locale Locale used to for i18n. * * @since ostermillerutils 1.00.00 */ public static void setLocale(Locale locale){ labels = ResourceBundle.getBundle("com.Ostermiller.util.Browser", locale); } /** * A list of commands to try in order to display the url. * The url is put into the command using MessageFormat, so * the URL will be specified as {0} in the command. * Some examples of commands to try might be:<br> * <code>rundll32 url.dll,FileProtocolHandler {0}</code></br> * <code>netscape {0}</code><br> * These commands are passed in order to exec until something works * when displayURL is used. * * @since ostermillerutils 1.00.00 */ public static String[] exec = null; /** * Determine appropriate commands to start a browser on the current * operating system. On windows: <br> * <code>rundll32 url.dll,FileProtocolHandler {0}</code></br> * On other operating systems, the "which" command is used to * test if Mozilla, netscape, and lynx(xterm) are available (in that * order). * * @since ostermillerutils 1.00.00 */ public static void init(){ exec = defaultCommands(); } /** * Retrieve the default commands to open a browser for this system. * * @since ostermillerutils 1.00.00 */ public static String[] defaultCommands(){ String[] exec = null; if ( System.getProperty("os.name").startsWith("Windows")){ exec = new String[]{ "rundll32 url.dll,FileProtocolHandler {0}", }; } else if (System.getProperty("os.name").startsWith("Mac")){ Vector browsers = new Vector(); 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){ exec = null; } else { exec = (String[])browsers.toArray(new String[0]); } } else { Vector browsers = new Vector(); try { Process p = Runtime.getRuntime().exec("which firebird"); if (p.waitFor() == 0){ browsers.add("firebird -remote openURL({0})"); browsers.add("firebird {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){ exec = null; } else { exec = (String[])browsers.toArray(new String[0]); } } return exec; } /** * Save the options used to the given properties file. * Property names used will all start with com.Ostermiller.util.Browser * Properties are saved in such a way that a call to load(props); will * restore the state of this class. * If the default commands to open a browser are being used then * they are not saved in the properties file, assuming that the user * will want to use the defaults next time even if the defaults change. * * @param props properties file to which configuration is saved. * * @since ostermillerutils 1.00.00 */ public static void save(Properties props){ boolean saveBrowser = false; if (Browser.exec != null && Browser.exec.length > 0){ String[] exec = Browser.defaultCommands(); if (exec != null && exec.length == Browser.exec.length){ for (int i=0; i<exec.length; i++){ if (!exec[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"); } } /** * Load the options for this class from the given properties file. * This method is designed to work with the save(props) method. All * properties used will start with com.Ostermiller.util.Browser. If * no configuration is found, the default configuration will be used. * If this method is used, a call to Browser.init(); is not needed. * * @param props properties file from which configuration is loaded. * * @since ostermillerutils 1.00.00 */ 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(); } } /** * Display a URL in the system browser. * * Browser.init() should be called before calling this function or * Browser.exec should be set explicitly. * * For security reasons, the URL will may not be passed directly to the * browser as it is passed to this method. The URL may be made safe for * the exec command by URLEncoding the URL before passing it. * * @param url the url to display * @throws IOException if the url is not valid or the browser fails to star * * @since ostermillerutils 1.00.00 */ 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()){ // Mac OS X has NSWorkspace, but it is not in the classpath, add it. 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(); //success = com.apple.cocoa.application.NSWorkspace.sharedWorkspace().openURL(new java.net.URL(url)); } catch (Exception x) {} 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}); //com.apple.mrj.MRJFileUtils.openURL(url); } catch (Exception x){ System.err.println(x.getMessage()); throw new IOException(labels.getString("failed")); } } } else { throw new IOException(labels.getString("nocommand")); } } else { // for security, see if the url is valid. // this is primarily to catch an attack in which the url // starts with a - to fool the command line flags, bu // it could catch other stuff as well, and will throw a // MalformedURLException which will give the caller of this // function useful information. new URL(url); // escape any weird characters in the url. This is primarily // to prevent an attacker from putting in spaces // that might fool exec into allowing // the attacker to execute arbitrary code. 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 == '\\'){ //characters that are necessary for URLs and should be safe //to pass to exec. Exec uses a default string tokenizer with //the default arguments (whitespace) to separate command line //arguments, so there should be no problem with anything bu //whitespace. sb.append(c); } else { c = (char)(c & 0xFF); // get the lowest 8 bits (URLEncoding) 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 each of the exec commands until something works try { for (int i=0; i<exec.length && !found; i++){ try { // stick the url into the command command = MessageFormat.format(exec[i], messageArray); // parse the command line. Vector argsVector = new Vector(); BrowserCommandLexer lex = new BrowserCommandLexer(new StringReader(command)); String t; while ((t = lex.getNextToken()) != null) { argsVector.add(t); } String[] args = new String[argsVector.size()];
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -