Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/applet/Main.java
38829 views
/*1* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.applet;2627import java.io.BufferedInputStream;28import java.io.File;29import java.io.FileInputStream;30import java.io.FileOutputStream;31import java.io.IOException;32import java.lang.reflect.Method;33import java.lang.reflect.InvocationTargetException;34import java.net.URL;35import java.net.MalformedURLException;36import java.util.Enumeration;37import java.util.Properties;38import java.util.Vector;39import sun.net.www.ParseUtil;4041/**42* The main entry point into AppletViewer.43*/44public class Main {45/**46* The file which contains all of the AppletViewer specific properties.47*/48static File theUserPropertiesFile;4950/**51* The default key/value pairs for the required user-specific properties.52*/53static final String [][] avDefaultUserProps = {54// There's a bootstrapping problem here. If we don't have a proxyHost,55// then we will not be able to connect to a URL outside the firewall;56// however, there's no way for us to set the proxyHost without starting57// AppletViewer. This problem existed before the re-write.58{"http.proxyHost", ""},59{"http.proxyPort", "80"},60{"package.restrict.access.sun", "true"}61};6263static {64File userHome = new File(System.getProperty("user.home"));65// make sure we can write to this location66userHome.canWrite();6768theUserPropertiesFile = new File(userHome, ".appletviewer");69}7071// i18n72private static AppletMessageHandler amh = new AppletMessageHandler("appletviewer");7374/**75* Member variables set according to options passed in to AppletViewer.76*/77private boolean debugFlag = false;78private boolean helpFlag = false;79private String encoding = null;80private boolean noSecurityFlag = false;81private static boolean cmdLineTestFlag = false;8283/**84* The list of valid URLs passed in to AppletViewer.85*/86private static Vector urlList = new Vector(1);8788// This is used in init(). Getting rid of this is desirable but depends89// on whether the property that uses it is necessary/standard.90public static final String theVersion = System.getProperty("java.version");9192/**93* The main entry point into AppletViewer.94*/95public static void main(String [] args) {96Main m = new Main();97int ret = m.run(args);9899// Exit immediately if we got some sort of error along the way.100// For debugging purposes, if we have passed in "-XcmdLineTest" we101// force a premature exit.102if ((ret != 0) || (cmdLineTestFlag))103System.exit(ret);104}105106private int run(String [] args) {107// DECODE ARGS108try {109if (args.length == 0) {110usage();111return 0;112}113for (int i = 0; i < args.length; ) {114int j = decodeArg(args, i);115if (j == 0) {116throw new ParseException(lookup("main.err.unrecognizedarg",117args[i]));118}119i += j;120}121} catch (ParseException e) {122System.err.println(e.getMessage());123return 1;124}125126// CHECK ARGUMENTS127if (helpFlag) {128usage();129return 0;130}131132if (urlList.size() == 0) {133System.err.println(lookup("main.err.inputfile"));134return 1;135}136137if (debugFlag) {138// START A DEBUG SESSION139// Given the current architecture, we will end up decoding the140// arguments again, but at least we are guaranteed to have141// arguments which are valid.142return invokeDebugger(args);143}144145// INSTALL THE SECURITY MANAGER (if necessary)146if (!noSecurityFlag && (System.getSecurityManager() == null))147init();148149// LAUNCH APPLETVIEWER FOR EACH URL150for (int i = 0; i < urlList.size(); i++) {151try {152// XXX 5/17 this parsing method should be changed/fixed so that153// it doesn't do both parsing of the html file and launching of154// the AppletPanel155AppletViewer.parse((URL) urlList.elementAt(i), encoding);156} catch (IOException e) {157System.err.println(lookup("main.err.io", e.getMessage()));158return 1;159}160}161return 0;162}163164private static void usage() {165System.out.println(lookup("usage"));166}167168/**169* Decode a single argument in an array and return the number of elements170* used.171*172* @param args The array of arguments.173* @param i The argument to decode.174* @return The number of array elements used when the argument was175* decoded.176* @exception ParseException177* Thrown when there is a problem with something in the178* argument array.179*/180private int decodeArg(String [] args, int i) throws ParseException {181String arg = args[i];182int argc = args.length;183184if ("-help".equalsIgnoreCase(arg) || "-?".equals(arg)) {185helpFlag = true;186return 1;187} else if ("-encoding".equals(arg) && (i < argc - 1)) {188if (encoding != null)189throw new ParseException(lookup("main.err.dupoption", arg));190encoding = args[++i];191return 2;192} else if ("-debug".equals(arg)) {193debugFlag = true;194return 1;195} else if ("-Xnosecurity".equals(arg)) {196// This is an undocumented (and, in the future, unsupported)197// flag which prevents AppletViewer from installing its own198// SecurityManager.199200System.err.println();201System.err.println(lookup("main.warn.nosecmgr"));202System.err.println();203204noSecurityFlag = true;205return 1;206} else if ("-XcmdLineTest".equals(arg)) {207// This is an internal flag which should be used for command-line208// testing. It instructs AppletViewer to force a premature exit209// immediately after the applet has been launched.210cmdLineTestFlag = true;211return 1;212} else if (arg.startsWith("-")) {213throw new ParseException(lookup("main.err.unsupportedopt", arg));214} else {215// we found what we hope is a url216URL url = parseURL(arg);217if (url != null) {218urlList.addElement(url);219return 1;220}221}222return 0;223}224225/**226* Following the relevant RFC, construct a valid URL based on the passed in227* string.228*229* @param url a string which represents either a relative or absolute URL.230* @return a URL when the passed in string can be interpreted according231* to the RFC, <code>null</code> otherwise.232* @exception ParseException233* Thrown when we are unable to construct a proper URL from the234* passed in string.235*/236private URL parseURL(String url) throws ParseException {237URL u = null;238// prefix of the urls with 'file' scheme239String prefix = "file:";240241try {242if (url.indexOf(':') <= 1)243{244// appletviewer accepts only unencoded filesystem paths245u = ParseUtil.fileToEncodedURL(new File(url));246} else if (url.startsWith(prefix) &&247url.length() != prefix.length() &&248!(new File(url.substring(prefix.length())).isAbsolute()))249{250// relative file URL, like this "file:index.html"251// ensure that this file URL is absolute252// ParseUtil.fileToEncodedURL should be done last (see 6329251)253String path = ParseUtil.fileToEncodedURL(new File(System.getProperty("user.dir"))).getPath() +254url.substring(prefix.length());255u = new URL("file", "", path);256} else {257// appletviewer accepts only encoded urls258u = new URL(url);259}260} catch (MalformedURLException e) {261throw new ParseException(lookup("main.err.badurl",262url, e.getMessage()));263}264265return u;266}267268/**269* Invoke the debugger with the arguments passed in to appletviewer.270*271* @param args The arguments passed into the debugger.272* @return <code>0</code> if the debugger is invoked successfully,273* <code>1</code> otherwise.274*/275private int invokeDebugger(String [] args) {276// CONSTRUCT THE COMMAND LINE277String [] newArgs = new String[args.length + 1];278int current = 0;279280// Add a -classpath argument that prevents281// the debugger from launching appletviewer with the default of282// ".". appletviewer's classpath should never contain valid283// classes since they will result in security exceptions.284// Ideally, the classpath should be set to "", but the VM won't285// allow an empty classpath, so a phony directory name is used.286String phonyDir = System.getProperty("java.home") +287File.separator + "phony";288newArgs[current++] = "-Djava.class.path=" + phonyDir;289290// Appletviewer's main class is the debuggee291newArgs[current++] = "sun.applet.Main";292293// Append all the of the original appletviewer arguments,294// leaving out the "-debug" option.295for (int i = 0; i < args.length; i++) {296if (!("-debug".equals(args[i]))) {297newArgs[current++] = args[i];298}299}300301// LAUNCH THE DEBUGGER302// Reflection is used for two reasons:303// 1) The debugger classes are on classpath and thus must be loaded304// by the application class loader. (Currently, appletviewer are305// loaded through the boot class path out of rt.jar.)306// 2) Reflection removes any build dependency between appletviewer307// and jdb.308try {309Class c = Class.forName("com.sun.tools.example.debug.tty.TTY", true,310ClassLoader.getSystemClassLoader());311Method m = c.getDeclaredMethod("main",312new Class[] { String[].class });313m.invoke(null, new Object[] { newArgs });314} catch (ClassNotFoundException cnfe) {315System.err.println(lookup("main.debug.cantfinddebug"));316return 1;317} catch (NoSuchMethodException nsme) {318System.err.println(lookup("main.debug.cantfindmain"));319return 1;320} catch (InvocationTargetException ite) {321System.err.println(lookup("main.debug.exceptionindebug"));322return 1;323} catch (IllegalAccessException iae) {324System.err.println(lookup("main.debug.cantaccess"));325return 1;326}327return 0;328}329330private void init() {331// GET APPLETVIEWER USER-SPECIFIC PROPERTIES332Properties avProps = getAVProps();333334// ADD OTHER RANDOM PROPERTIES335// XXX 5/18 need to revisit why these are here, is there some336// standard for what is available?337338// Standard browser properties339avProps.put("browser", "sun.applet.AppletViewer");340avProps.put("browser.version", "1.06");341avProps.put("browser.vendor", "Oracle Corporation");342avProps.put("http.agent", "Java(tm) 2 SDK, Standard Edition v" + theVersion);343344// Define which packages can be extended by applets345// XXX 5/19 probably not needed, not checked in AppletSecurity346avProps.put("package.restrict.definition.java", "true");347avProps.put("package.restrict.definition.sun", "true");348349// Define which properties can be read by applets.350// A property named by "key" can be read only when its twin351// property "key.applet" is true. The following ten properties352// are open by default. Any other property can be explicitly353// opened up by the browser user by calling appletviewer with354// -J-Dkey.applet=true355avProps.put("java.version.applet", "true");356avProps.put("java.vendor.applet", "true");357avProps.put("java.vendor.url.applet", "true");358avProps.put("java.class.version.applet", "true");359avProps.put("os.name.applet", "true");360avProps.put("os.version.applet", "true");361avProps.put("os.arch.applet", "true");362avProps.put("file.separator.applet", "true");363avProps.put("path.separator.applet", "true");364avProps.put("line.separator.applet", "true");365366// Read in the System properties. If something is going to be367// over-written, warn about it.368Properties sysProps = System.getProperties();369for (Enumeration e = sysProps.propertyNames(); e.hasMoreElements(); ) {370String key = (String) e.nextElement();371String val = (String) sysProps.getProperty(key);372String oldVal;373if ((oldVal = (String) avProps.setProperty(key, val)) != null)374System.err.println(lookup("main.warn.prop.overwrite", key,375oldVal, val));376}377378// INSTALL THE PROPERTY LIST379System.setProperties(avProps);380381// Create and install the security manager382if (!noSecurityFlag) {383System.setSecurityManager(new AppletSecurity());384} else {385System.err.println(lookup("main.nosecmgr"));386}387388// REMIND: Create and install a socket factory!389}390391/**392* Read the AppletViewer user-specific properties. Typically, these393* properties should reside in the file $USER/.appletviewer. If this file394* does not exist, one will be created. Information for this file will395* be gleaned from $USER/.hotjava/properties. If that file does not exist,396* then default values will be used.397*398* @return A Properties object containing all of the AppletViewer399* user-specific properties.400*/401private Properties getAVProps() {402Properties avProps = new Properties();403404File dotAV = theUserPropertiesFile;405if (dotAV.exists()) {406// we must have already done the conversion407if (dotAV.canRead()) {408// just read the file409avProps = getAVProps(dotAV);410} else {411// send out warning and use defaults412System.err.println(lookup("main.warn.cantreadprops",413dotAV.toString()));414avProps = setDefaultAVProps();415}416} else {417// create the $USER/.appletviewer file418419// see if $USER/.hotjava/properties exists420File userHome = new File(System.getProperty("user.home"));421File dotHJ = new File(userHome, ".hotjava");422dotHJ = new File(dotHJ, "properties");423if (dotHJ.exists()) {424// just read the file425avProps = getAVProps(dotHJ);426} else {427// send out warning and use defaults428System.err.println(lookup("main.warn.cantreadprops",429dotHJ.toString()));430avProps = setDefaultAVProps();431}432433// SAVE THE FILE434try (FileOutputStream out = new FileOutputStream(dotAV)) {435avProps.store(out, lookup("main.prop.store"));436} catch (IOException e) {437System.err.println(lookup("main.err.prop.cantsave",438dotAV.toString()));439}440}441return avProps;442}443444/**445* Set the AppletViewer user-specific properties to be the default values.446*447* @return A Properties object containing all of the AppletViewer448* user-specific properties, set to the default values.449*/450private Properties setDefaultAVProps() {451Properties avProps = new Properties();452for (int i = 0; i < avDefaultUserProps.length; i++) {453avProps.setProperty(avDefaultUserProps[i][0],454avDefaultUserProps[i][1]);455}456return avProps;457}458459/**460* Given a file, find only the properties that are setable by AppletViewer.461*462* @param inFile A Properties file from which we select the properties of463* interest.464* @return A Properties object containing all of the AppletViewer465* user-specific properties.466*/467private Properties getAVProps(File inFile) {468Properties avProps = new Properties();469470// read the file471Properties tmpProps = new Properties();472try (FileInputStream in = new FileInputStream(inFile)) {473tmpProps.load(new BufferedInputStream(in));474} catch (IOException e) {475System.err.println(lookup("main.err.prop.cantread", inFile.toString()));476}477478// pick off the properties we care about479for (int i = 0; i < avDefaultUserProps.length; i++) {480String value = tmpProps.getProperty(avDefaultUserProps[i][0]);481if (value != null) {482// the property exists in the file, so replace the default483avProps.setProperty(avDefaultUserProps[i][0], value);484} else {485// just use the default486avProps.setProperty(avDefaultUserProps[i][0],487avDefaultUserProps[i][1]);488}489}490return avProps;491}492493/**494* Methods for easier i18n handling.495*/496497private static String lookup(String key) {498return amh.getMessage(key);499}500501private static String lookup(String key, String arg0) {502return amh.getMessage(key, arg0);503}504505private static String lookup(String key, String arg0, String arg1) {506return amh.getMessage(key, arg0, arg1);507}508509private static String lookup(String key, String arg0, String arg1,510String arg2) {511return amh.getMessage(key, arg0, arg1, arg2);512}513514class ParseException extends RuntimeException515{516public ParseException(String msg) {517super(msg);518}519520public ParseException(Throwable t) {521super(t.getMessage());522this.t = t;523}524525Throwable t = null;526}527}528529530