diff options
Diffstat (limited to 'netx/net')
100 files changed, 3019 insertions, 3327 deletions
diff --git a/netx/net/sourceforge/jnlp/AppletDesc.java b/netx/net/sourceforge/jnlp/AppletDesc.java index 39133ce..a3b7fe4 100644 --- a/netx/net/sourceforge/jnlp/AppletDesc.java +++ b/netx/net/sourceforge/jnlp/AppletDesc.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp; import java.io.*; @@ -45,8 +44,7 @@ public class AppletDesc { private int height; /** the parameters */ - private Map<String,String> parameters; - + private Map<String, String> parameters; /** * Create an Applet descriptor. @@ -59,13 +57,13 @@ public class AppletDesc { * @param parameters the parameters */ public AppletDesc(String name, String mainClass, URL documentBase, int width, int height, - Map<String,String> parameters) { + Map<String, String> parameters) { this.name = name; this.mainClass = mainClass; this.documentBase = documentBase; this.width = width; this.height = height; - this.parameters = new HashMap<String,String>(parameters); + this.parameters = new HashMap<String, String>(parameters); } /** @@ -106,8 +104,8 @@ public class AppletDesc { /** * Returns the applet parameters */ - public Map<String,String> getParameters() { - return new HashMap<String,String>(parameters); + public Map<String, String> getParameters() { + return new HashMap<String, String>(parameters); } /** diff --git a/netx/net/sourceforge/jnlp/ApplicationDesc.java b/netx/net/sourceforge/jnlp/ApplicationDesc.java index 221eaac..87fc75a 100644 --- a/netx/net/sourceforge/jnlp/ApplicationDesc.java +++ b/netx/net/sourceforge/jnlp/ApplicationDesc.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp; import java.io.*; @@ -35,7 +34,6 @@ public class ApplicationDesc { /** the arguments */ private String arguments[]; - /** * Create an Application descriptor. * diff --git a/netx/net/sourceforge/jnlp/ComponentDesc.java b/netx/net/sourceforge/jnlp/ComponentDesc.java index 7d0b2a3..2bf4967 100644 --- a/netx/net/sourceforge/jnlp/ComponentDesc.java +++ b/netx/net/sourceforge/jnlp/ComponentDesc.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp; import java.io.*; diff --git a/netx/net/sourceforge/jnlp/DefaultLaunchHandler.java b/netx/net/sourceforge/jnlp/DefaultLaunchHandler.java index 357ad1a..7240684 100644 --- a/netx/net/sourceforge/jnlp/DefaultLaunchHandler.java +++ b/netx/net/sourceforge/jnlp/DefaultLaunchHandler.java @@ -23,7 +23,6 @@ import java.awt.*; import java.util.*; import javax.swing.*; - /** * This default implementation shows prints the exception to * stdout and if not in headless mode displays the exception in a @@ -100,7 +99,7 @@ public class DefaultLaunchHandler implements LaunchHandler { Throwable causes[] = ex.getCauses(); - for (int i=0; i < causes.length; i++) { + for (int i = 0; i < causes.length; i++) { result.append(" ("); result.append(causes[i].getClass().getName()); result.append(" "); diff --git a/netx/net/sourceforge/jnlp/ExtensionDesc.java b/netx/net/sourceforge/jnlp/ExtensionDesc.java index 09a2ddb..4e4283f 100644 --- a/netx/net/sourceforge/jnlp/ExtensionDesc.java +++ b/netx/net/sourceforge/jnlp/ExtensionDesc.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp; import static net.sourceforge.jnlp.runtime.Translator.R; @@ -46,12 +45,11 @@ public class ExtensionDesc { private JNLPFile file; /** map from ext-part to local part */ - private Map<String,String> extToPart = new HashMap<String,String>(); + private Map<String, String> extToPart = new HashMap<String, String>(); /** eager ext parts */ private List<String> eagerExtParts = new ArrayList<String>(); - /** * Create an extention descriptor. * @@ -125,7 +123,7 @@ public class ExtensionDesc { file = new JNLPFile(location); if (JNLPRuntime.isDebug()) - System.out.println("Resolve: "+file.getInformation().getTitle()); + System.out.println("Resolve: " + file.getInformation().getTitle()); // check for it being an extension descriptor if (!file.isComponent() && !file.isInstaller()) diff --git a/netx/net/sourceforge/jnlp/IconDesc.java b/netx/net/sourceforge/jnlp/IconDesc.java index c115b42..448bcf5 100644 --- a/netx/net/sourceforge/jnlp/IconDesc.java +++ b/netx/net/sourceforge/jnlp/IconDesc.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp; import java.io.*; @@ -47,7 +46,6 @@ public class IconDesc { /** destop shortcut icon */ public static final Object SHORTCUT = "shortcut"; - /** the location of the icon */ private URL location; @@ -66,7 +64,6 @@ public class IconDesc { /** the size, or -1 if unknown*/ private int size; - /** * Creates an icon descriptor with the specified information. * @@ -131,5 +128,4 @@ public class IconDesc { return depth; } - } diff --git a/netx/net/sourceforge/jnlp/InformationDesc.java b/netx/net/sourceforge/jnlp/InformationDesc.java index 076b6b3..faee3c2 100644 --- a/netx/net/sourceforge/jnlp/InformationDesc.java +++ b/netx/net/sourceforge/jnlp/InformationDesc.java @@ -15,7 +15,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp; import java.io.*; @@ -37,13 +36,13 @@ public class InformationDesc { // specification name. /** one-line description */ - public static final Object ONE_LINE= "oneline"; + public static final Object ONE_LINE = "oneline"; /** short description */ - public static final Object SHORT= "short"; + public static final Object SHORT = "short"; /** tooltip description */ - public static final Object TOOLTIP= "tooltip"; + public static final Object TOOLTIP = "tooltip"; /** default description */ public static final Object DEFAULT = "default"; @@ -57,7 +56,6 @@ public class InformationDesc { /** the JNLPFile this information is for */ private JNLPFile jnlpFile; - /** * Create an information element object. * @@ -87,7 +85,7 @@ public class InformationDesc { * Returns the application's homepage. */ public URL getHomepage() { - return (URL)getItem("homepage"); + return (URL) getItem("homepage"); } /** @@ -114,9 +112,9 @@ public class InformationDesc { * Information.TOOLTIP, Information.DEFAULT */ public String getDescription(Object kind) { - String result = (String) getItem("description-"+kind); + String result = (String) getItem("description-" + kind); if (result == null) - return (String) getItem("description-"+DEFAULT); + return (String) getItem("description-" + DEFAULT); else return result; } @@ -129,7 +127,7 @@ public class InformationDesc { * @return an array of zero of more IconDescs of the specified icon type */ public IconDesc[] getIcons(Object kind) { - List<Object> icons = getItems("icon-"+kind); + List<Object> icons = getItems("icon-" + kind); return icons.toArray(new IconDesc[icons.size()]); }; @@ -151,14 +149,14 @@ public class InformationDesc { return null; IconDesc best = null; - for (int i=0; i < icons.length; i++) { + for (int i = 0; i < icons.length; i++) { if (icons[i].getWidth() >= width && - icons[i].getHeight() >= height) { + icons[i].getHeight() >= height) { if (best == null) best = icons[i]; if (icons[i].getWidth() <= best.getWidth() && // Use <= so last specified of - icons[i].getHeight() <= best.getHeight()) // equivalent icons is chosen. + icons[i].getHeight() <= best.getHeight()) // equivalent icons is chosen. best = icons[i]; } } @@ -233,7 +231,7 @@ public class InformationDesc { if (items.size() == 0) return null; else - return items.get( items.size()-1 ); + return items.get(items.size() - 1); } /** @@ -244,9 +242,9 @@ public class InformationDesc { return Collections.emptyList(); List<Object> result = new ArrayList<Object>(); - for (int i=0; i < info.size(); i+=2) + for (int i = 0; i < info.size(); i += 2) if (info.get(i).equals(key)) - result.add( info.get(i+1) ); + result.add(info.get(i + 1)); return result; } @@ -257,7 +255,7 @@ public class InformationDesc { */ protected void addItem(String key, Object value) { if (info == null) - info = new ArrayList<Object>(); + info = new ArrayList<Object>(); info.add(key); info.add(value); diff --git a/netx/net/sourceforge/jnlp/InstallerDesc.java b/netx/net/sourceforge/jnlp/InstallerDesc.java index 17b8f87..797f5ac 100644 --- a/netx/net/sourceforge/jnlp/InstallerDesc.java +++ b/netx/net/sourceforge/jnlp/InstallerDesc.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp; import java.io.*; @@ -32,7 +31,6 @@ public class InstallerDesc { /** the main class name and package. */ private String mainClass; - /** * Creates a installer descriptor. * diff --git a/netx/net/sourceforge/jnlp/JARDesc.java b/netx/net/sourceforge/jnlp/JARDesc.java index d3941ca..78bc311 100644 --- a/netx/net/sourceforge/jnlp/JARDesc.java +++ b/netx/net/sourceforge/jnlp/JARDesc.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp; import java.io.*; diff --git a/netx/net/sourceforge/jnlp/JNLPFile.java b/netx/net/sourceforge/jnlp/JNLPFile.java index 6ba186f..24a6566 100644 --- a/netx/net/sourceforge/jnlp/JNLPFile.java +++ b/netx/net/sourceforge/jnlp/JNLPFile.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp; import static net.sourceforge.jnlp.runtime.Translator.R; @@ -34,7 +33,6 @@ import net.sourceforge.jnlp.cache.ResourceTracker; import net.sourceforge.jnlp.cache.UpdatePolicy; import net.sourceforge.jnlp.runtime.JNLPRuntime; - /** * Provides methods to access the information in a Java Network * Launching Protocol (JNLP) file. The Java Network Launching @@ -115,8 +113,7 @@ public class JNLPFile { defaultLocale = Locale.getDefault(); defaultOS = System.getProperty("os.name"); defaultArch = System.getProperty("os.arch"); - } - catch (SecurityException ex) { + } catch (SecurityException ex) { // null values will still work, and app can set defaults later } } @@ -241,7 +238,6 @@ public class JNLPFile { //parse(Parser.getRootNode(input), strict, null); } - /** * Open the jnlp file URL from the cache if there, otherwise * download to the cache. Called from constructor. @@ -252,11 +248,10 @@ public class JNLPFile { try { ResourceTracker tracker = new ResourceTracker(false); // no prefetch - tracker.addResource(location, version , policy); + tracker.addResource(location, version, policy); return tracker.getInputStream(location); - } - catch (Exception ex) { + } catch (Exception ex) { throw new IOException(ex.getMessage()); } } @@ -333,16 +328,16 @@ public class JNLPFile { * through the specified locale. */ public InformationDesc getInformation(final Locale locale) { - return new InformationDesc(this, new Locale[] {locale}) { + return new InformationDesc(this, new Locale[] { locale }) { protected List<Object> getItems(Object key) { List<Object> result = new ArrayList<Object>(); - for (int i=0; i < info.size(); i++) { + for (int i = 0; i < info.size(); i++) { InformationDesc infoDesc = (InformationDesc) info.get(i); if (localMatches(locale, infoDesc.getLocales())) if (localMatches(locale, infoDesc.getLocales())) - result.addAll(infoDesc.getItems(key) ); + result.addAll(infoDesc.getItems(key)); } return result; @@ -378,17 +373,17 @@ public class JNLPFile { * specified locale, os, and arch. */ public ResourcesDesc getResources(final Locale locale, final String os, final String arch) { - return new ResourcesDesc(this, new Locale[] {locale}, new String[] {os}, new String[] {arch}) { + return new ResourcesDesc(this, new Locale[] { locale }, new String[] { os }, new String[] { arch }) { public <T> List<T> getResources(Class<T> launchType) { List<T> result = new ArrayList<T>(); - for (int i=0; i < resources.size(); i++) { + for (int i = 0; i < resources.size(); i++) { ResourcesDesc rescDesc = resources.get(i); if (localMatches(locale, rescDesc.getLocales()) - && stringMatches(os, rescDesc.getOS()) - && stringMatches(arch, rescDesc.getArch())) - result.addAll(rescDesc.getResources(launchType) ); + && stringMatches(os, rescDesc.getOS()) + && stringMatches(arch, rescDesc.getArch())) + result.addAll(rescDesc.getResources(launchType)); } result.addAll(sharedResources.getResources(launchType)); @@ -499,7 +494,6 @@ public class JNLPFile { defaultLocale = locale; } - /** * Returns whether a locale is matched by one of more other * locales. Only the non-empty language, country, and variant @@ -515,7 +509,7 @@ public class JNLPFile { if (available == null || available.length == 0) return true; - for (int i=0; i < available.length; i++) { + for (int i = 0; i < available.length; i++) { String language = requested.getLanguage(); // "" but never null String country = requested.getCountry(); String variant = requested.getVariant(); @@ -546,7 +540,7 @@ public class JNLPFile { if (available == null || available.length == 0) return true; - for (int i=0; i < available.length; i++) + for (int i = 0; i < available.length; i++) if (available[i] != null && available[i].startsWith(prefixStr)) return true; @@ -579,11 +573,9 @@ public class JNLPFile { launchType = parser.getLauncher(root); component = parser.getComponent(root); security = parser.getSecurity(root); - } - catch (ParseException ex) { + } catch (ParseException ex) { throw ex; - } - catch (Exception ex) { + } catch (Exception ex) { if (JNLPRuntime.isDebug()) ex.printStackTrace(); diff --git a/netx/net/sourceforge/jnlp/JREDesc.java b/netx/net/sourceforge/jnlp/JREDesc.java index 54538f4..5f7e8c2 100644 --- a/netx/net/sourceforge/jnlp/JREDesc.java +++ b/netx/net/sourceforge/jnlp/JREDesc.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp; import static net.sourceforge.jnlp.runtime.Translator.R; @@ -49,7 +48,6 @@ public class JREDesc { /** list of ResourceDesc objects */ private List resources; - /** * Create a JRE descriptor. * @@ -139,10 +137,10 @@ public class JREDesc { boolean lastCharacterIsDigit = true; // the last character must be 0-9 or k/K/m/M - char lastChar = Character.toLowerCase(heapSize.charAt(heapSize.length()-1)); + char lastChar = Character.toLowerCase(heapSize.charAt(heapSize.length() - 1)); if ((lastChar < '0' || lastChar > '9')) { lastCharacterIsDigit = false; - if (lastChar != 'k' && lastChar!= 'm' ) { + if (lastChar != 'k' && lastChar != 'm') { throw new ParseException(R("PBadHeapSize", heapSize)); } } @@ -152,7 +150,7 @@ public class JREDesc { indexOfLastDigit = indexOfLastDigit - 1; } - String size = heapSize.substring(0,indexOfLastDigit); + String size = heapSize.substring(0, indexOfLastDigit); try { // check that the number is a number! Integer.valueOf(size); diff --git a/netx/net/sourceforge/jnlp/LaunchException.java b/netx/net/sourceforge/jnlp/LaunchException.java index 2666387..9e682df 100644 --- a/netx/net/sourceforge/jnlp/LaunchException.java +++ b/netx/net/sourceforge/jnlp/LaunchException.java @@ -48,12 +48,11 @@ public class LaunchException extends Exception { /** severity of the warning/error */ private String severity; - /** * Creates a LaunchException without detail message. */ public LaunchException(JNLPFile file, Exception cause, String severity, String category, String summary, String description) { - super(severity + ": " + category + ": "+ summary); + super(severity + ": " + category + ": " + summary); this.file = file; this.category = category; @@ -79,7 +78,7 @@ public class LaunchException extends Exception { * Creates a LaunchException with a cause and detail message */ public LaunchException(String message, Throwable cause) { - this(message+": "+cause.getMessage()); + this(message + ": " + cause.getMessage()); // replace with setCause when no longer 1.3 compatible this.cause = cause; diff --git a/netx/net/sourceforge/jnlp/LaunchHandler.java b/netx/net/sourceforge/jnlp/LaunchHandler.java index 5176fb0..a0b106b 100644 --- a/netx/net/sourceforge/jnlp/LaunchHandler.java +++ b/netx/net/sourceforge/jnlp/LaunchHandler.java @@ -51,6 +51,7 @@ public interface LaunchHandler { * @return true to allow the application to continue, false to stop it. */ public boolean validationError(LaunchException security); + // this method will probably be replaced when real security // controller is in place. diff --git a/netx/net/sourceforge/jnlp/Launcher.java b/netx/net/sourceforge/jnlp/Launcher.java index 13e0f52..8fa7c1d 100644 --- a/netx/net/sourceforge/jnlp/Launcher.java +++ b/netx/net/sourceforge/jnlp/Launcher.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp; import static net.sourceforge.jnlp.runtime.Translator.R; @@ -56,7 +55,6 @@ import javax.swing.text.html.parser.ParserDelegator; import sun.awt.SunToolkit; - /** * Launches JNLPFiles either in the foreground or background.<p> * @@ -74,7 +72,7 @@ public class Launcher { // defines class Launcher.BgRunner, Launcher.TgThread /** shared thread group */ - /*package*/ static final ThreadGroup mainGroup = new ThreadGroup(R("LAllThreadGroup")); + /*package*/static final ThreadGroup mainGroup = new ThreadGroup(R("LAllThreadGroup")); /** the handler */ private LaunchHandler handler = null; @@ -220,19 +218,18 @@ public class Launcher { } if (file instanceof PluginBridge && cont != null) - tg = new TgThread(file, cont, true); + tg = new TgThread(file, cont, true); else if (cont == null) - tg = new TgThread(file); + tg = new TgThread(file); else - tg = new TgThread(file, cont); + tg = new TgThread(file, cont); tg.start(); try { tg.join(); - } - catch (InterruptedException ex) { - //By default, null is thrown here, and the message dialog is shown. + } catch (InterruptedException ex) { + //By default, null is thrown here, and the message dialog is shown. throw launchWarning(new LaunchException(file, ex, R("LSMinor"), R("LCSystem"), R("LThreadInterrupted"), R("LThreadInterruptedInfo"))); } @@ -339,7 +336,7 @@ public class Launcher { "javaws"; commands.add(pathToWebstartBinary); // use -Jargument format to pass arguments to the JVM through the launcher - for (String arg: vmArgs) { + for (String arg : vmArgs) { commands.add("-J" + arg); } commands.addAll(javawsArgs); @@ -351,11 +348,9 @@ public class Launcher { new StreamEater(p.getInputStream()).start(); p.getOutputStream().close(); - } - catch (NullPointerException ex) { + } catch (NullPointerException ex) { throw launchError(new LaunchException(null, null, R("LSFatal"), R("LCExternalLaunch"), R("LNetxJarMissing"), R("LNetxJarMissingInfo"))); - } - catch (Exception ex) { + } catch (Exception ex) { throw launchError(new LaunchException(null, ex, R("LSFatal"), R("LCExternalLaunch"), R("LCouldNotLaunch"), R("LCouldNotLaunchInfo"))); } } @@ -369,24 +364,23 @@ public class Launcher { try { file = new JNLPFile(location, (Version) null, true, updatePolicy); // strict - } - catch (ParseException ex) { + } catch (ParseException ex) { file = new JNLPFile(location, (Version) null, false, updatePolicy); // only here if strict failed but lax did not fail LaunchException lex = - launchWarning(new LaunchException(file, ex, R("LSMinor"), R("LCFileFormat"), R("LNotToSpec"), R("LNotToSpecInfo"))); + launchWarning(new LaunchException(file, ex, R("LSMinor"), R("LCFileFormat"), R("LNotToSpec"), R("LNotToSpecInfo"))); if (lex != null) throw lex; } return file; - } - catch (Exception ex) { + } catch (Exception ex) { if (ex instanceof LaunchException) throw (LaunchException) ex; // already sent to handler when first thrown - else // IO and Parse + else + // IO and Parse throw launchError(new LaunchException(null, ex, R("LSFatal"), R("LCReadError"), R("LCantRead"), R("LCantReadInfo"))); } } @@ -401,8 +395,10 @@ public class Launcher { markNetxRunning(); Runtime.getRuntime().addShutdownHook(new Thread() { - public void run() { markNetxStopped(); } - }); + public void run() { + markNetxStopped(); + } + }); try { @@ -435,7 +431,6 @@ public class Launcher { } } - ApplicationInstance app = createApplication(file); app.initialize(); @@ -447,25 +442,26 @@ public class Launcher { JARDesc mainJarDesc = file.getResources().getMainJAR(); File f = CacheUtil.getCacheFile(mainJarDesc.getLocation(), null); if (f != null) { - JarFile mainJar = new JarFile(f); - mainName = mainJar.getManifest(). + JarFile mainJar = new JarFile(f); + mainName = mainJar.getManifest(). getMainAttributes().getValue("Main-Class"); } } if (mainName == null) throw launchError(new LaunchException(file, null, - R("LSFatal"), R("LCClient"), R("LCantDetermineMainClass") , + R("LSFatal"), R("LCClient"), R("LCantDetermineMainClass"), R("LCantDetermineMainClassInfo"))); Class<?> mainClass = app.getClassLoader().loadClass(mainName); - Method main = mainClass.getMethod("main", new Class<?>[] {String[].class} ); + Method main = mainClass.getMethod("main", new Class<?>[] { String[].class }); String args[] = file.getApplication().getArguments(); SwingUtilities.invokeAndWait(new Runnable() { // dummy method to force Event Dispatch Thread creation - public void run(){} + public void run() { + } }); setContextClassLoaderForAllThreads(app.getThreadGroup(), app.getClassLoader()); @@ -478,14 +474,12 @@ public class Launcher { } main.setAccessible(true); - main.invoke(null, new Object[] { args } ); + main.invoke(null, new Object[] { args }); return app; - } - catch (LaunchException lex) { + } catch (LaunchException lex) { throw launchError(lex); - } - catch (Exception ex) { + } catch (Exception ex) { throw launchError(new LaunchException(file, ex, R("LSFatal"), R("LCLaunching"), R("LCouldNotLaunch"), R("LCouldNotLaunchInfo"))); } } @@ -509,10 +503,9 @@ public class Launcher { threadCountGuess = threadCountGuess * 2; threads = new Thread[threadCountGuess]; tg.enumerate(threads, true); - } while (threads[threadCountGuess-1] != null); - + } while (threads[threadCountGuess - 1] != null); - for (Thread thread: threads) { + for (Thread thread : threads) { if (thread != null) { if (JNLPRuntime.isDebug()) { System.err.println("Setting " + classLoader + " as the classloader for thread " + thread.getName()); @@ -548,11 +541,9 @@ public class Launcher { applet.getAppletEnvironment().startApplet(); // this should be a direct call to applet instance return applet; - } - catch (LaunchException lex) { + } catch (LaunchException lex) { throw launchError(lex); - } - catch (Exception ex) { + } catch (Exception ex) { throw launchError(new LaunchException(file, ex, R("LSFatal"), R("LCLaunching"), R("LCouldNotLaunch"), R("LCouldNotLaunchInfo"))); } } @@ -568,11 +559,9 @@ public class Launcher { AppletInstance applet = createApplet(file, enableCodeBase, cont); applet.initialize(); return applet; - } - catch (LaunchException lex) { + } catch (LaunchException lex) { throw launchError(lex); - } - catch (Exception ex) { + } catch (Exception ex) { throw launchError(new LaunchException(file, ex, R("LSFatal"), R("LCLaunching"), R("LCouldNotLaunch"), R("LCouldNotLaunchInfo"))); } } @@ -601,17 +590,17 @@ public class Launcher { String appletName = file.getApplet().getMainClass(); - //Classloader chokes if there's '/' in the path to the main class. - //Must replace with '.' instead. - appletName = appletName.replace('/', '.'); + //Classloader chokes if there's '/' in the path to the main class. + //Must replace with '.' instead. + appletName = appletName.replace('/', '.'); Class appletClass = loader.loadClass(appletName); Applet applet = (Applet) appletClass.newInstance(); AppletInstance appletInstance; if (cont == null) - appletInstance = new AppletInstance(file, group, loader, applet); + appletInstance = new AppletInstance(file, group, loader, applet); else - appletInstance = new AppletInstance(file, group, loader, applet, cont); + appletInstance = new AppletInstance(file, group, loader, applet, cont); group.setApplication(appletInstance); loader.setApplication(appletInstance); @@ -619,8 +608,7 @@ public class Launcher { setContextClassLoaderForAllThreads(appletInstance.getThreadGroup(), appletInstance.getClassLoader()); return appletInstance; - } - catch (Exception ex) { + } catch (Exception ex) { throw launchError(new LaunchException(file, ex, R("LSFatal"), R("LCInit"), R("LInitApplet"), R("LInitAppletInfo"))); } } @@ -640,15 +628,14 @@ public class Launcher { String appletName = file.getApplet().getMainClass(); - //Classloader chokes if there's '/' in the path to the main class. - //Must replace with '.' instead. - appletName = appletName.replace('/', '.'); + //Classloader chokes if there's '/' in the path to the main class. + //Must replace with '.' instead. + appletName = appletName.replace('/', '.'); Class appletClass = loader.loadClass(appletName); Applet applet = (Applet) appletClass.newInstance(); return applet; - } - catch (Exception ex) { + } catch (Exception ex) { throw launchError(new LaunchException(file, ex, R("LSFatal"), R("LCInit"), R("LInitApplet"), R("LInitAppletInfo"))); } } @@ -666,8 +653,7 @@ public class Launcher { loader.setApplication(app); return app; - } - catch (Exception ex) { + } catch (Exception ex) { throw new LaunchException(file, ex, R("LSFatal"), R("LCInit"), R("LInitApplication"), R("LInitApplicationInfo")); } } @@ -770,7 +756,7 @@ public class Launcher { fileLock = null; if (JNLPRuntime.isDebug()) { String file = JNLPRuntime.getConfiguration() - .getProperty(DeploymentConfiguration.KEY_USER_NETX_RUNNING_FILE); + .getProperty(DeploymentConfiguration.KEY_USER_NETX_RUNNING_FILE); System.out.println("Release shared lock on " + file); } } catch (IOException e) { @@ -829,33 +815,32 @@ public class Launcher { // Do not create new AppContext if we're using NetX and icedteaplugin. // The plugin needs an AppContext too, but it has to be created earlier. if (context && !isPlugin) - SunToolkit.createNewAppContext(); + SunToolkit.createNewAppContext(); doPerApplicationAppContextHacks(); if (isPlugin) { - // Do not display download indicators if we're using gcjwebplugin. - JNLPRuntime.setDefaultDownloadIndicator(null); - application = getApplet(file, true, cont); + // Do not display download indicators if we're using gcjwebplugin. + JNLPRuntime.setDefaultDownloadIndicator(null); + application = getApplet(file, true, cont); } else { - if (file.isApplication()) - application = launchApplication(file); - else if (file.isApplet()) - application = launchApplet(file, true, cont); // enable applet code base - else if (file.isInstaller()) - application = launchInstaller(file); - else - throw launchError(new LaunchException(file, null, + if (file.isApplication()) + application = launchApplication(file); + else if (file.isApplet()) + application = launchApplet(file, true, cont); // enable applet code base + else if (file.isInstaller()) + application = launchInstaller(file); + else + throw launchError(new LaunchException(file, null, R("LSFatal"), R("LCClient"), R("LNotLaunchable"), R("LNotLaunchableInfo"))); } - } - catch (LaunchException ex) { + } catch (LaunchException ex) { ex.printStackTrace(); exception = ex; // Exit if we can't launch the application. if (exitOnFailure) - System.exit(0); + System.exit(0); } } @@ -869,7 +854,6 @@ public class Launcher { }; - /** * This runnable is used by the <code>launchBackground</code> * methods to launch a JNLP file from a separate thread. @@ -889,8 +873,7 @@ public class Launcher { launch(file); if (location != null) launch(location); - } - catch (LaunchException ex) { + } catch (LaunchException ex) { // launch method communicates error conditions to the // handler if it exists, otherwise we don't care because // there's nothing that can be done about the exception. diff --git a/netx/net/sourceforge/jnlp/NetxPanel.java b/netx/net/sourceforge/jnlp/NetxPanel.java index 1cd4d1b..e049b10 100644 --- a/netx/net/sourceforge/jnlp/NetxPanel.java +++ b/netx/net/sourceforge/jnlp/NetxPanel.java @@ -38,22 +38,19 @@ import sun.awt.SunToolkit; * * @author Francis Kung <[email protected]> */ -public class NetxPanel extends AppletViewerPanel -{ +public class NetxPanel extends AppletViewerPanel { private PluginBridge bridge = null; private boolean exitOnFailure = true; private AppletInstance appInst = null; private boolean appletAlive; - public NetxPanel(URL documentURL, Hashtable<String,String> atts) - { + public NetxPanel(URL documentURL, Hashtable<String, String> atts) { super(documentURL, atts); } // overloaded constructor, called when initialized via plugin - public NetxPanel(URL documentURL, Hashtable<String,String> atts, - boolean exitOnFailure) - { + public NetxPanel(URL documentURL, Hashtable<String, String> atts, + boolean exitOnFailure) { this(documentURL, atts); this.exitOnFailure = exitOnFailure; this.appletAlive = true; @@ -76,7 +73,7 @@ public class NetxPanel extends AppletViewerPanel protected void runLoader() { try { - bridge = new PluginBridge(baseURL, + bridge = new PluginBridge(baseURL, getDocumentBase(), getJarFiles(), getCode(), @@ -84,46 +81,45 @@ public class NetxPanel extends AppletViewerPanel getHeight(), atts); - doInit = true; - dispatchAppletEvent(APPLET_LOADING, null); - status = APPLET_LOAD; - - Launcher l = new Launcher(exitOnFailure); - - try { - appInst = (AppletInstance) l.launch(bridge, this); - } catch (LaunchException e) { - // Assume user has indicated he does not trust the - // applet. - if (exitOnFailure) - System.exit(0); - } - applet = appInst.getApplet(); - - //On the other hand, if you create an applet this way, it'll work - //fine. Note that you might to open visibility in sun.applet.AppletPanel - //for this to work (the loader field, and getClassLoader). - //loader = getClassLoader(getCodeBase(), getClassLoaderCacheKey()); - //applet = createApplet(loader); - - // This shows that when using NetX's JNLPClassLoader, keyboard input - // won't make it to the applet, whereas using sun.applet.AppletClassLoader - // works just fine. - - dispatchAppletEvent(APPLET_LOADING_COMPLETED, null); - - if (applet != null) - { - // Stick it in the frame - applet.setStub(this); - applet.setVisible(false); - add("Center", applet); - showAppletStatus("loaded"); - validate(); - } + doInit = true; + dispatchAppletEvent(APPLET_LOADING, null); + status = APPLET_LOAD; + + Launcher l = new Launcher(exitOnFailure); + + try { + appInst = (AppletInstance) l.launch(bridge, this); + } catch (LaunchException e) { + // Assume user has indicated he does not trust the + // applet. + if (exitOnFailure) + System.exit(0); + } + applet = appInst.getApplet(); + + //On the other hand, if you create an applet this way, it'll work + //fine. Note that you might to open visibility in sun.applet.AppletPanel + //for this to work (the loader field, and getClassLoader). + //loader = getClassLoader(getCodeBase(), getClassLoaderCacheKey()); + //applet = createApplet(loader); + + // This shows that when using NetX's JNLPClassLoader, keyboard input + // won't make it to the applet, whereas using sun.applet.AppletClassLoader + // works just fine. + + dispatchAppletEvent(APPLET_LOADING_COMPLETED, null); + + if (applet != null) { + // Stick it in the frame + applet.setStub(this); + applet.setVisible(false); + add("Center", applet); + showAppletStatus("loaded"); + validate(); + } } catch (Exception e) { this.appletAlive = false; - e.printStackTrace(); + e.printStackTrace(); } } @@ -134,13 +130,13 @@ public class NetxPanel extends AppletViewerPanel // Reminder: Relax visibility in sun.applet.AppletPanel protected synchronized void createAppletThread() { // initialize JNLPRuntime in the main threadgroup - synchronized(JNLPRuntime.initMutex) { + synchronized (JNLPRuntime.initMutex) { //The custom NetX Policy and SecurityManager are set here. if (!JNLPRuntime.isInitialized()) { if (JNLPRuntime.isDebug()) System.out.println("initializing JNLPRuntime..."); - JNLPRuntime.initialize(false); + JNLPRuntime.initialize(false); } else { if (JNLPRuntime.isDebug()) System.out.println("JNLPRuntime already initialized"); diff --git a/netx/net/sourceforge/jnlp/Node.java b/netx/net/sourceforge/jnlp/Node.java index a3f0aa2..3ab00ca 100644 --- a/netx/net/sourceforge/jnlp/Node.java +++ b/netx/net/sourceforge/jnlp/Node.java @@ -50,19 +50,19 @@ class Node { List<Node> list = new ArrayList<Node>(); for (Enumeration e = xml.enumerateChildren(); e.hasMoreElements();) - list.add( new Node((XMLElement)e.nextElement()) ); + list.add(new Node((XMLElement) e.nextElement())); - children = list.toArray( new Node[list.size()] ); + children = list.toArray(new Node[list.size()]); - for (int i=0; i < children.length-1; i++) - children[i].next = children[i+1]; + for (int i = 0; i < children.length - 1; i++) + children[i].next = children[i + 1]; } return children; } String getAttribute(String name) { - return (String)xml.getAttribute(name); + return (String) xml.getAttribute(name); } String getNodeName() { diff --git a/netx/net/sourceforge/jnlp/PackageDesc.java b/netx/net/sourceforge/jnlp/PackageDesc.java index 22822fb..88fcc17 100644 --- a/netx/net/sourceforge/jnlp/PackageDesc.java +++ b/netx/net/sourceforge/jnlp/PackageDesc.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp; import java.io.*; @@ -38,7 +37,6 @@ public class PackageDesc { /** whether the package includes subpackages */ private boolean recursive; - /** * Create a package descriptor. * @@ -64,10 +62,10 @@ public class PackageDesc { // form 2: package.* if (name.endsWith(".*")) { - String pkName = name.substring(0, name.length()-1); + String pkName = name.substring(0, name.length() - 1); if (className.startsWith(pkName)) { - String postfix = className.substring(pkName.length()+1); + String postfix = className.substring(pkName.length() + 1); if (recursive || -1 == postfix.indexOf(".")) return true; diff --git a/netx/net/sourceforge/jnlp/ParseException.java b/netx/net/sourceforge/jnlp/ParseException.java index 9ed86e1..0fcb9bc 100644 --- a/netx/net/sourceforge/jnlp/ParseException.java +++ b/netx/net/sourceforge/jnlp/ParseException.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp; import java.io.*; @@ -36,7 +35,6 @@ public class ParseException extends Exception { /** the original exception */ private Throwable cause = null; - /** * Create a parse exception with the specified message. */ diff --git a/netx/net/sourceforge/jnlp/Parser.java b/netx/net/sourceforge/jnlp/Parser.java index c5b7a34..5c9ad01 100644 --- a/netx/net/sourceforge/jnlp/Parser.java +++ b/netx/net/sourceforge/jnlp/Parser.java @@ -15,7 +15,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp; import static net.sourceforge.jnlp.runtime.Translator.R; @@ -66,7 +65,6 @@ class Parser { }; */ - /** the supported JNLP file versions */ private static Version supportedVersions = new Version("1.0 1.1 1.2 1.3 1.4 1.5 1.6 6.0"); @@ -98,7 +96,6 @@ class Parser { /** whether to allow extensions to the JNLP specification */ private boolean allowExtensions; // true if extensions to JNLP spec are ok - /** * Create a parser for the JNLP file. If the location * parameters is not null it is used as the default codebase @@ -128,7 +125,7 @@ class Parser { // JNLP tag information this.spec = getVersion(root, "spec", "1.0+"); this.codebase = addSlash(getURL(root, "codebase", base)); - this.base = (codebase!=null) ? codebase : base; // if codebase not specified use default codebase + this.base = (codebase != null) ? codebase : base; // if codebase not specified use default codebase fileLocation = getURL(root, "href", this.base); // ensure version is supported @@ -188,7 +185,7 @@ class Parser { Check check; String checkValue = getAttribute(node, "check", "timeout"); if (checkValue.equals("always")) { - check = Check.ALWAYS; + check = Check.ALWAYS; } else if (checkValue.equals("timeout")) { check = Check.TIMEOUT; } else if (checkValue.equals("background")) { @@ -234,8 +231,7 @@ class Parser { * @throws ParseException if the JNLP file is invalid */ public List<ResourcesDesc> getResources(Node parent, boolean j2se) - throws ParseException - { + throws ParseException { List<ResourcesDesc> result = new ArrayList<ResourcesDesc>(); Node resources[] = getChildNodes(parent, "resources"); @@ -244,7 +240,7 @@ class Parser { throw new ParseException(R("PNoResources")); // create objects from the resources sections - for (int i=0; i < resources.length; i++) + for (int i = 0; i < resources.length; i++) result.add(getResourcesDesc(resources[i], j2se)); return result; @@ -262,7 +258,7 @@ class Parser { // create resources ResourcesDesc resources = - new ResourcesDesc(file, + new ResourcesDesc(file, getLocales(node), splitString(getAttribute(node, "os", null)), splitString(getAttribute(node, "arch", null))); @@ -282,7 +278,7 @@ class Parser { if (strict) throw new ParseException(R("PExtensionHasJ2SE")); if (!j2se) - resources.addResource( getJRE(child) ); + resources.addResource(getJRE(child)); else throw new ParseException(R("PInnerJ2SE")); } @@ -302,13 +298,13 @@ class Parser { } if ("extension".equals(name)) - resources.addResource( getExtension(child) ); + resources.addResource(getExtension(child)); if ("property".equals(name)) - resources.addResource( getProperty(child) ); + resources.addResource(getProperty(child)); if ("package".equals(name)) - resources.addResource( getPackage(child) ); + resources.addResource(getPackage(child)); child = child.getNextSibling(); } @@ -325,7 +321,7 @@ class Parser { public JREDesc getJRE(Node node) throws ParseException { Version version = getVersion(node, "version", null); URL location = getURL(node, "href", base); - String vmArgs = getAttribute(node, "java-vm-args",null); + String vmArgs = getAttribute(node, "java-vm-args", null); try { checkVMArgs(vmArgs); } catch (IllegalArgumentException argumentException) { @@ -341,8 +337,6 @@ class Parser { return new JREDesc(version, location, vmArgs, initialHeap, maxHeap, resources); } - - /** * Returns the JAR element at the specified node. * @@ -380,7 +374,7 @@ class Parser { ExtensionDesc ext = new ExtensionDesc(name, version, location); Node dload[] = getChildNodes(node, "ext-download"); - for (int i=0; i < dload.length; i++) { + for (int i = 0; i < dload.length; i++) { boolean lazy = "lazy".equals(getAttribute(dload[i], "download", "eager")); ext.addPart(getRequiredAttribute(dload[i], "ext-part", null), @@ -430,8 +424,7 @@ class Parser { * @throws ParseException if the JNLP file is invalid */ public List<InformationDesc> getInfo(Node parent) - throws ParseException - { + throws ParseException { List<InformationDesc> result = new ArrayList<InformationDesc>(); Node info[] = getChildNodes(parent, "information"); @@ -440,7 +433,7 @@ class Parser { throw new ParseException(R("PNoInfoElement")); // create objects from the info sections - for (int i=0; i < info.length; i++) + for (int i = 0; i < info.length; i++) result.add(getInformationDesc(info[i])); return result; @@ -515,12 +508,12 @@ class Parser { * @param value the info object to add (icon or string) */ protected void addInfo(InformationDesc info, Node node, String mod, Object value) { - String modStr = (mod == null) ? "" : "-"+mod; + String modStr = (mod == null) ? "" : "-" + mod; if (node == null) return; - info.addItem(node.getNodeName()+modStr, value); + info.addItem(node.getNodeName() + modStr, value); } /** @@ -586,7 +579,7 @@ class Parser { if (security != null) if (getChildNode(security, "all-permissions") != null - || getChildNode(security, "j2ee-application-client-permissions") != null) + || getChildNode(security, "j2ee-application-client-permissions") != null) return true; return false; @@ -606,8 +599,8 @@ class Parser { public Object getLauncher(Node parent) throws ParseException { // check for other than one application type if (1 < getChildNodes(parent, "applet-desc").length - + getChildNodes(parent, "application-desc").length - + getChildNodes(parent, "installer-desc").length) + + getChildNodes(parent, "application-desc").length + + getChildNodes(parent, "installer-desc").length) throw new ParseException(R("PTwoDescriptors")); Node child = parent.getFirstChild(); @@ -637,15 +630,14 @@ class Parser { String name = getRequiredAttribute(node, "name", R("PUnknownApplet")); String main = getRequiredAttribute(node, "main-class", null); URL docbase = getURL(node, "documentbase", base); - Map<String,String> paramMap = new HashMap<String,String>(); + Map<String, String> paramMap = new HashMap<String, String>(); int width = 0; int height = 0; try { width = Integer.parseInt(getRequiredAttribute(node, "width", "100")); height = Integer.parseInt(getRequiredAttribute(node, "height", "100")); - } - catch (NumberFormatException nfe) { + } catch (NumberFormatException nfe) { if (width <= 0) throw new ParseException(R("PBadWidth")); throw new ParseException(R("PBadWidth")); @@ -653,7 +645,7 @@ class Parser { // read params Node params[] = getChildNodes(node, "param"); - for (int i=0; i < params.length; i++) { + for (int i = 0; i < params.length; i++) { paramMap.put(getRequiredAttribute(params[i], "name", null), getRequiredAttribute(params[i], "value", "")); } @@ -675,14 +667,14 @@ class Parser { // read parameters Node args[] = getChildNodes(node, "argument"); - for (int i=0; i < args.length; i++) { + for (int i = 0; i < args.length; i++) { //argsList.add( args[i].getNodeValue() ); //This approach was not finding the argument text - argsList.add( getSpanText(args[i]) ); + argsList.add(getSpanText(args[i])); } - String argStrings[] = argsList.toArray( new String[argsList.size()] ); + String argStrings[] = argsList.toArray(new String[argsList.size()]); return new ApplicationDesc(main, argStrings); } @@ -749,7 +741,7 @@ class Parser { throw new ParseException(R("PTwoDesktops")); } showOnDesktop = true; - } else if ("menu".equals(name)){ + } else if ("menu".equals(name)) { if (menu != null && strict) { throw new ParseException(R("PTwoMenus")); } @@ -775,7 +767,6 @@ class Parser { return new MenuDesc(subMenu); } - /** * Returns the related-content descriptor. */ @@ -844,21 +835,22 @@ class Parser { while (true) { part.append(st.nextToken()); - if (st.hasMoreTokens() && part.charAt(part.length()-1) == '\\') - part.setCharAt(part.length()-1, ' '); // join with the space + if (st.hasMoreTokens() && part.charAt(part.length() - 1) == '\\') + part.setCharAt(part.length() - 1, ' '); // join with the space else break; // bizarre while format gets \ at end of string right (no extra space added at end) } // delete \ quote chars - for (int i = part.length(); i-- > 0;) // sweet syntax for reverse loop + for (int i = part.length(); i-- > 0;) + // sweet syntax for reverse loop if (part.charAt(i) == '\\') part.deleteCharAt(i--); // and skip previous char so \\ becomes \ - result.add( part.toString() ); + result.add(part.toString()); } - return result.toArray(new String[result.size()] ); + return result.toArray(new String[result.size()]); } /** @@ -869,15 +861,15 @@ class Parser { public Locale[] getLocales(Node node) { List<Locale> locales = new ArrayList<Locale>(); String localeParts[] = - splitString(getAttribute(node, "locale", "")); + splitString(getAttribute(node, "locale", "")); - for (int i=0; i < localeParts.length; i++) { - Locale l = getLocale( localeParts[i] ); + for (int i = 0; i < localeParts.length; i++) { + Locale l = getLocale(localeParts[i]); if (l != null) locales.add(l); } - return locales.toArray(new Locale[locales.size()] ); + return locales.toArray(new Locale[locales.size()]); } /** @@ -890,15 +882,13 @@ class Parser { return null; String language = localeStr.substring(0, 2); - String country = (localeStr.length()<5) ? "" : localeStr.substring(3, 5); - String variant = (localeStr.length()<7) ? "" : localeStr.substring(6, 8); + String country = (localeStr.length() < 5) ? "" : localeStr.substring(3, 5); + String variant = (localeStr.length() < 7) ? "" : localeStr.substring(6, 8); // null is not allowed n locale but "" is return new Locale(language, country, variant); } - - // XML junk /** @@ -954,10 +944,9 @@ class Parser { child = child.getNextSibling(); } - return result.toArray( new Node[result.size()] ); + return result.toArray(new Node[result.size()]); } - /** * Returns a URL with a trailing / appended to it if there is no * trailing slash on the specifed URL. @@ -968,16 +957,14 @@ class Parser { if (!source.toString().endsWith("/")) { try { - source = new URL(source.toString()+"/"); - } - catch (MalformedURLException ex) { + source = new URL(source.toString() + "/"); + } catch (MalformedURLException ex) { } } return source; } - /** * Returns the same result as getURL except that a * ParseException is thrown if the attribute is null or empty. @@ -995,7 +982,6 @@ class Parser { return getURL(node, name, base); } - /** * Returns a URL object from a href string relative to the * code base. If the href denotes a relative URL, it must @@ -1018,23 +1004,21 @@ class Parser { else { try { return new URL(href); - } - catch (MalformedURLException ex) { + } catch (MalformedURLException ex) { // is relative } URL result = new URL(base, href); // check for going above the codebase - if (! result.toString().startsWith( base.toString()) ) + if (!result.toString().startsWith(base.toString())) if (strict) throw new ParseException(R("PUrlNotInCodebase", node.getNodeName(), href, base)); return result; } - } - catch (MalformedURLException ex) { + } catch (MalformedURLException ex) { if (base == null) throw new ParseException(R("PBadNonrelativeUrl", node.getNodeName(), href)); else @@ -1074,13 +1058,13 @@ class Parser { String[] arguments = vmArgs.split(" "); boolean argumentIsValid = false; - for (String argument: arguments) { + for (String argument : arguments) { argumentIsValid = false; if (validArguments.contains(argument)) { argumentIsValid = true; } else { - for (String validStartingArgument: validStartingArguments) { + for (String validStartingArgument : validStartingArguments) { if (argument.startsWith(validStartingArgument)) { argumentIsValid = true; break; @@ -1102,33 +1086,33 @@ class Parser { */ private String[] getValidVMArguments() { return new String[] { - "-d32", /* use a 32-bit data model if available */ - "-client", /* to select the client VM */ - "-server", /* to select the server VM */ - "-verbose", /* enable verbose output */ - "-version", /* print product version and exit */ - "-showversion", /* print product version and continue */ - "-help", /* print this help message */ - "-X", /* print help on non-standard options */ - "-ea", /* enable assertions */ - "-enableassertions", /* enable assertions */ - "-da", /* disable assertions */ - "-disableassertions", /* disable assertions */ - "-esa", /* enable system assertions */ - "-enablesystemassertions", /* enable system assertions */ - "-dsa", /* disable system assertione */ - "-disablesystemassertions", /* disable system assertione */ - "-Xmixed", /* mixed mode execution (default) */ - "-Xint", /* interpreted mode execution only */ - "-Xnoclassgc", /* disable class garbage collection */ - "-Xincgc", /* enable incremental garbage collection */ - "-Xbatch", /* disable background compilation */ - "-Xprof", /* output cpu profiling data */ - "-Xdebug", /* enable remote debugging */ - "-Xfuture", /* enable strictest checks, anticipating future default */ - "-Xrs", /* reduce use of OS signals by Java/VM (see documentation) */ - "-XX:+ForceTimeHighResolution", /* use high resolution timer */ - "-XX:-ForceTimeHighResolution", /* use low resolution (default) */ + "-d32", /* use a 32-bit data model if available */ + "-client", /* to select the client VM */ + "-server", /* to select the server VM */ + "-verbose", /* enable verbose output */ + "-version", /* print product version and exit */ + "-showversion", /* print product version and continue */ + "-help", /* print this help message */ + "-X", /* print help on non-standard options */ + "-ea", /* enable assertions */ + "-enableassertions", /* enable assertions */ + "-da", /* disable assertions */ + "-disableassertions", /* disable assertions */ + "-esa", /* enable system assertions */ + "-enablesystemassertions", /* enable system assertions */ + "-dsa", /* disable system assertione */ + "-disablesystemassertions", /* disable system assertione */ + "-Xmixed", /* mixed mode execution (default) */ + "-Xint", /* interpreted mode execution only */ + "-Xnoclassgc", /* disable class garbage collection */ + "-Xincgc", /* enable incremental garbage collection */ + "-Xbatch", /* disable background compilation */ + "-Xprof", /* output cpu profiling data */ + "-Xdebug", /* enable remote debugging */ + "-Xfuture", /* enable strictest checks, anticipating future default */ + "-Xrs", /* reduce use of OS signals by Java/VM (see documentation) */ + "-XX:+ForceTimeHighResolution", /* use high resolution timer */ + "-XX:-ForceTimeHighResolution", /* use low resolution (default) */ }; } @@ -1140,26 +1124,26 @@ class Parser { */ private String[] getValidStartingVMArguments() { return new String[] { - "-ea", /* enable assertions for classes */ - "-enableassertions", /* enable assertions for classes */ - "-da", /* disable assertions for classes */ - "-disableassertions", /* disable assertions for classes */ - "-verbose", /* enable verbose output */ - "-Xms", /* set initial Java heap size */ - "-Xmx", /* set maximum Java heap size */ - "-Xss", /* set java thread stack size */ - "-XX:NewRatio", /* set Ratio of new/old gen sizes */ - "-XX:NewSize", /* set initial size of new generation */ - "-XX:MaxNewSize", /* set max size of new generation */ - "-XX:PermSize", /* set initial size of permanent gen */ - "-XX:MaxPermSize", /* set max size of permanent gen */ - "-XX:MaxHeapFreeRatio", /* heap free percentage (default 70) */ - "-XX:MinHeapFreeRatio", /* heap free percentage (default 40) */ - "-XX:UseSerialGC", /* use serial garbage collection */ - "-XX:ThreadStackSize", /* thread stack size (in KB) */ - "-XX:MaxInlineSize", /* set max num of bytecodes to inline */ - "-XX:ReservedCodeCacheSize", /* Reserved code cache size (bytes) */ - "-XX:MaxDirectMemorySize", + "-ea", /* enable assertions for classes */ + "-enableassertions", /* enable assertions for classes */ + "-da", /* disable assertions for classes */ + "-disableassertions", /* disable assertions for classes */ + "-verbose", /* enable verbose output */ + "-Xms", /* set initial Java heap size */ + "-Xmx", /* set maximum Java heap size */ + "-Xss", /* set java thread stack size */ + "-XX:NewRatio", /* set Ratio of new/old gen sizes */ + "-XX:NewSize", /* set initial size of new generation */ + "-XX:MaxNewSize", /* set max size of new generation */ + "-XX:PermSize", /* set initial size of permanent gen */ + "-XX:MaxPermSize", /* set max size of permanent gen */ + "-XX:MaxHeapFreeRatio", /* heap free percentage (default 70) */ + "-XX:MinHeapFreeRatio", /* heap free percentage (default 40) */ + "-XX:UseSerialGC", /* use serial garbage collection */ + "-XX:ThreadStackSize", /* thread stack size (in KB) */ + "-XX:MaxInlineSize", /* set max num of bytecodes to inline */ + "-XX:ReservedCodeCacheSize", /* Reserved code cache size (bytes) */ + "-XX:MaxDirectMemorySize", }; } @@ -1200,7 +1184,7 @@ class Parser { // String result = ((Element) node).getAttribute(name); String result = node.getAttribute(name); - if (result == null || result.length()==0) + if (result == null || result.length() == 0) return defaultValue; return result; @@ -1242,22 +1226,20 @@ class Parser { // Clean the jnlp xml file of all comments before passing // it to the parser. new Thread( - new Runnable(){ - public void run(){ - (new XMLElement()).sanitizeInput(isr, pout); - try { - pout.close(); - } catch (IOException ioe) { - ioe.printStackTrace(); + new Runnable() { + public void run() { + (new XMLElement()).sanitizeInput(isr, pout); + try { + pout.close(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } } - } - } - ).start(); + }).start(); xml.parseFromReader(new InputStreamReader(pin)); Node jnlpNode = new Node(xml); return jnlpNode; - } - catch(Exception ex) { + } catch (Exception ex) { throw new ParseException(R("PBadXML"), ex); } } @@ -1268,7 +1250,7 @@ class Parser { * @param input the InputStream * @return a String representation of encoding */ - private static String getEncoding(InputStream input) throws IOException{ + private static String getEncoding(InputStream input) throws IOException { //Fixme: This only recognizes UTF-8, UTF-16, and //UTF-32, which is enough to parse the prolog portion of xml to //find out the exact encoding (if it exists). The reason being @@ -1300,26 +1282,26 @@ class Parser { } } } else if (s[0] == 254 && s[1] == 255 && (s[2] != 0 || - s[3] != 0)) { + s[3] != 0)) { encoding = "UTF-16"; } else if (s[0] == 0 && s[1] == 0 && s[2] == 254 && - s[3] == 255) { + s[3] == 255) { encoding = "X-UTF-32BE-BOM"; } else if (s[0] == 0 && s[1] == 0 && s[2] == 0 && - s[3] == 60) { + s[3] == 60) { encoding = "UTF-32BE"; } else if (s[0] == 60 && s[1] == 0 && s[2] == 0 && - s[3] == 0) { + s[3] == 0) { encoding = "UTF-32LE"; } else if (s[0] == 0 && s[1] == 60 && s[2] == 0 && - s[3] == 63) { + s[3] == 63) { encoding = "UTF-16BE"; } else if (s[0] == 60 && s[1] == 0 && s[2] == 63 && - s[3] == 0) { + s[3] == 0) { encoding = "UTF-16LE"; } diff --git a/netx/net/sourceforge/jnlp/PluginBridge.java b/netx/net/sourceforge/jnlp/PluginBridge.java index 56538e7..75e96e5 100644 --- a/netx/net/sourceforge/jnlp/PluginBridge.java +++ b/netx/net/sourceforge/jnlp/PluginBridge.java @@ -34,33 +34,30 @@ import java.util.Map; import net.sourceforge.jnlp.runtime.JNLPRuntime; - -public class PluginBridge extends JNLPFile -{ +public class PluginBridge extends JNLPFile { String name; String[] jars = new String[0]; String[] cacheJars = new String[0]; String[] cacheExJars = new String[0]; - Hashtable<String,String> atts; + Hashtable<String, String> atts; public PluginBridge(URL codebase, URL documentBase, String jar, String main, - int width, int height, Hashtable<String,String> atts) - throws Exception - { + int width, int height, Hashtable<String, String> atts) + throws Exception { specVersion = new Version("1.0"); fileVersion = new Version("1.1"); this.codeBase = codebase; this.sourceLocation = documentBase; - if (atts.containsKey("jnlp_href")){ + if (atts.containsKey("jnlp_href")) { try { URL jnlp = new URL(codeBase.toExternalForm() + atts.get("jnlp_href")); JNLPFile jnlpFile = new JNLPFile(jnlp); - Map<String,String> jnlpParams = jnlpFile.getApplet().getParameters(); + Map<String, String> jnlpParams = jnlpFile.getApplet().getParameters(); // Change the parameter name to lowercase to follow conventions. - for (Map.Entry<String,String> entry : jnlpParams.entrySet()){ + for (Map.Entry<String, String> entry : jnlpParams.entrySet()) { atts.put(entry.getKey().toLowerCase(), entry.getValue()); } } catch (MalformedURLException e) { @@ -86,7 +83,7 @@ public class PluginBridge extends JNLPFile String[] jars = cacheArchive.split(","); cacheJars = new String[jars.length]; - for (int i=0; i < jars.length; i++) { + for (int i = 0; i < jars.length; i++) { cacheJars[i] = jars[i].trim(); @@ -103,10 +100,10 @@ public class PluginBridge extends JNLPFile if (jar != null && jar.length() > 0) { this.jars = jar.split(","); - + // trim white spaces - for (int i =0; i < this.jars.length; i++) { - this.jars[i] = this.jars[i].trim(); + for (int i = 0; i < this.jars.length; i++) { + this.jars[i] = this.jars[i].trim(); } if (JNLPRuntime.isDebug()) { @@ -139,16 +136,13 @@ public class PluginBridge extends JNLPFile documentBase; } - public String getTitle() - { + public String getTitle() { return name; } - public InformationDesc getInformation(final Locale locale) - { - return new InformationDesc(this, new Locale[] {locale}) { - protected List<Object> getItems(Object key) - { + public InformationDesc getInformation(final Locale locale) { + return new InformationDesc(this, new Locale[] { locale }) { + protected List<Object> getItems(Object key) { // Should we populate this list with applet attribute tags? return new ArrayList<Object>(); } @@ -156,19 +150,15 @@ public class PluginBridge extends JNLPFile } public ResourcesDesc getResources(final Locale locale, final String os, - final String arch) - { - return new ResourcesDesc(this, new Locale[] {locale}, new String[] {os}, - new String[] {arch}) { + final String arch) { + return new ResourcesDesc(this, new Locale[] { locale }, new String[] { os }, + new String[] { arch }) { @Override - public <T> List<T> getResources(Class<T> launchType) - { + public <T> List<T> getResources(Class<T> launchType) { // Need to add the JAR manually... //should this be done to sharedResources on init? - if (launchType.equals(JARDesc.class)) - { - try - { + if (launchType.equals(JARDesc.class)) { + try { List<JARDesc> jarDescs = new ArrayList<JARDesc>(); jarDescs.addAll(sharedResources.getResources(JARDesc.class)); @@ -233,13 +223,13 @@ public class PluginBridge extends JNLPFile } // We know this is a safe list of JarDesc objects @SuppressWarnings("unchecked") - List<T> result = (List<T>) jarDescs; + List<T> result = (List<T>) jarDescs; return result; + } catch (MalformedURLException ex) { /* Ignored */ } - catch (MalformedURLException ex) { /* Ignored */ } } return sharedResources.getResources(launchType); - } + } @Override public JARDesc[] getJARs() { @@ -247,8 +237,7 @@ public class PluginBridge extends JNLPFile return jarDescs.toArray(new JARDesc[jarDescs.size()]); } - public void addResource(Object resource) - { + public void addResource(Object resource) { // todo: honor the current locale, os, arch values sharedResources.addResource(resource); } @@ -259,12 +248,15 @@ public class PluginBridge extends JNLPFile public boolean isApplet() { return true; } + public boolean isApplication() { return false; } + public boolean isComponent() { return false; } + public boolean isInstaller() { return false; } diff --git a/netx/net/sourceforge/jnlp/PropertyDesc.java b/netx/net/sourceforge/jnlp/PropertyDesc.java index c96b748..14248a8 100644 --- a/netx/net/sourceforge/jnlp/PropertyDesc.java +++ b/netx/net/sourceforge/jnlp/PropertyDesc.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp; import java.io.*; @@ -35,7 +34,6 @@ public class PropertyDesc { /** the value */ private String value; - /** * Creates a property descriptor. * diff --git a/netx/net/sourceforge/jnlp/ResourcesDesc.java b/netx/net/sourceforge/jnlp/ResourcesDesc.java index ca6f1dd..abd3e35 100644 --- a/netx/net/sourceforge/jnlp/ResourcesDesc.java +++ b/netx/net/sourceforge/jnlp/ResourcesDesc.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp; import java.io.*; @@ -44,6 +43,7 @@ public class ResourcesDesc { /** list of jars, packages, properties, and extensions */ private List<Object> resources = new ArrayList<Object>(); + // mixed list makes easier for lookup code /** @@ -67,7 +67,7 @@ public class ResourcesDesc { */ public JREDesc[] getJREs() { List<JREDesc> resources = getResources(JREDesc.class); - return resources.toArray( new JREDesc[resources.size()] ); + return resources.toArray(new JREDesc[resources.size()]); } /** @@ -78,7 +78,7 @@ public class ResourcesDesc { public JARDesc getMainJAR() { JARDesc jars[] = getJARs(); - for (int i=0; i < jars.length; i++) + for (int i = 0; i < jars.length; i++) if (jars[i].isMain()) return jars[i]; @@ -93,7 +93,7 @@ public class ResourcesDesc { */ public JARDesc[] getJARs() { List<JARDesc> resources = getResources(JARDesc.class); - return resources.toArray( new JARDesc[resources.size()] ); + return resources.toArray(new JARDesc[resources.size()]); } /** @@ -107,11 +107,11 @@ public class ResourcesDesc { for (int i = resources.size(); i-- > 0;) { JARDesc jar = resources.get(i); - if (!(""+jar.getPart()).equals(""+partName)) + if (!("" + jar.getPart()).equals("" + partName)) resources.remove(i); } - return resources.toArray( new JARDesc[resources.size()] ); + return resources.toArray(new JARDesc[resources.size()]); } /** @@ -119,7 +119,7 @@ public class ResourcesDesc { */ public ExtensionDesc[] getExtensions() { List<ExtensionDesc> resources = getResources(ExtensionDesc.class); - return resources.toArray( new ExtensionDesc[resources.size()] ); + return resources.toArray(new ExtensionDesc[resources.size()]); } /** @@ -127,7 +127,7 @@ public class ResourcesDesc { */ public PackageDesc[] getPackages() { List<PackageDesc> resources = getResources(PackageDesc.class); - return resources.toArray( new PackageDesc[resources.size()] ); + return resources.toArray(new PackageDesc[resources.size()]); } /** @@ -146,7 +146,7 @@ public class ResourcesDesc { resources.remove(i); } - return resources.toArray( new PackageDesc[resources.size()] ); + return resources.toArray(new PackageDesc[resources.size()]); } /** @@ -154,18 +154,18 @@ public class ResourcesDesc { */ public PropertyDesc[] getProperties() { List<PropertyDesc> resources = getResources(PropertyDesc.class); - return resources.toArray( new PropertyDesc[resources.size()] ); + return resources.toArray(new PropertyDesc[resources.size()]); } /** * Returns the properties as a map. */ - public Map<String,String> getPropertiesMap() { - Map<String,String> properties = new HashMap<String,String>(); + public Map<String, String> getPropertiesMap() { + Map<String, String> properties = new HashMap<String, String>(); List<PropertyDesc> resources = getResources(PropertyDesc.class); - for (int i=0; i < resources.size(); i++) { + for (int i = 0; i < resources.size(); i++) { PropertyDesc prop = resources.get(i); - properties.put( prop.getKey(), prop.getValue() ); + properties.put(prop.getKey(), prop.getValue()); } return properties; @@ -208,8 +208,8 @@ public class ResourcesDesc { public <T> List<T> getResources(Class<T> type) { List<T> result = new ArrayList<T>(); - for (int i=0; i < resources.size(); i++) - if ( type.isAssignableFrom(resources.get(i).getClass()) ) + for (int i = 0; i < resources.size(); i++) + if (type.isAssignableFrom(resources.get(i).getClass())) result.add(type.cast(resources.get(i))); return result; diff --git a/netx/net/sourceforge/jnlp/SecurityDesc.java b/netx/net/sourceforge/jnlp/SecurityDesc.java index c5ddec4..c695bec 100644 --- a/netx/net/sourceforge/jnlp/SecurityDesc.java +++ b/netx/net/sourceforge/jnlp/SecurityDesc.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp; import java.io.*; @@ -67,75 +66,75 @@ public class SecurityDesc { /** basic permissions for restricted mode */ private static Permission j2eePermissions[] = { - new AWTPermission("accessClipboard"), - // disabled because we can't at this time prevent an - // application from accessing other applications' event - // queues, or even prevent access to security dialog queues. - // - // new AWTPermission("accessEventQueue"), - new RuntimePermission("exitVM"), - new RuntimePermission("loadLibrary"), - new RuntimePermission("queuePrintJob"), - new SocketPermission("*", "connect"), - new SocketPermission("localhost:1024-", "accept, listen"), - new FilePermission("*", "read, write"), - new PropertyPermission("*", "read"), + new AWTPermission("accessClipboard"), + // disabled because we can't at this time prevent an + // application from accessing other applications' event + // queues, or even prevent access to security dialog queues. + // + // new AWTPermission("accessEventQueue"), + new RuntimePermission("exitVM"), + new RuntimePermission("loadLibrary"), + new RuntimePermission("queuePrintJob"), + new SocketPermission("*", "connect"), + new SocketPermission("localhost:1024-", "accept, listen"), + new FilePermission("*", "read, write"), + new PropertyPermission("*", "read"), }; /** basic permissions for restricted mode */ private static Permission sandboxPermissions[] = { - new SocketPermission("localhost:1024-", "listen"), - // new SocketPermission("<DownloadHost>", "connect, accept"), // added by code - new PropertyPermission("java.version", "read"), - new PropertyPermission("java.vendor", "read"), - new PropertyPermission("java.vendor.url", "read"), - new PropertyPermission("java.class.version", "read"), - new PropertyPermission("os.name", "read"), - new PropertyPermission("os.version", "read"), - new PropertyPermission("os.arch", "read"), - new PropertyPermission("file.separator", "read"), - new PropertyPermission("path.separator", "read"), - new PropertyPermission("line.separator", "read"), - new PropertyPermission("java.specification.version", "read"), - new PropertyPermission("java.specification.vendor", "read"), - new PropertyPermission("java.specification.name", "read"), - new PropertyPermission("java.vm.specification.vendor", "read"), - new PropertyPermission("java.vm.specification.name", "read"), - new PropertyPermission("java.vm.version", "read"), - new PropertyPermission("java.vm.vendor", "read"), - new PropertyPermission("java.vm.name", "read"), - new PropertyPermission("javawebstart.version", "read"), - new PropertyPermission("javaplugin.*", "read"), - new PropertyPermission("jnlp.*", "read,write"), - new PropertyPermission("javaws.*", "read,write"), - new RuntimePermission("exitVM"), - new RuntimePermission("stopThread"), + new SocketPermission("localhost:1024-", "listen"), + // new SocketPermission("<DownloadHost>", "connect, accept"), // added by code + new PropertyPermission("java.version", "read"), + new PropertyPermission("java.vendor", "read"), + new PropertyPermission("java.vendor.url", "read"), + new PropertyPermission("java.class.version", "read"), + new PropertyPermission("os.name", "read"), + new PropertyPermission("os.version", "read"), + new PropertyPermission("os.arch", "read"), + new PropertyPermission("file.separator", "read"), + new PropertyPermission("path.separator", "read"), + new PropertyPermission("line.separator", "read"), + new PropertyPermission("java.specification.version", "read"), + new PropertyPermission("java.specification.vendor", "read"), + new PropertyPermission("java.specification.name", "read"), + new PropertyPermission("java.vm.specification.vendor", "read"), + new PropertyPermission("java.vm.specification.name", "read"), + new PropertyPermission("java.vm.version", "read"), + new PropertyPermission("java.vm.vendor", "read"), + new PropertyPermission("java.vm.name", "read"), + new PropertyPermission("javawebstart.version", "read"), + new PropertyPermission("javaplugin.*", "read"), + new PropertyPermission("jnlp.*", "read,write"), + new PropertyPermission("javaws.*", "read,write"), + new RuntimePermission("exitVM"), + new RuntimePermission("stopThread"), // disabled because we can't at this time prevent an // application from accessing other applications' event // queues, or even prevent access to security dialog queues. // // new AWTPermission("accessEventQueue"), - }; + }; /** basic permissions for restricted mode */ private static Permission jnlpRIAPermissions[] = { - new PropertyPermission("awt.useSystemAAFontSettings", "read,write"), - new PropertyPermission("http.agent", "read,write"), - new PropertyPermission("http.keepAlive", "read,write"), - new PropertyPermission("java.awt.syncLWRequests", "read,write"), - new PropertyPermission("java.awt.Window.locationByPlatform", "read,write"), - new PropertyPermission("javaws.cfg.jauthenticator", "read,write"), - new PropertyPermission("javax.swing.defaultlf", "read,write"), - new PropertyPermission("sun.awt.noerasebackground", "read,write"), - new PropertyPermission("sun.awt.erasebackgroundonresize", "read,write"), - new PropertyPermission("sun.java2d.d3d", "read,write"), - new PropertyPermission("sun.java2d.dpiaware", "read,write"), - new PropertyPermission("sun.java2d.noddraw", "read,write"), - new PropertyPermission("sun.java2d.opengl", "read,write"), - new PropertyPermission("swing.boldMetal", "read,write"), - new PropertyPermission("swing.metalTheme", "read,write"), - new PropertyPermission("swing.noxp", "read,write"), - new PropertyPermission("swing.useSystemFontSettings", "read,write"), + new PropertyPermission("awt.useSystemAAFontSettings", "read,write"), + new PropertyPermission("http.agent", "read,write"), + new PropertyPermission("http.keepAlive", "read,write"), + new PropertyPermission("java.awt.syncLWRequests", "read,write"), + new PropertyPermission("java.awt.Window.locationByPlatform", "read,write"), + new PropertyPermission("javaws.cfg.jauthenticator", "read,write"), + new PropertyPermission("javax.swing.defaultlf", "read,write"), + new PropertyPermission("sun.awt.noerasebackground", "read,write"), + new PropertyPermission("sun.awt.erasebackgroundonresize", "read,write"), + new PropertyPermission("sun.java2d.d3d", "read,write"), + new PropertyPermission("sun.java2d.dpiaware", "read,write"), + new PropertyPermission("sun.java2d.noddraw", "read,write"), + new PropertyPermission("sun.java2d.opengl", "read,write"), + new PropertyPermission("swing.boldMetal", "read,write"), + new PropertyPermission("swing.metalTheme", "read,write"), + new PropertyPermission("swing.noxp", "read,write"), + new PropertyPermission("swing.useSystemFontSettings", "read,write"), }; /** @@ -178,7 +177,7 @@ public class SecurityDesc { // add j2ee to sandbox if needed if (type == J2EE_PERMISSIONS) - for (int i=0; i < j2eePermissions.length; i++) + for (int i = 0; i < j2eePermissions.length; i++) permissions.add(j2eePermissions[i]); return permissions; @@ -191,7 +190,7 @@ public class SecurityDesc { Permissions permissions = new Permissions(); - for (int i=0; i < sandboxPermissions.length; i++) + for (int i = 0; i < sandboxPermissions.length; i++) permissions.add(sandboxPermissions[i]); if (grantAwtPermissions) { @@ -199,7 +198,7 @@ public class SecurityDesc { } if (file.isApplication()) - for (int i=0; i < jnlpRIAPermissions.length; i++) + for (int i = 0; i < jnlpRIAPermissions.length; i++) permissions.add(jnlpRIAPermissions[i]); if (downloadHost != null) diff --git a/netx/net/sourceforge/jnlp/Version.java b/netx/net/sourceforge/jnlp/Version.java index 1a48a86..f4ccc1a 100644 --- a/netx/net/sourceforge/jnlp/Version.java +++ b/netx/net/sourceforge/jnlp/Version.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp; import java.io.*; @@ -57,7 +56,6 @@ public class Version { /** contains all the versions matched */ private String versionString; - /** * Create a Version object based on a version string (ie, * "1.2.3+ 4.56*"). @@ -96,8 +94,8 @@ public class Version { public boolean matches(Version version) { List<String> versionStrings = version.getVersionStrings(); - for (int i=0; i < versionStrings.size(); i++) { - if (!this.matchesSingle(versionStrings.get(i) )) + for (int i = 0; i < versionStrings.size(); i++) { + if (!this.matchesSingle(versionStrings.get(i))) return false; } @@ -114,7 +112,6 @@ public class Version { return matches(new Version(version)); } - /** * Returns true if any of this version's version-ids match one * or more of the specifed version's version-id. @@ -124,8 +121,8 @@ public class Version { public boolean matchesAny(Version version) { List<String> versionStrings = version.getVersionStrings(); - for (int i=0; i < versionStrings.size(); i++) { - if (this.matchesSingle( versionStrings.get(i) )) + for (int i = 0; i < versionStrings.size(); i++) { + if (this.matchesSingle(versionStrings.get(i))) return true; } @@ -140,14 +137,13 @@ public class Version { */ private boolean matchesSingle(String version) { List<String> versionStrings = this.getVersionStrings(); - for (int i=0; i < versionStrings.size(); i++) { - if ( matches(version, versionStrings.get(i)) ) + for (int i = 0; i < versionStrings.size(); i++) { + if (matches(version, versionStrings.get(i))) return true; } return false; } - /** * Returns whether a single version string is supported by * another single version string. @@ -185,8 +181,8 @@ public class Version { * @param parts2 normalized version parts */ protected boolean equal(List<String> parts1, List<String> parts2) { - for (int i=0; i < parts1.size(); i++) { - if ( 0 != compare(parts1.get(i), parts2.get(i)) ) + for (int i = 0; i < parts1.size(); i++) { + if (0 != compare(parts1.get(i), parts2.get(i))) return false; } @@ -203,7 +199,7 @@ public class Version { protected boolean greater(List<String> parts1, List<String> parts2) { //if (true) return false; - for (int i=0; i < parts1.size(); i++) { + for (int i = 0; i < parts1.size(); i++) { // if part1 > part2 then it's a later version, so return true if (compare(parts1.get(i), parts2.get(i)) > 0) return true; @@ -244,8 +240,7 @@ public class Version { number2 = Integer.valueOf(part2); return number1.compareTo(number2); - } - catch (NumberFormatException ex) { + } catch (NumberFormatException ex) { // means to compare as strings } @@ -275,11 +270,11 @@ public class Version { for (List<String> vers : versions) { // remove excess elements while (vers.size() > length) - vers.remove( vers.size()-1 ); + vers.remove(vers.size() - 1); // add in empty pad elements while (vers.size() < length) - vers.add( emptyString ); + vers.add(emptyString); } } @@ -291,7 +286,7 @@ public class Version { StringTokenizer st = new StringTokenizer(versionString, " "); while (st.hasMoreTokens()) - strings.add( st.nextToken() ); + strings.add(st.nextToken()); return strings; } @@ -304,9 +299,9 @@ public class Version { protected List<String> getParts(String oneVersion) { ArrayList<String> strings = new ArrayList<String>(); - StringTokenizer st = new StringTokenizer(oneVersion, seperators+"+*"); + StringTokenizer st = new StringTokenizer(oneVersion, seperators + "+*"); while (st.hasMoreTokens()) { - strings.add( st.nextToken() ); + strings.add(st.nextToken()); } return strings; diff --git a/netx/net/sourceforge/jnlp/cache/CacheEntry.java b/netx/net/sourceforge/jnlp/cache/CacheEntry.java index d442a90..9299962 100644 --- a/netx/net/sourceforge/jnlp/cache/CacheEntry.java +++ b/netx/net/sourceforge/jnlp/cache/CacheEntry.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.cache; import static net.sourceforge.jnlp.runtime.Translator.R; @@ -47,7 +46,6 @@ public class CacheEntry { /** info about the cached file */ private PropertiesFile properties; - /** * Create a CacheEntry for the resources specified as a remote * URL. @@ -60,7 +58,7 @@ public class CacheEntry { this.version = version; File infoFile = CacheUtil.getCacheFile(location, version); - infoFile = new File(infoFile.getPath()+".info"); // replace with something that can't be clobbered + infoFile = new File(infoFile.getPath() + ".info"); // replace with something that can't be clobbered properties = new PropertiesFile(infoFile, R("CAutoGen")); } @@ -91,8 +89,7 @@ public class CacheEntry { public long getLastUpdated() { try { return Long.parseLong(properties.getProperty("last-updated")); - } - catch (Exception ex) { + } catch (Exception ex) { return 0; } } @@ -127,8 +124,7 @@ public class CacheEntry { return true; else return false; - } - catch (Exception ex) { + } catch (Exception ex) { if (JNLPRuntime.isDebug()) ex.printStackTrace(); @@ -155,8 +151,7 @@ public class CacheEntry { return false; else return true; - } - catch (Exception ex) { + } catch (Exception ex) { if (JNLPRuntime.isDebug()) ex.printStackTrace(); diff --git a/netx/net/sourceforge/jnlp/cache/CacheUtil.java b/netx/net/sourceforge/jnlp/cache/CacheUtil.java index 04b5adc..e316282 100644 --- a/netx/net/sourceforge/jnlp/cache/CacheUtil.java +++ b/netx/net/sourceforge/jnlp/cache/CacheUtil.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.cache; import static net.sourceforge.jnlp.runtime.Translator.R; @@ -49,17 +48,17 @@ public class CacheUtil { * ie sourceforge.net and www.sourceforge.net). */ public static boolean urlEquals(URL u1, URL u2) { - if (u1==u2) + if (u1 == u2) return true; - if (u1==null || u2==null) + if (u1 == null || u2 == null) return false; if (!compare(u1.getProtocol(), u2.getProtocol(), true) || - !compare(u1.getHost(), u2.getHost(), true) || - //u1.getDefaultPort() != u2.getDefaultPort() || // only in 1.4 - !compare(u1.getPath(), u2.getPath(), false) || - !compare(u1.getQuery(), u2.getQuery(), false) || - !compare(u1.getRef(), u2.getRef(), false)) + !compare(u1.getHost(), u2.getHost(), true) || + //u1.getDefaultPort() != u2.getDefaultPort() || // only in 1.4 + !compare(u1.getPath(), u2.getPath(), false) || + !compare(u1.getQuery(), u2.getQuery(), false) || + !compare(u1.getRef(), u2.getRef(), false)) return false; else return true; @@ -82,8 +81,7 @@ public class CacheUtil { File f = rt.getCacheFile(location); // TODO: Should be toURI().toURL() return f.toURL(); - } - catch (MalformedURLException ex) { + } catch (MalformedURLException ex) { return location; } } @@ -92,9 +90,9 @@ public class CacheUtil { * Compare strings that can be null. */ private static boolean compare(String s1, String s2, boolean ignore) { - if (s1==s2) + if (s1 == s2) return true; - if (s1==null || s2==null) + if (s1 == null || s2 == null) return false; if (ignore) @@ -112,16 +110,14 @@ public class CacheUtil { File file = CacheUtil.getCacheFile(location, version); return new FilePermission(file.getPath(), "read"); - } - else { + } else { try { // this is what URLClassLoader does return location.openConnection().getPermission(); - } - catch (java.io.IOException ioe) { + } catch (java.io.IOException ioe) { // should try to figure out the permission if (JNLPRuntime.isDebug()) - ioe.printStackTrace(); + ioe.printStackTrace(); } } @@ -223,11 +219,10 @@ public class CacheUtil { boolean result = entry.isCurrent(connection); if (JNLPRuntime.isDebug()) - System.out.println("isCurrent: "+source+" = "+result); + System.out.println("isCurrent: " + source + " = " + result); return result; - } - catch (Exception ex) { + } catch (Exception ex) { if (JNLPRuntime.isDebug()) ex.printStackTrace(); @@ -252,7 +247,7 @@ public class CacheUtil { boolean result = entry.isCached(); if (JNLPRuntime.isDebug()) - System.out.println("isCached: "+source+" = "+result); + System.out.println("isCached: " + source + " = " + result); return result; } @@ -294,13 +289,12 @@ public class CacheUtil { try { String cacheDir = JNLPRuntime.getConfiguration() - .getProperty(DeploymentConfiguration.KEY_USER_CACHE_DIR); + .getProperty(DeploymentConfiguration.KEY_USER_CACHE_DIR); File localFile = urlToPath(source, cacheDir); localFile.getParentFile().mkdirs(); return localFile; - } - catch (Exception ex) { + } catch (Exception ex) { if (JNLPRuntime.isDebug()) ex.printStackTrace(); @@ -343,8 +337,7 @@ public class CacheUtil { os.write(b, 0, c); } - } - finally { + } finally { is.close(); os.close(); } @@ -378,7 +371,6 @@ public class CacheUtil { return new File(FileUtils.sanitizePath(path.toString())); } - /** * Waits until the resources are downloaded, while showing a * progress indicator. @@ -404,11 +396,11 @@ public class CacheUtil { // only resources not starting out downloaded are displayed List<URL> urlList = new ArrayList<URL>(); - for (int i=0; i < resources.length; i++) { + for (int i = 0; i < resources.length; i++) { if (!tracker.checkResource(resources[i])) urlList.add(resources[i]); } - URL undownloaded[] = urlList.toArray( new URL[urlList.size()] ); + URL undownloaded[] = urlList.toArray(new URL[urlList.size()]); listener = indicator.getListener(app, title, undownloaded); @@ -416,35 +408,32 @@ public class CacheUtil { long read = 0; long total = 0; - for (int i=0; i < undownloaded.length; i++) { + for (int i = 0; i < undownloaded.length; i++) { // add in any -1's; they're insignificant total += tracker.getTotalSize(undownloaded[i]); read += tracker.getAmountRead(undownloaded[i]); } - int percent = (int)( (100*read)/Math.max(1,total) ); + int percent = (int) ((100 * read) / Math.max(1, total)); - for (int i=0; i < undownloaded.length; i++) + for (int i = 0; i < undownloaded.length; i++) listener.progress(undownloaded[i], "version", tracker.getAmountRead(undownloaded[i]), tracker.getTotalSize(undownloaded[i]), percent); - } - while (!tracker.waitForResources(resources, indicator.getUpdateRate())); + } while (!tracker.waitForResources(resources, indicator.getUpdateRate())); // make sure they read 100% until indicator closes - for (int i=0; i < undownloaded.length; i++) + for (int i = 0; i < undownloaded.length; i++) listener.progress(undownloaded[i], "version", tracker.getTotalSize(undownloaded[i]), tracker.getTotalSize(undownloaded[i]), 100); - } - catch (InterruptedException ex) { + } catch (InterruptedException ex) { if (JNLPRuntime.isDebug()) ex.printStackTrace(); - } - finally { + } finally { if (listener != null) indicator.disposeListener(listener); } diff --git a/netx/net/sourceforge/jnlp/cache/DefaultDownloadIndicator.java b/netx/net/sourceforge/jnlp/cache/DefaultDownloadIndicator.java index f7c382e..7472307 100644 --- a/netx/net/sourceforge/jnlp/cache/DefaultDownloadIndicator.java +++ b/netx/net/sourceforge/jnlp/cache/DefaultDownloadIndicator.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.cache; import static net.sourceforge.jnlp.runtime.Translator.R; @@ -100,12 +99,12 @@ public class DefaultDownloadIndicator implements DownloadIndicator { DownloadPanel result = new DownloadPanel(downloadName); if (frame == null) { - frame = new JFrame(downloading+"..."); + frame = new JFrame(downloading + "..."); frame.getContentPane().setLayout(new GridBagLayout()); } if (resources != null) - for (int i=0; i < resources.length; i++) + for (int i = 0; i < resources.length; i++) result.addProgressPanel(resources[i], null); frame.getContentPane().add(result, vertical); @@ -114,10 +113,10 @@ public class DefaultDownloadIndicator implements DownloadIndicator { if (!frame.isVisible()) { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(frame.getGraphicsConfiguration()); - Dimension screen = new Dimension(screenSize.width - insets.left , + Dimension screen = new Dimension(screenSize.width - insets.left, screenSize.height - insets.top); - frame.setLocation(screen.width-frame.getWidth(), - screen.height-frame.getHeight()); + frame.setLocation(screen.width - frame.getWidth(), + screen.height - frame.getHeight()); } frame.setVisible(true); @@ -149,8 +148,6 @@ public class DefaultDownloadIndicator implements DownloadIndicator { timer.start(); } - - /** * Groups the url progress in a panel. */ @@ -168,7 +165,6 @@ public class DefaultDownloadIndicator implements DownloadIndicator { /** list of ProgressPanels */ private List<ProgressPanel> panels = new ArrayList<ProgressPanel>(); - /** * Create a new download panel for with the specified download * name. @@ -226,7 +222,7 @@ public class DefaultDownloadIndicator implements DownloadIndicator { // don't get whole string from resource and sub in // values because it'll be doing a MessageFormat for // each update. - header.setText(downloading+" "+downloadName+": "+percent+"% "+complete+"."); + header.setText(downloading + " " + downloadName + ": " + percent + "% " + complete + "."); } /** @@ -259,8 +255,6 @@ public class DefaultDownloadIndicator implements DownloadIndicator { }; - - /** * A progress bar with the URL next to it. */ @@ -271,10 +265,10 @@ public class DefaultDownloadIndicator implements DownloadIndicator { private long readSoFar; ProgressPanel(URL url, String version) { - JLabel location = new JLabel(" "+url.getHost()+"/"+url.getFile()); + JLabel location = new JLabel(" " + url.getHost() + "/" + url.getFile()); - bar.setMinimumSize(new Dimension(80,15)); - bar.setPreferredSize(new Dimension(80,15)); + bar.setMinimumSize(new Dimension(80, 15)); + bar.setPreferredSize(new Dimension(80, 15)); bar.setOpaque(false); setLayout(new GridBagLayout()); @@ -308,15 +302,14 @@ public class DefaultDownloadIndicator implements DownloadIndicator { if (readSoFar <= 0 || total <= 0) { // make barber pole - } - else { - double progress = (double)readSoFar / (double)total; - int divide = (int)(w * progress); + } else { + double progress = (double) readSoFar / (double) total; + int divide = (int) (w * progress); g.setColor(Color.white); g.fillRect(x, y, w, h); g.setColor(Color.blue); - g.fillRect(x+1, y+1, divide-1, h-1); + g.fillRect(x + 1, y + 1, divide - 1, h - 1); } } }; diff --git a/netx/net/sourceforge/jnlp/cache/DownloadIndicator.java b/netx/net/sourceforge/jnlp/cache/DownloadIndicator.java index a6eecb8..7506392 100644 --- a/netx/net/sourceforge/jnlp/cache/DownloadIndicator.java +++ b/netx/net/sourceforge/jnlp/cache/DownloadIndicator.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.cache; import java.awt.*; diff --git a/netx/net/sourceforge/jnlp/cache/Resource.java b/netx/net/sourceforge/jnlp/cache/Resource.java index 08a31fb..9818b64 100644 --- a/netx/net/sourceforge/jnlp/cache/Resource.java +++ b/netx/net/sourceforge/jnlp/cache/Resource.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.cache; import java.io.*; @@ -169,17 +168,26 @@ public class Resource { private String getStatusString(int flag) { StringBuffer result = new StringBuffer(); - if (flag == 0) result.append("<> "); - if ((flag & CONNECT) != 0) result.append("CONNECT "); - if ((flag & CONNECTING) != 0) result.append("CONNECTING "); - if ((flag & CONNECTED) != 0) result.append("CONNECTED "); - if ((flag & DOWNLOAD) != 0) result.append("DOWNLOAD "); - if ((flag & DOWNLOADING) != 0) result.append("DOWNLOADING "); - if ((flag & DOWNLOADED) != 0) result.append("DOWNLOADED "); - if ((flag & ERROR) != 0) result.append("ERROR "); - if ((flag & STARTED) != 0) result.append("STARTED "); - - return result.deleteCharAt(result.length()-1).toString(); + if (flag == 0) + result.append("<> "); + if ((flag & CONNECT) != 0) + result.append("CONNECT "); + if ((flag & CONNECTING) != 0) + result.append("CONNECTING "); + if ((flag & CONNECTED) != 0) + result.append("CONNECTED "); + if ((flag & DOWNLOAD) != 0) + result.append("DOWNLOAD "); + if ((flag & DOWNLOADING) != 0) + result.append("DOWNLOADING "); + if ((flag & DOWNLOADED) != 0) + result.append("DOWNLOADED "); + if ((flag & ERROR) != 0) + result.append("ERROR "); + if ((flag & STARTED) != 0) + result.append("STARTED "); + + return result.deleteCharAt(result.length() - 1).toString(); } /** @@ -190,7 +198,7 @@ public class Resource { public void changeStatus(int clear, int add) { int orig = 0; - synchronized(this) { + synchronized (this) { orig = status; this.status &= ~clear; @@ -199,12 +207,12 @@ public class Resource { if (JNLPRuntime.isDebug()) if (status != orig) { - System.out.print("Status: "+getStatusString(status)); + System.out.print("Status: " + getStatusString(status)); if ((status & ~orig) != 0) - System.out.print(" +("+getStatusString(status & ~orig)+")"); + System.out.print(" +(" + getStatusString(status & ~orig) + ")"); if ((~status & orig) != 0) - System.out.print(" -("+getStatusString(~status & orig)+")"); - System.out.println(" @ "+location.getPath()); + System.out.print(" -(" + getStatusString(~status & orig) + ")"); + System.out.println(" @ " + location.getPath()); } } @@ -245,7 +253,7 @@ public class Resource { send = trackers.hardList(); } - for (int i=0; i < send.size(); i++) { + for (int i = 0; i < send.size(); i++) { ResourceTracker rt = send.get(i); rt.fireDownloadEvent(this); } @@ -258,13 +266,13 @@ public class Resource { // time spent in synchronized addResource determining if // Resource is already in a tracker, and better for offline // mode on some OS. - return CacheUtil.urlEquals(location, ((Resource)other).location); + return CacheUtil.urlEquals(location, ((Resource) other).location); } return false; } public String toString() { - return "location="+location.toString() + " state="+getStatusString(status); + return "location=" + location.toString() + " state=" + getStatusString(status); } } diff --git a/netx/net/sourceforge/jnlp/cache/ResourceTracker.java b/netx/net/sourceforge/jnlp/cache/ResourceTracker.java index e4d85b0..c21be39 100644 --- a/netx/net/sourceforge/jnlp/cache/ResourceTracker.java +++ b/netx/net/sourceforge/jnlp/cache/ResourceTracker.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.cache; import java.io.BufferedInputStream; @@ -85,7 +84,6 @@ public class ResourceTracker { // todo: might make a tracker be able to download more than one // version of a resource, but probably not very useful. - // defines // ResourceTracker.Downloader (download threads) @@ -114,14 +112,14 @@ public class ResourceTracker { /** weak list of resource trackers with resources to prefetch */ private static WeakList<ResourceTracker> prefetchTrackers = - new WeakList<ResourceTracker>(); + new WeakList<ResourceTracker>(); /** resources requested to be downloaded */ private static ArrayList<Resource> queue = new ArrayList<Resource>(); /** resource trackers threads are working for (used for load balancing across multi-tracker downloads) */ private static ArrayList<ResourceTracker> active = - new ArrayList<ResourceTracker>(); // + new ArrayList<ResourceTracker>(); // /** the resources known about by this resource tracker */ private List<Resource> resources = new ArrayList<Resource>(); @@ -132,7 +130,6 @@ public class ResourceTracker { /** whether to download parts before requested */ private boolean prefetch; - /** * Creates a resource tracker that does not prefetch resources. */ @@ -227,7 +224,7 @@ public class ResourceTracker { // they will just 'pass through' the tracker as if they were // never added (for example, not affecting the total download size). synchronized (resource) { - resource.changeStatus(0, DOWNLOADED|CONNECTED|STARTED); + resource.changeStatus(0, DOWNLOADED | CONNECTED | STARTED); } fireDownloadEvent(resource); return true; @@ -238,13 +235,13 @@ public class ResourceTracker { if (entry.isCached() && !updatePolicy.shouldUpdate(entry)) { if (JNLPRuntime.isDebug()) - System.out.println("not updating: "+resource.location); + System.out.println("not updating: " + resource.location); synchronized (resource) { resource.localFile = CacheUtil.getCacheFile(resource.location, resource.downloadVersion); resource.size = resource.localFile.length(); resource.transferred = resource.localFile.length(); - resource.changeStatus(0, DOWNLOADED|CONNECTED|STARTED); + resource.changeStatus(0, DOWNLOADED | CONNECTED | STARTED); } fireDownloadEvent(resource); return true; @@ -304,8 +301,8 @@ public class ResourceTracker { } DownloadEvent event = new DownloadEvent(this, resource); - for (int i=0; i < l.length; i++) { - if (0 != ((ERROR|DOWNLOADED) & status)) + for (int i = 0; i < l.length; i++) { + if (0 != ((ERROR | DOWNLOADED) & status)) l[i].downloadCompleted(event); else if (0 != (DOWNLOADING & status)) l[i].downloadStarted(event); @@ -333,8 +330,7 @@ public class ResourceTracker { if (f != null) // TODO: Should be toURI().toURL() return f.toURL(); - } - catch (MalformedURLException ex) { + } catch (MalformedURLException ex) { if (JNLPRuntime.isDebug()) ex.printStackTrace(); } @@ -358,7 +354,7 @@ public class ResourceTracker { public File getCacheFile(URL location) { try { Resource resource = getResource(location); - if (!resource.isSet(DOWNLOADED|ERROR)) + if (!resource.isSet(DOWNLOADED | ERROR)) waitForResource(location, 0); if (resource.isSet(ERROR)) @@ -374,8 +370,7 @@ public class ResourceTracker { } return null; - } - catch (InterruptedException ex) { + } catch (InterruptedException ex) { if (JNLPRuntime.isDebug()) ex.printStackTrace(); @@ -398,15 +393,14 @@ public class ResourceTracker { public InputStream getInputStream(URL location) throws IOException { try { Resource resource = getResource(location); - if (!resource.isSet(DOWNLOADED|ERROR)) + if (!resource.isSet(DOWNLOADED | ERROR)) waitForResource(location, 0); if (resource.localFile != null) return new FileInputStream(resource.localFile); return resource.location.openStream(); - } - catch (InterruptedException ex) { + } catch (InterruptedException ex) { throw new IOException("wait was interrupted"); } } @@ -421,11 +415,11 @@ public class ResourceTracker { * @throws IllegalArgumentException if the resource is not being tracked */ public boolean waitForResources(URL urls[], long timeout) throws InterruptedException { - Resource resources[] = new Resource[ urls.length ]; + Resource resources[] = new Resource[urls.length]; - synchronized(resources) { + synchronized (resources) { // keep the lock so getResource doesn't have to aquire it each time - for (int i=0; i < urls.length; i++) + for (int i = 0; i < urls.length; i++) resources[i] = getResource(urls[i]); } @@ -469,7 +463,7 @@ public class ResourceTracker { * @throws IllegalArgumentException if the resource is not being tracked */ public boolean checkResource(URL location) { - return getResource(location).isSet(DOWNLOADED|ERROR); // isSet atomic + return getResource(location).isSet(DOWNLOADED | ERROR); // isSet atomic } /** @@ -505,11 +499,11 @@ public class ResourceTracker { enqueue = !resource.isSet(STARTED); if (!resource.isSet(CONNECTED | CONNECTING)) - resource.changeStatus(0, CONNECT|STARTED); + resource.changeStatus(0, CONNECT | STARTED); if (!resource.isSet(DOWNLOADED | DOWNLOADING)) - resource.changeStatus(0, DOWNLOAD|STARTED); + resource.changeStatus(0, DOWNLOAD | STARTED); - if (!resource.isSet(DOWNLOAD|CONNECT)) + if (!resource.isSet(DOWNLOAD | CONNECT)) enqueue = false; } @@ -580,8 +574,8 @@ public class ResourceTracker { */ private void queueResource(Resource resource) { synchronized (lock) { - if (!resource.isSet(CONNECT|DOWNLOAD)) - throw new IllegalArgumentException("Invalid resource state (resource: "+resource+")"); + if (!resource.isSet(CONNECT | DOWNLOAD)) + throw new IllegalArgumentException("Invalid resource state (resource: " + resource + ")"); queue.add(resource); startThread(); @@ -668,7 +662,7 @@ public class ResourceTracker { // explicitly close the URLConnection. if (con instanceof HttpURLConnection) - ((HttpURLConnection)con).disconnect(); + ((HttpURLConnection) con).disconnect(); /* * If the file was compressed, uncompress it. @@ -709,17 +703,16 @@ public class ResourceTracker { } resource.changeStatus(DOWNLOADING, DOWNLOADED); - synchronized(lock) { + synchronized (lock) { lock.notifyAll(); // wake up wait's to check for completion } resource.fireDownloadEvent(); // fire DOWNLOADED - } - catch (Exception ex) { + } catch (Exception ex) { if (JNLPRuntime.isDebug()) ex.printStackTrace(); resource.changeStatus(0, ERROR); - synchronized(lock) { + synchronized (lock) { lock.notifyAll(); // wake up wait's to check for completion } resource.fireDownloadEvent(); // fire ERROR @@ -743,15 +736,15 @@ public class ResourceTracker { int size = connection.getContentLength(); boolean current = CacheUtil.isCurrent(resource.location, resource.requestVersion, connection) && resource.getUpdatePolicy() != UpdatePolicy.FORCE; - synchronized(resource) { + synchronized (resource) { resource.localFile = localFile; // resource.connection = connection; resource.size = size; - resource.changeStatus(CONNECT|CONNECTING, CONNECTED); + resource.changeStatus(CONNECT | CONNECTING, CONNECTED); // check if up-to-date; if so set as downloaded if (current) - resource.changeStatus(DOWNLOAD|DOWNLOADING, DOWNLOADED); + resource.changeStatus(DOWNLOAD | DOWNLOADING, DOWNLOADED); } // update cache entry @@ -762,21 +755,20 @@ public class ResourceTracker { entry.setLastUpdated(System.currentTimeMillis()); entry.store(); - synchronized(lock) { + synchronized (lock) { lock.notifyAll(); // wake up wait's to check for completion } resource.fireDownloadEvent(); // fire CONNECTED // explicitly close the URLConnection. - if (connection instanceof HttpURLConnection) - ((HttpURLConnection)connection).disconnect(); - } - catch (Exception ex) { + if (connection instanceof HttpURLConnection) + ((HttpURLConnection) connection).disconnect(); + } catch (Exception ex) { if (JNLPRuntime.isDebug()) ex.printStackTrace(); resource.changeStatus(0, ERROR); - synchronized(lock) { + synchronized (lock) { lock.notifyAll(); // wake up wait's to check for completion } resource.fireDownloadEvent(); // fire ERROR @@ -807,7 +799,6 @@ public class ResourceTracker { return versionedURL; } - /** * Pick the next resource to download or initialize. If there * are no more resources requested then one is taken from a @@ -826,7 +817,7 @@ public class ResourceTracker { // pick from queue result = selectByFlag(queue, CONNECT, ERROR); // connect but not error if (result == null) - result = selectByFlag(queue, DOWNLOAD, ERROR|CONNECT|CONNECTING); + result = selectByFlag(queue, DOWNLOAD, ERROR | CONNECT | CONNECTING); // remove from queue if found if (result != null) @@ -842,8 +833,7 @@ public class ResourceTracker { synchronized (result) { if (result.isSet(CONNECT)) { result.changeStatus(CONNECT, CONNECTING); - } - else if (result.isSet(DOWNLOAD)) { + } else if (result.isSet(DOWNLOAD)) { // only download if *not* connecting, when done connecting // select next will pick up the download part. This makes // all requested connects happen before any downloads, so @@ -867,7 +857,7 @@ public class ResourceTracker { // first find one to initialize synchronized (prefetchTrackers) { - for (int i=0; i < prefetchTrackers.size() && result == null; i++) { + for (int i = 0; i < prefetchTrackers.size() && result == null; i++) { ResourceTracker tracker = prefetchTrackers.get(i); if (tracker == null) continue; @@ -876,7 +866,7 @@ public class ResourceTracker { result = selectByFlag(tracker.resources, UNINITIALIZED, ERROR); if (result == null && alternate == null) - alternate = selectByFlag(tracker.resources, CONNECTED, ERROR|DOWNLOADED|DOWNLOADING|DOWNLOAD); + alternate = selectByFlag(tracker.resources, CONNECTED, ERROR | DOWNLOADED | DOWNLOADING | DOWNLOAD); } } } @@ -915,7 +905,7 @@ public class ResourceTracker { Resource result = null; int score = Integer.MAX_VALUE; - for (int i=0; i < source.size(); i++) { + for (int i = 0; i < source.size(); i++) { Resource resource = source.get(i); boolean selectable = false; @@ -927,7 +917,7 @@ public class ResourceTracker { if (selectable) { int activeCount = 0; - for (int j=0; j < active.size(); j++) + for (int j = 0; j < active.size(); j++) if (active.get(j) == resource.getTracker()) activeCount++; @@ -950,7 +940,7 @@ public class ResourceTracker { */ private Resource getResource(URL location) { synchronized (resources) { - for (int i=0; i < resources.size(); i++) { + for (int i = 0; i < resources.size(); i++) { Resource resource = resources.get(i); if (CacheUtil.urlEquals(resource.location, location)) @@ -974,7 +964,7 @@ public class ResourceTracker { long startTime = System.currentTimeMillis(); // start them downloading / connecting in background - for (int i=0; i < resources.length; i++) + for (int i = 0; i < resources.length; i++) startResource(resources[i]); // wait for completion @@ -983,9 +973,9 @@ public class ResourceTracker { synchronized (lock) { // check for completion - for (int i=0; i < resources.length; i++) { - //NetX Deadlocking may be solved by removing this - //synch block. + for (int i = 0; i < resources.length; i++) { + //NetX Deadlocking may be solved by removing this + //synch block. synchronized (resources[i]) { if (!resources[i].isSet(DOWNLOADED | ERROR)) { finished = false; @@ -1000,7 +990,7 @@ public class ResourceTracker { long waitTime = 0; if (timeout > 0) { - waitTime = timeout - (System.currentTimeMillis()-startTime); + waitTime = timeout - (System.currentTimeMillis() - startTime); if (waitTime <= 0) return false; } @@ -1010,7 +1000,6 @@ public class ResourceTracker { } } - // inner classes /** @@ -1039,8 +1028,7 @@ public class ResourceTracker { try { processResource(resource); - } - catch (Exception ex) { + } catch (Exception ex) { if (JNLPRuntime.isDebug()) ex.printStackTrace(); } diff --git a/netx/net/sourceforge/jnlp/cache/UpdatePolicy.java b/netx/net/sourceforge/jnlp/cache/UpdatePolicy.java index 157e38c..8c069f6 100644 --- a/netx/net/sourceforge/jnlp/cache/UpdatePolicy.java +++ b/netx/net/sourceforge/jnlp/cache/UpdatePolicy.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.cache; import java.io.*; @@ -27,6 +26,7 @@ import javax.jnlp.*; import net.sourceforge.jnlp.*; import net.sourceforge.jnlp.runtime.*; import net.sourceforge.jnlp.util.*; + /** * A policy that determines when a resource should be checked for * an updated version.<p> @@ -52,7 +52,6 @@ public class UpdatePolicy { private long timeDiff = -1; - /** * Create a new update policy; this policy always updates the * entry unless the shouldUpdate method is overridden. diff --git a/netx/net/sourceforge/jnlp/controlpanel/AdvancedProxySettingsDialog.java b/netx/net/sourceforge/jnlp/controlpanel/AdvancedProxySettingsDialog.java index 2334947..241f04c 100644 --- a/netx/net/sourceforge/jnlp/controlpanel/AdvancedProxySettingsDialog.java +++ b/netx/net/sourceforge/jnlp/controlpanel/AdvancedProxySettingsDialog.java @@ -130,9 +130,7 @@ public class AdvancedProxySettingsDialog extends JDialog { psd.dispose(); } }); - - - + } /** diff --git a/netx/net/sourceforge/jnlp/controlpanel/ControlPanel.java b/netx/net/sourceforge/jnlp/controlpanel/ControlPanel.java index 27812a9..3273940 100644 --- a/netx/net/sourceforge/jnlp/controlpanel/ControlPanel.java +++ b/netx/net/sourceforge/jnlp/controlpanel/ControlPanel.java @@ -182,7 +182,7 @@ public class ControlPanel extends JFrame { SettingsPanel[] panels = new SettingsPanel[] { new SettingsPanel(Translator.R("CPTabAbout"), createAboutPanel()), new SettingsPanel(Translator.R("CPTabCache"), createCacheSettingsPanel()), new SettingsPanel(Translator.R("CPTabCertificate"), createCertificatesSettingsPanel()), -// new SettingsPanel(Translator.R("CPTabClassLoader"), createClassLoaderSettingsPanel()), + // new SettingsPanel(Translator.R("CPTabClassLoader"), createClassLoaderSettingsPanel()), new SettingsPanel(Translator.R("CPTabDebugging"), createDebugSettingsPanel()), new SettingsPanel(Translator.R("CPTabDesktopIntegration"), createDesktopSettingsPanel()), new SettingsPanel(Translator.R("CPTabNetwork"), createNetworkSettingsPanel()), diff --git a/netx/net/sourceforge/jnlp/controlpanel/DebuggingPanel.java b/netx/net/sourceforge/jnlp/controlpanel/DebuggingPanel.java index 0693357..1cdbb46 100644 --- a/netx/net/sourceforge/jnlp/controlpanel/DebuggingPanel.java +++ b/netx/net/sourceforge/jnlp/controlpanel/DebuggingPanel.java @@ -116,7 +116,8 @@ public class DebuggingPanel extends NamedBorderPanel implements ItemListener { case 3: for (int j = 0; j < javaConsoleItems.length; j++) { consoleComboBox.addItem(javaConsoleItems[j]); - if (config.getProperty("deployment.console.startup.mode").equals(javaConsoleItems[j].getValue())) consoleComboBox.setSelectedIndex(j); + if (config.getProperty("deployment.console.startup.mode").equals(javaConsoleItems[j].getValue())) + consoleComboBox.setSelectedIndex(j); } consoleComboBox.addItemListener(this); add(consolePanel, c); diff --git a/netx/net/sourceforge/jnlp/controlpanel/DesktopShortcutPanel.java b/netx/net/sourceforge/jnlp/controlpanel/DesktopShortcutPanel.java index 3d13c62..8563b82 100644 --- a/netx/net/sourceforge/jnlp/controlpanel/DesktopShortcutPanel.java +++ b/netx/net/sourceforge/jnlp/controlpanel/DesktopShortcutPanel.java @@ -72,7 +72,8 @@ public class DesktopShortcutPanel extends NamedBorderPanel implements ItemListen shortcutComboOptions.setActionCommand("deployment.javaws.shortcut"); // The configuration property this combobox affects. for (int j = 0; j < items.length; j++) { shortcutComboOptions.addItem(items[j]); - if (config.getProperty("deployment.javaws.shortcut").equals(items[j].getValue())) shortcutComboOptions.setSelectedIndex(j); + if (config.getProperty("deployment.javaws.shortcut").equals(items[j].getValue())) + shortcutComboOptions.setSelectedIndex(j); } shortcutComboOptions.addItemListener(this); diff --git a/netx/net/sourceforge/jnlp/controlpanel/MiddleClickListener.java b/netx/net/sourceforge/jnlp/controlpanel/MiddleClickListener.java index 0062684..633bfdf 100644 --- a/netx/net/sourceforge/jnlp/controlpanel/MiddleClickListener.java +++ b/netx/net/sourceforge/jnlp/controlpanel/MiddleClickListener.java @@ -39,7 +39,8 @@ class MiddleClickListener extends MouseAdapter { String result = null; if (obj instanceof JTextField) result = ((JTextField) obj).getText(); - else if (obj instanceof JTextArea) result = ((JTextArea) obj).getText(); + else if (obj instanceof JTextArea) + result = ((JTextArea) obj).getText(); config.setProperty(property, result); } diff --git a/netx/net/sourceforge/jnlp/controlpanel/NamedBorderPanel.java b/netx/net/sourceforge/jnlp/controlpanel/NamedBorderPanel.java index c7b2506..9ec1398 100644 --- a/netx/net/sourceforge/jnlp/controlpanel/NamedBorderPanel.java +++ b/netx/net/sourceforge/jnlp/controlpanel/NamedBorderPanel.java @@ -54,7 +54,7 @@ public class NamedBorderPanel extends JPanel { public NamedBorderPanel(String title) { super(); setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createTitledBorder(title), + BorderFactory.createTitledBorder(title), BorderFactory.createEmptyBorder(5, 5, 5, 5))); } } diff --git a/netx/net/sourceforge/jnlp/controlpanel/NetworkSettingsPanel.java b/netx/net/sourceforge/jnlp/controlpanel/NetworkSettingsPanel.java index 4b6ee04..ae21521 100644 --- a/netx/net/sourceforge/jnlp/controlpanel/NetworkSettingsPanel.java +++ b/netx/net/sourceforge/jnlp/controlpanel/NetworkSettingsPanel.java @@ -190,7 +190,8 @@ public class NetworkSettingsPanel extends JPanel implements ActionListener { locationField.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) { String value = locationField.getText(); - if (value.trim().equals("")) value = null; + if (value.trim().equals("")) + value = null; config.setProperty(properties[4], value); } }); diff --git a/netx/net/sourceforge/jnlp/controlpanel/SecuritySettingsPanel.java b/netx/net/sourceforge/jnlp/controlpanel/SecuritySettingsPanel.java index 18d574a..d148b8a 100644 --- a/netx/net/sourceforge/jnlp/controlpanel/SecuritySettingsPanel.java +++ b/netx/net/sourceforge/jnlp/controlpanel/SecuritySettingsPanel.java @@ -64,7 +64,7 @@ public class SecuritySettingsPanel extends NamedBorderPanel implements ActionLis "deployment.security.SSLv2Hello", // Default FALSE "deployment.security.SSLv3", // Default TRUE "deployment.security.TLSv1", // Default TRUE -// "deployment.security.mixcode", // Default TRUE + // "deployment.security.mixcode", // Default TRUE }; /** diff --git a/netx/net/sourceforge/jnlp/controlpanel/TemporaryInternetFilesPanel.java b/netx/net/sourceforge/jnlp/controlpanel/TemporaryInternetFilesPanel.java index ef56a18..413b585 100644 --- a/netx/net/sourceforge/jnlp/controlpanel/TemporaryInternetFilesPanel.java +++ b/netx/net/sourceforge/jnlp/controlpanel/TemporaryInternetFilesPanel.java @@ -226,7 +226,8 @@ public class TemporaryInternetFilesPanel extends NamedBorderPanel implements Cha Object o = e.getSource(); if (o instanceof JSlider) spCacheSize.setValue(((JSlider) o).getValue()); - else if (o instanceof JSpinner) slCacheSize.setValue((Integer) ((JSpinner) o).getValue()); + else if (o instanceof JSpinner) + slCacheSize.setValue((Integer) ((JSpinner) o).getValue()); config.setProperty(properties[2], spCacheSize.getValue().toString()); } diff --git a/netx/net/sourceforge/jnlp/event/ApplicationEvent.java b/netx/net/sourceforge/jnlp/event/ApplicationEvent.java index 10d6844..12e0d83 100644 --- a/netx/net/sourceforge/jnlp/event/ApplicationEvent.java +++ b/netx/net/sourceforge/jnlp/event/ApplicationEvent.java @@ -32,7 +32,6 @@ public class ApplicationEvent extends EventObject { /** the application instance */ private ApplicationInstance application; - /** * Creates a launch event for the specified application * instance. diff --git a/netx/net/sourceforge/jnlp/event/ApplicationListener.java b/netx/net/sourceforge/jnlp/event/ApplicationListener.java index b000b2c..8df4b68 100644 --- a/netx/net/sourceforge/jnlp/event/ApplicationListener.java +++ b/netx/net/sourceforge/jnlp/event/ApplicationListener.java @@ -14,12 +14,10 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.event; import java.util.*; - /** * The listener that is notified when an application instance is * terminated. diff --git a/netx/net/sourceforge/jnlp/event/DownloadEvent.java b/netx/net/sourceforge/jnlp/event/DownloadEvent.java index a5697d1..9d07c2f 100644 --- a/netx/net/sourceforge/jnlp/event/DownloadEvent.java +++ b/netx/net/sourceforge/jnlp/event/DownloadEvent.java @@ -38,7 +38,6 @@ public class DownloadEvent extends EventObject { /** the resource */ private Resource resource; - /** * Creates a launch event for the specified application * instance. diff --git a/netx/net/sourceforge/jnlp/event/DownloadListener.java b/netx/net/sourceforge/jnlp/event/DownloadListener.java index b9816b9..dfdd42d 100644 --- a/netx/net/sourceforge/jnlp/event/DownloadListener.java +++ b/netx/net/sourceforge/jnlp/event/DownloadListener.java @@ -14,12 +14,10 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.event; import java.util.*; - /** * The listener that is notified of the state of resources being * downloaded by a ResourceTracker. Events may be delivered on a diff --git a/netx/net/sourceforge/jnlp/runtime/AppThreadGroup.java b/netx/net/sourceforge/jnlp/runtime/AppThreadGroup.java index 84ee28f..5287975 100644 --- a/netx/net/sourceforge/jnlp/runtime/AppThreadGroup.java +++ b/netx/net/sourceforge/jnlp/runtime/AppThreadGroup.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.runtime; import java.awt.*; @@ -30,7 +29,6 @@ public class AppThreadGroup extends ThreadGroup { /** the app */ private ApplicationInstance app = null; - /** * Creates new JavaAppThreadGroup * @@ -64,5 +62,4 @@ public class AppThreadGroup extends ThreadGroup { super.uncaughtException(t, e); } - } diff --git a/netx/net/sourceforge/jnlp/runtime/AppletAudioClip.java b/netx/net/sourceforge/jnlp/runtime/AppletAudioClip.java index 3b62e0d..ea6bbc2 100644 --- a/netx/net/sourceforge/jnlp/runtime/AppletAudioClip.java +++ b/netx/net/sourceforge/jnlp/runtime/AppletAudioClip.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.runtime; import java.net.*; @@ -35,7 +34,6 @@ public class AppletAudioClip implements AudioClip { /** the clip */ private Clip clip; - /** * Creates new AudioClip. If the clip cannot be opened no * exception is thrown, instead the methods of the AudioClip @@ -49,9 +47,8 @@ public class AppletAudioClip implements AudioClip { clip = (Clip) AudioSystem.getLine(new Line.Info(Clip.class)); clip.open(stream); - } - catch (Exception ex) { - System.err.println("Error loading sound:"+location.toString()); + } catch (Exception ex) { + System.err.println("Error loading sound:" + location.toString()); clip = null; } } diff --git a/netx/net/sourceforge/jnlp/runtime/AppletEnvironment.java b/netx/net/sourceforge/jnlp/runtime/AppletEnvironment.java index 65032fe..f55c95d 100644 --- a/netx/net/sourceforge/jnlp/runtime/AppletEnvironment.java +++ b/netx/net/sourceforge/jnlp/runtime/AppletEnvironment.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.runtime; import java.applet.*; @@ -65,7 +64,6 @@ public class AppletEnvironment implements AppletContext, AppletStub { /** whether the applet has been destroyed */ private boolean destroyed = false; - /** * Create a new applet environment for the applet specified by * the JNLP file. @@ -151,7 +149,7 @@ public class AppletEnvironment implements AppletContext, AppletStub { AppletDesc appletDesc = file.getApplet(); if (cont instanceof AppletStub) - applet.setStub((AppletStub)cont); + applet.setStub((AppletStub) cont); else applet.setStub(this); @@ -171,26 +169,25 @@ public class AppletEnvironment implements AppletContext, AppletStub { try { SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - // do first because some applets need to be displayed before - // starting (they use Component.getImage or something) - cont.setVisible(true); - - applet.init(); - applet.start(); - - cont.invalidate(); // this should force the applet to - cont.validate(); // the correct size and to repaint - cont.repaint(); - } + public void run() { + // do first because some applets need to be displayed before + // starting (they use Component.getImage or something) + cont.setVisible(true); + + applet.init(); + applet.start(); + + cont.invalidate(); // this should force the applet to + cont.validate(); // the correct size and to repaint + cont.repaint(); + } }); } catch (InterruptedException ie) { } catch (InvocationTargetException ite) { } - } - catch (Exception ex) { + } catch (Exception ex) { if (JNLPRuntime.isDebug()) ex.printStackTrace(); @@ -220,7 +217,7 @@ public class AppletEnvironment implements AppletContext, AppletStub { public Enumeration<Applet> getApplets() { checkDestroyed(); - return Collections.enumeration( Arrays.asList(new Applet[] { applet }) ); + return Collections.enumeration(Arrays.asList(new Applet[] { applet })); } /** @@ -293,7 +290,7 @@ public class AppletEnvironment implements AppletContext, AppletStub { /** * Required for JRE1.4, but not implemented yet. */ - public Iterator<String> getStreamKeys() { + public Iterator<String> getStreamKeys() { checkDestroyed(); return null; @@ -350,5 +347,4 @@ public class AppletEnvironment implements AppletContext, AppletStub { return true; } - } diff --git a/netx/net/sourceforge/jnlp/runtime/AppletInstance.java b/netx/net/sourceforge/jnlp/runtime/AppletInstance.java index 51bc801..a7fbce1 100644 --- a/netx/net/sourceforge/jnlp/runtime/AppletInstance.java +++ b/netx/net/sourceforge/jnlp/runtime/AppletInstance.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.runtime; import java.applet.*; @@ -29,7 +28,6 @@ import java.lang.ref.*; import net.sourceforge.jnlp.*; - /** * Represents a launched application instance created from a JNLP * file. This class does not control the operation of the applet, @@ -49,7 +47,6 @@ public class AppletInstance extends ApplicationInstance { /** the applet environment */ private AppletEnvironment environment; - /** * Create a New Task based on the Specified URL */ @@ -124,8 +121,7 @@ public class AppletInstance extends ApplicationInstance { try { applet.stop(); applet.destroy(); - } - catch (Exception ex) { + } catch (Exception ex) { if (JNLPRuntime.isDebug()) ex.printStackTrace(); } diff --git a/netx/net/sourceforge/jnlp/runtime/ApplicationInstance.java b/netx/net/sourceforge/jnlp/runtime/ApplicationInstance.java index 99b576d..f86eb39 100644 --- a/netx/net/sourceforge/jnlp/runtime/ApplicationInstance.java +++ b/netx/net/sourceforge/jnlp/runtime/ApplicationInstance.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.runtime; import java.awt.Window; @@ -54,7 +53,6 @@ public class ApplicationInstance { // todo: should attempt to unload the environment variables // installed by the application. - /** the file */ private JNLPFile file; @@ -83,8 +81,8 @@ public class ApplicationInstance { /** list of application listeners */ private EventListenerList listeners = new EventListenerList(); - /** whether or not this application is signed */ - private boolean isSigned = false; + /** whether or not this application is signed */ + private boolean isSigned = false; /** * Create an application instance for the file. This should be done in the @@ -119,11 +117,11 @@ public class ApplicationInstance { Object list[] = listeners.getListenerList(); ApplicationEvent event = null; - for (int i=list.length-1; i>0; i-=2) { // last to first required + for (int i = list.length - 1; i > 0; i -= 2) { // last to first required if (event == null) event = new ApplicationEvent(this); - ((ApplicationListener)list[i]).applicationDestroyed(event); + ((ApplicationListener) list[i]).applicationDestroyed(event); } } @@ -174,7 +172,7 @@ public class ApplicationInstance { */ private boolean shouldCreateShortcut(ShortcutDesc sd) { String currentSetting = JNLPRuntime.getConfiguration() - .getProperty(DeploymentConfiguration.KEY_CREATE_DESKTOP_SHORTCUT); + .getProperty(DeploymentConfiguration.KEY_CREATE_DESKTOP_SHORTCUT); boolean createShortcut = false; /* @@ -221,7 +219,7 @@ public class ApplicationInstance { void installEnvironment() { final PropertyDesc props[] = file.getResources().getProperties(); - CodeSource cs = new CodeSource((URL) null, (java.security.cert.Certificate [])null); + CodeSource cs = new CodeSource((URL) null, (java.security.cert.Certificate[]) null); JNLPClassLoader loader = (JNLPClassLoader) this.loader; SecurityDesc s = loader.getSecurity(); @@ -229,11 +227,11 @@ public class ApplicationInstance { ProtectionDomain pd = new ProtectionDomain(cs, s.getPermissions(), null, null); // Add to hashmap - AccessControlContext acc = new AccessControlContext(new ProtectionDomain[] {pd}); + AccessControlContext acc = new AccessControlContext(new ProtectionDomain[] { pd }); PrivilegedAction<Object> installProps = new PrivilegedAction<Object>() { public Object run() { - for (int i=0; i < props.length; i++) { + for (int i = 0; i < props.length; i++) { System.setProperty(props[i].getKey(), props[i].getValue()); } @@ -274,7 +272,7 @@ public class ApplicationInstance { try { // destroy resources - for (int i=0; i < weakWindows.size(); i++) { + for (int i = 0; i < weakWindows.size(); i++) { Window w = weakWindows.get(i); if (w != null) w.dispose(); @@ -282,12 +280,12 @@ public class ApplicationInstance { weakWindows.clear(); - // interrupt threads - Thread threads[] = new Thread[ group.activeCount() * 2 ]; + // interrupt threads + Thread threads[] = new Thread[group.activeCount() * 2]; int nthreads = group.enumerate(threads); - for (int i=0; i < nthreads; i++) { + for (int i = 0; i < nthreads; i++) { if (JNLPRuntime.isDebug()) - System.out.println("Interrupt thread: "+threads[i]); + System.out.println("Interrupt thread: " + threads[i]); threads[i].interrupt(); } @@ -295,17 +293,16 @@ public class ApplicationInstance { // then stop Thread.currentThread().yield(); nthreads = group.enumerate(threads); - for (int i=0; i < nthreads; i++) { + for (int i = 0; i < nthreads; i++) { if (JNLPRuntime.isDebug()) - System.out.println("Stop thread: "+threads[i]); + System.out.println("Stop thread: " + threads[i]); threads[i].stop(); } // then destroy - except Thread.destroy() not implemented in jdk - } - finally { + } finally { stopped = true; fireDestroyed(); } @@ -344,12 +341,12 @@ public class ApplicationInstance { weakWindows.trimToSize(); } - /** - * Returns whether or not this jar is signed. - */ - public boolean isSigned() { - return isSigned; - } + /** + * Returns whether or not this jar is signed. + */ + public boolean isSigned() { + return isSigned; + } public AppContext getAppContext() { return appContext; diff --git a/netx/net/sourceforge/jnlp/runtime/Boot.java b/netx/net/sourceforge/jnlp/runtime/Boot.java index c4939b7..b075e65 100644 --- a/netx/net/sourceforge/jnlp/runtime/Boot.java +++ b/netx/net/sourceforge/jnlp/runtime/Boot.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.runtime; import static net.sourceforge.jnlp.runtime.Translator.R; @@ -63,62 +62,60 @@ public final class Boot implements PrivilegedAction<Void> { /** the text to display before launching the about link */ private static final String aboutMessage = "" - + "netx v"+version+" - (C)2001-2003 Jon A. Maxwell ([email protected])\n" - + "\n" - + R("BLaunchAbout"); + + "netx v" + version + " - (C)2001-2003 Jon A. Maxwell ([email protected])\n" + + "\n" + + R("BLaunchAbout"); private static final String miniLicense = "\n" - + " netx - an open-source JNLP client.\n" - + " Copyright (C) 2001-2003 Jon A. Maxwell (JAM)\n" - + "\n" - + " // This library is free software; you can redistribute it and/or\n" - + " modify it under the terms of the GNU Lesser General Public\n" - + " License as published by the Free Software Foundation; either\n" - + " version 2.1 of the License, or (at your option) any later version.\n" - + "\n" - + " This library is distributed in the hope that it will be useful,\n" - + " but WITHOUT ANY WARRANTY; without even the implied warranty of\n" - + " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" - + " Lesser General Public License for more details.\n" - + "\n" - + " You should have received a copy of the GNU Lesser General Public\n" - + " License along with this library; if not, write to the Free Software\n" - + " Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n" - + "\n"; + + " netx - an open-source JNLP client.\n" + + " Copyright (C) 2001-2003 Jon A. Maxwell (JAM)\n" + + "\n" + + " // This library is free software; you can redistribute it and/or\n" + + " modify it under the terms of the GNU Lesser General Public\n" + + " License as published by the Free Software Foundation; either\n" + + " version 2.1 of the License, or (at your option) any later version.\n" + + "\n" + + " This library is distributed in the hope that it will be useful,\n" + + " but WITHOUT ANY WARRANTY; without even the implied warranty of\n" + + " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" + + " Lesser General Public License for more details.\n" + + "\n" + + " You should have received a copy of the GNU Lesser General Public\n" + + " License along with this library; if not, write to the Free Software\n" + + " Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n" + + "\n"; private static final String helpMessage = "\n" - + "Usage: " + R("BOUsage")+"\n" - + " " + R("BOUsage2")+"\n" - + "\n" - + "control-options:"+"\n" - + " -about "+R("BOAbout")+"\n" - + " -viewer "+R("BOViewer")+"\n" - + "\n" - + "run-options:"+"\n" - + " -arg arg "+R("BOArg")+"\n" - + " -param name=value "+R("BOParam")+"\n" - + " -property name=value "+R("BOProperty")+"\n" - + " -update seconds "+R("BOUpdate")+"\n" - + " -license "+R("BOLicense")+"\n" - + " -verbose "+R("BOVerbose")+"\n" - + " -nosecurity "+R("BONosecurity")+"\n" - + " -noupdate "+R("BONoupdate")+"\n" - + " -headless "+R("BOHeadless")+"\n" - + " -strict "+R("BOStrict")+"\n" - + " -Xnofork "+R("BXnofork")+"\n" - + " -Xclearcache "+R("BXclearcache")+"\n" - + " -help "+R("BOHelp")+"\n"; + + "Usage: " + R("BOUsage") + "\n" + + " " + R("BOUsage2") + "\n" + + "\n" + + "control-options:" + "\n" + + " -about " + R("BOAbout") + "\n" + + " -viewer " + R("BOViewer") + "\n" + + "\n" + + "run-options:" + "\n" + + " -arg arg " + R("BOArg") + "\n" + + " -param name=value " + R("BOParam") + "\n" + + " -property name=value " + R("BOProperty") + "\n" + + " -update seconds " + R("BOUpdate") + "\n" + + " -license " + R("BOLicense") + "\n" + + " -verbose " + R("BOVerbose") + "\n" + + " -nosecurity " + R("BONosecurity") + "\n" + + " -noupdate " + R("BONoupdate") + "\n" + + " -headless " + R("BOHeadless") + "\n" + + " -strict " + R("BOStrict") + "\n" + + " -Xnofork " + R("BXnofork") + "\n" + + " -Xclearcache " + R("BXclearcache") + "\n" + + " -help " + R("BOHelp") + "\n"; /** the JNLP file to open to display the network-based about window */ private static final String NETX_ABOUT_FILE = System.getProperty("java.home") + File.separator + "lib" + File.separator + "about.jnlp"; - private static final String doubleArgs = "-basedir -jnlp -arg -param -property -update"; private static String args[]; // avoid the hot potato - /** * Launch the JNLP file specified by the command-line arguments. */ @@ -155,13 +152,12 @@ public final class Boot implements PrivilegedAction<Void> { if (null != getOption("-update")) { int value = Integer.parseInt(getOption("-update")); - JNLPRuntime.setDefaultUpdatePolicy(new UpdatePolicy(value*1000l)); + JNLPRuntime.setDefaultUpdatePolicy(new UpdatePolicy(value * 1000l)); } if (null != getOption("-headless")) JNLPRuntime.setHeadless(true); - if (null != getOption("-noupdate")) JNLPRuntime.setDefaultUpdatePolicy(UpdatePolicy.NEVER); @@ -198,11 +194,9 @@ public final class Boot implements PrivilegedAction<Void> { try { new Launcher().launch(getFile()); - } - catch (LaunchException ex) { + } catch (LaunchException ex) { // default handler prints this - } - catch (Exception ex) { + } catch (Exception ex) { if (JNLPRuntime.isDebug()) ex.printStackTrace(); @@ -213,7 +207,7 @@ public final class Boot implements PrivilegedAction<Void> { } private static void fatalError(String message) { - System.err.println("netx: "+message); + System.err.println("netx: " + message); System.exit(1); } @@ -252,7 +246,7 @@ public final class Boot implements PrivilegedAction<Void> { } if (JNLPRuntime.isDebug()) - System.out.println(R("BFileLoc")+": "+location); + System.out.println(R("BFileLoc") + ": " + location); URL url = null; @@ -306,14 +300,14 @@ public final class Boot implements PrivilegedAction<Void> { String props[] = getOptions("-property"); ResourcesDesc resources = file.getResources(); - for (int i=0; i < props.length; i++) { + for (int i = 0; i < props.length; i++) { // allows empty property, not sure about validity of that. int equals = props[i].indexOf("="); if (equals == -1) fatalError(R("BBadProp", props[i])); String key = props[i].substring(0, equals); - String value = props[i].substring(equals+1, props[i].length()); + String value = props[i].substring(equals + 1, props[i].length()); resources.addResource(new PropertyDesc(key, value)); } @@ -327,14 +321,14 @@ public final class Boot implements PrivilegedAction<Void> { String params[] = getOptions("-param"); AppletDesc applet = file.getApplet(); - for (int i=0; i < params.length; i++) { + for (int i = 0; i < params.length; i++) { // allows empty param, not sure about validity of that. int equals = params[i].indexOf("="); if (equals == -1) fatalError(R("BBadParam", params[i])); String name = params[i].substring(0, equals); - String value = params[i].substring(equals+1, params[i].length()); + String value = params[i].substring(equals + 1, params[i].length()); applet.addParameter(name, value); } @@ -345,10 +339,10 @@ public final class Boot implements PrivilegedAction<Void> { * actually an application (not installer). */ private static void addArguments(JNLPFile file) { - String args[] = getOptions("-arg"); // FYI args also global variable + String args[] = getOptions("-arg"); // FYI args also global variable ApplicationDesc app = file.getApplication(); - for (int i=0; i < args.length; i++) { + for (int i = 0; i < args.length; i++) { app.addArgument(args[i]); } } @@ -401,20 +395,19 @@ public final class Boot implements PrivilegedAction<Void> { private static String[] getOptions(String option) { List<String> result = new ArrayList<String>(); - for (int i=0; i < args.length; i++) { + for (int i = 0; i < args.length; i++) { if (option.equals(args[i])) { if (-1 == doubleArgs.indexOf(option)) result.add(option); - else - if (i+1 < args.length) - result.add(args[i+1]); + else if (i + 1 < args.length) + result.add(args[i + 1]); } if (args[i].startsWith("-") && -1 != doubleArgs.indexOf(args[i])) i++; } - return result.toArray( new String[result.size()] ); + return result.toArray(new String[result.size()]); } } diff --git a/netx/net/sourceforge/jnlp/runtime/Boot13.java b/netx/net/sourceforge/jnlp/runtime/Boot13.java index 1b5aaa3..a573a1b 100644 --- a/netx/net/sourceforge/jnlp/runtime/Boot13.java +++ b/netx/net/sourceforge/jnlp/runtime/Boot13.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.runtime; import java.lang.reflect.*; @@ -50,7 +49,7 @@ public class Boot13 extends URLClassLoader { protected PermissionCollection getPermissions(CodeSource source) { Permissions result = new Permissions(); - result.add( new AllPermission() ); + result.add(new AllPermission()); return result; } @@ -66,8 +65,7 @@ public class Boot13 extends URLClassLoader { // but the wrong permissions. try { return findClass(name); - } - catch (ClassNotFoundException ex) { + } catch (ClassNotFoundException ex) { } return getParent().loadClass(name); @@ -89,14 +87,14 @@ public class Boot13 extends URLClassLoader { System.exit(1); } - Boot13 b = new Boot13(new URL[] {cs}); + Boot13 b = new Boot13(new URL[] { cs }); Thread.currentThread().setContextClassLoader(b); // try to prevent getting the non-policy version of classes Class<?> c = b.loadClass("net.sourceforge.jnlp.runtime.Boot"); - Method main = c.getDeclaredMethod("main", new Class<?>[] {String[].class} ); + Method main = c.getDeclaredMethod("main", new Class<?>[] { String[].class }); - main.invoke(null, new Object[] { args } ); + main.invoke(null, new Object[] { args }); } } diff --git a/netx/net/sourceforge/jnlp/runtime/DeploymentConfiguration.java b/netx/net/sourceforge/jnlp/runtime/DeploymentConfiguration.java index 2a4c963..662730f 100644 --- a/netx/net/sourceforge/jnlp/runtime/DeploymentConfiguration.java +++ b/netx/net/sourceforge/jnlp/runtime/DeploymentConfiguration.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.runtime; import java.awt.AWTPermission; @@ -215,7 +214,7 @@ public final class DeploymentConfiguration { private Map<String, ConfigValue> unchangeableConfiguration; public DeploymentConfiguration() { - currentConfiguration = new HashMap<String,ConfigValue>(); + currentConfiguration = new HashMap<String, ConfigValue>(); unchangeableConfiguration = new HashMap<String, ConfigValue>(); } @@ -372,10 +371,10 @@ public final class DeploymentConfiguration { { KEY_USER_TRUSTED_CA_CERTS, USER_SECURITY + File.separator + "trusted.cacerts" }, { KEY_USER_TRUSTED_JSSE_CA_CERTS, USER_SECURITY + File.separator + "trusted.jssecacerts" }, { KEY_USER_TRUSTED_CERTS, USER_SECURITY + File.separator + "trusted.certs" }, - { KEY_USER_TRUSTED_JSSE_CERTS, USER_SECURITY + File.separator + "trusted.jssecerts"}, + { KEY_USER_TRUSTED_JSSE_CERTS, USER_SECURITY + File.separator + "trusted.jssecerts" }, { KEY_USER_TRUSTED_CLIENT_CERTS, USER_SECURITY + File.separator + "trusted.clientcerts" }, { "deployment.system.security.policy", null }, - { KEY_SYSTEM_TRUSTED_CA_CERTS , SYSTEM_SECURITY + File.separator + "cacerts" }, + { KEY_SYSTEM_TRUSTED_CA_CERTS, SYSTEM_SECURITY + File.separator + "cacerts" }, { KEY_SYSTEM_TRUSTED_JSSE_CA_CERTS, SYSTEM_SECURITY + File.separator + "jssecacerts" }, { KEY_SYSTEM_TRUSTED_CERTS, SYSTEM_SECURITY + File.separator + "trusted.certs" }, { KEY_SYSTEM_TRUSTED_JSSE_CERTS, SYSTEM_SECURITY + File.separator + "trusted.jssecerts" }, @@ -417,7 +416,7 @@ public final class DeploymentConfiguration { /* JNLP association */ { "deployment.javaws.associations", String.valueOf(JNLP_ASSOCIATION_ASK_USER) }, /* desktop integration */ - { KEY_CREATE_DESKTOP_SHORTCUT, ShortcutDesc.CREATE_ASK_USER_IF_HINTED}, + { KEY_CREATE_DESKTOP_SHORTCUT, ShortcutDesc.CREATE_ASK_USER_IF_HINTED }, /* jre selection */ { "deployment.javaws.installURL", null }, /* jre management */ @@ -500,7 +499,7 @@ public final class DeploymentConfiguration { + systemPropertiesFile); } ConfigValue mandatory = systemConfiguration.get("deployment.system.config.mandatory"); - systemPropertiesMandatory = Boolean.valueOf(mandatory == null? null: mandatory.get()); + systemPropertiesMandatory = Boolean.valueOf(mandatory == null ? null : mandatory.get()); return true; } else { if (JNLPRuntime.isDebug()) { @@ -548,7 +547,6 @@ public final class DeploymentConfiguration { } } - /** * Saves all properties that are not part of default or system properties * @@ -659,7 +657,7 @@ public final class DeploymentConfiguration { * @param srcMap the source for reading key value pairs */ private void mergeMaps(Map<String, ConfigValue> finalMap, Map<String, ConfigValue> srcMap) { - for (String key: srcMap.keySet()) { + for (String key : srcMap.keySet()) { ConfigValue configValue = finalMap.get(key); if (configValue == null) { configValue = srcMap.get(key); diff --git a/netx/net/sourceforge/jnlp/runtime/JNLPClassLoader.java b/netx/net/sourceforge/jnlp/runtime/JNLPClassLoader.java index aac70d0..3ac5014 100644 --- a/netx/net/sourceforge/jnlp/runtime/JNLPClassLoader.java +++ b/netx/net/sourceforge/jnlp/runtime/JNLPClassLoader.java @@ -1,4 +1,3 @@ - // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -14,7 +13,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.runtime; import static net.sourceforge.jnlp.runtime.Translator.R; @@ -81,8 +79,8 @@ public class JNLPClassLoader extends URLClassLoader { // resources in an extension. /** map from JNLPFile url to shared classloader */ - private static Map<String,JNLPClassLoader> urlToLoader = - new HashMap<String,JNLPClassLoader>(); // never garbage collected! + private static Map<String, JNLPClassLoader> urlToLoader = + new HashMap<String, JNLPClassLoader>(); // never garbage collected! /** the directory for native code */ private File nativeDir = null; // if set, some native code exists @@ -145,7 +143,7 @@ public class JNLPClassLoader extends URLClassLoader { /** Map of specific codesources to securitydesc */ private HashMap<URL, SecurityDesc> jarLocationSecurityMap = - new HashMap<URL, SecurityDesc>(); + new HashMap<URL, SecurityDesc>(); /** * Create a new JNLPClassLoader from the specified file. @@ -156,7 +154,7 @@ public class JNLPClassLoader extends URLClassLoader { super(new URL[0], JNLPClassLoader.class.getClassLoader()); if (JNLPRuntime.isDebug()) - System.out.println("New classloader: "+file.getFileLocation()); + System.out.println("New classloader: " + file.getFileLocation()); this.file = file; this.updatePolicy = policy; @@ -229,12 +227,12 @@ public class JNLPClassLoader extends URLClassLoader { if (file instanceof PluginBridge) { if (signing == true) { this.security = new SecurityDesc(file, - SecurityDesc.ALL_PERMISSIONS, - codebase.getHost()); + SecurityDesc.ALL_PERMISSIONS, + codebase.getHost()); } else { this.security = new SecurityDesc(file, - SecurityDesc.SANDBOX_PERMISSIONS, - codebase.getHost()); + SecurityDesc.SANDBOX_PERMISSIONS, + codebase.getHost()); } } else { //regular jnlp file @@ -252,8 +250,7 @@ public class JNLPClassLoader extends URLClassLoader { */ if (!file.getSecurity().getSecurityType().equals(SecurityDesc.SANDBOX_PERMISSIONS) && !signing) { throw new LaunchException(file, null, R("LSFatal"), R("LCClient"), R("LUnsignedJarWithSecurity"), R("LUnsignedJarWithSecurityInfo")); - } - else if (signing == true) { + } else if (signing == true) { this.security = file.getSecurity(); } else { this.security = new SecurityDesc(file, @@ -277,41 +274,41 @@ public class JNLPClassLoader extends URLClassLoader { if (uniqueKey != null) baseLoader = urlToLoader.get(uniqueKey); - try { + try { - // If base loader is null, or the baseloader's file and this - // file is different, initialize a new loader - if (baseLoader == null || + // If base loader is null, or the baseloader's file and this + // file is different, initialize a new loader + if (baseLoader == null || !baseLoader.getJNLPFile().getFileLocation().equals(file.getFileLocation())) { - loader = new JNLPClassLoader(file, policy); + loader = new JNLPClassLoader(file, policy); - // New loader init may have caused extentions to create a - // loader for this unique key. Check. - JNLPClassLoader extLoader = urlToLoader.get(uniqueKey); + // New loader init may have caused extentions to create a + // loader for this unique key. Check. + JNLPClassLoader extLoader = urlToLoader.get(uniqueKey); - if (extLoader != null && extLoader != loader) { - if (loader.signing && !extLoader.signing) - if (!SecurityWarning.showNotAllSignedWarningDialog(file)) - throw new LaunchException(file, null, R("LSFatal"), R("LCClient"), R("LSignedAppJarUsingUnsignedJar"), R("LSignedAppJarUsingUnsignedJarInfo")); + if (extLoader != null && extLoader != loader) { + if (loader.signing && !extLoader.signing) + if (!SecurityWarning.showNotAllSignedWarningDialog(file)) + throw new LaunchException(file, null, R("LSFatal"), R("LCClient"), R("LSignedAppJarUsingUnsignedJar"), R("LSignedAppJarUsingUnsignedJarInfo")); - loader.merge(extLoader); - } + loader.merge(extLoader); + } // loader is now current + ext. But we also need to think of // the baseLoader - if (baseLoader != null && baseLoader != loader) { - loader.merge(baseLoader); + if (baseLoader != null && baseLoader != loader) { + loader.merge(baseLoader); } - } else { - // if key is same and locations match, this is the loader we want - loader = baseLoader; - } + } else { + // if key is same and locations match, this is the loader we want + loader = baseLoader; + } - } catch (LaunchException e) { - throw e; - } + } catch (LaunchException e) { + throw e; + } // loaders are mapped to a unique key. Only extensions and parent // share a key, so it is safe to always share based on it @@ -348,18 +345,17 @@ public class JNLPClassLoader extends URLClassLoader { loaderList.add(this); - //if (ext != null) { - for (int i=0; i < ext.length; i++) { - try { - String uniqueKey = this.getJNLPFile().getUniqueKey(); - JNLPClassLoader loader = getInstance(ext[i].getLocation(), uniqueKey, ext[i].getVersion(), updatePolicy); - loaderList.add(loader); - } - catch (Exception ex) { - ex.printStackTrace(); - } - } - //} + //if (ext != null) { + for (int i = 0; i < ext.length; i++) { + try { + String uniqueKey = this.getJNLPFile().getUniqueKey(); + JNLPClassLoader loader = getInstance(ext[i].getLocation(), uniqueKey, ext[i].getVersion(), updatePolicy); + loaderList.add(loader); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + //} loaders = loaderList.toArray(new JNLPClassLoader[loaderList.size()]); } @@ -371,15 +367,15 @@ public class JNLPClassLoader extends URLClassLoader { resourcePermissions = new ArrayList<Permission>(); JARDesc jars[] = resources.getJARs(); - for (int i=0; i < jars.length; i++) { + for (int i = 0; i < jars.length; i++) { Permission p = CacheUtil.getReadPermission(jars[i].getLocation(), jars[i].getVersion()); if (JNLPRuntime.isDebug()) { if (p == null) - System.out.println("Unable to add permission for " + jars[i].getLocation()); + System.out.println("Unable to add permission for " + jars[i].getLocation()); else - System.out.println("Permission added: " + p.toString()); + System.out.println("Permission added: " + p.toString()); } if (p != null) resourcePermissions.add(p); @@ -392,17 +388,17 @@ public class JNLPClassLoader extends URLClassLoader { */ void initializeResources() throws LaunchException { JARDesc jars[] = resources.getJARs(); - if (jars == null || jars.length == 0) - return; - /* - if (jars == null || jars.length == 0) { - throw new LaunchException(null, null, R("LSFatal"), - R("LCInit"), R("LFatalVerification"), "No jars!"); - } - */ + if (jars == null || jars.length == 0) + return; + /* + if (jars == null || jars.length == 0) { + throw new LaunchException(null, null, R("LSFatal"), + R("LCInit"), R("LFatalVerification"), "No jars!"); + } + */ List<JARDesc> initialJars = new ArrayList<JARDesc>(); - for (int i=0; i < jars.length; i++) { + for (int i = 0; i < jars.length; i++) { available.add(jars[i]); @@ -418,94 +414,93 @@ public class JNLPClassLoader extends URLClassLoader { if (strict) fillInPartJars(initialJars); // add in each initial part's lazy jars - if (JNLPRuntime.isVerifying()) { + if (JNLPRuntime.isVerifying()) { - JarSigner js; - waitForJars(initialJars); //download the jars first. + JarSigner js; + waitForJars(initialJars); //download the jars first. - try { - js = verifyJars(initialJars); - } catch (Exception e) { - //we caught an Exception from the JarSigner class. - //Note: one of these exceptions could be from not being able - //to read the cacerts or trusted.certs files. - e.printStackTrace(); - throw new LaunchException(null, null, R("LSFatal"), + try { + js = verifyJars(initialJars); + } catch (Exception e) { + //we caught an Exception from the JarSigner class. + //Note: one of these exceptions could be from not being able + //to read the cacerts or trusted.certs files. + e.printStackTrace(); + throw new LaunchException(null, null, R("LSFatal"), R("LCInit"), R("LFatalVerification"), R("LFatalVerificationInfo")); - } + } - //Case when at least one jar has some signing - if (js.anyJarsSigned()){ - signing = true; + //Case when at least one jar has some signing + if (js.anyJarsSigned()) { + signing = true; - if (!js.allJarsSigned() && + if (!js.allJarsSigned() && !SecurityWarning.showNotAllSignedWarningDialog(file)) - throw new LaunchException(file, null, R("LSFatal"), R("LCClient"), R("LSignedAppJarUsingUnsignedJar"), R("LSignedAppJarUsingUnsignedJarInfo")); + throw new LaunchException(file, null, R("LSFatal"), R("LCClient"), R("LSignedAppJarUsingUnsignedJar"), R("LSignedAppJarUsingUnsignedJarInfo")); + + //user does not trust this publisher + if (!js.getAlreadyTrustPublisher()) { + checkTrustWithUser(js); + } else { + /** + * If the user trusts this publisher (i.e. the publisher's certificate + * is in the user's trusted.certs file), we do not show any dialogs. + */ + } + } else { + signing = false; + //otherwise this jar is simply unsigned -- make sure to ask + //for permission on certain actions + } + } - //user does not trust this publisher - if (!js.getAlreadyTrustPublisher()) { - checkTrustWithUser(js); - } else { - /** - * If the user trusts this publisher (i.e. the publisher's certificate - * is in the user's trusted.certs file), we do not show any dialogs. - */ - } - } else { + for (JARDesc jarDesc : file.getResources().getJARs()) { + try { + File cachedFile = tracker.getCacheFile(jarDesc.getLocation()); - signing = false; - //otherwise this jar is simply unsigned -- make sure to ask - //for permission on certain actions - } + if (cachedFile == null) { + System.err.println("JAR " + jarDesc.getLocation() + " not found. Continuing."); + continue; // JAR not found. Keep going. } - for (JARDesc jarDesc: file.getResources().getJARs()) { - try { - File cachedFile = tracker.getCacheFile(jarDesc.getLocation()); - - if (cachedFile == null) { - System.err.println("JAR " + jarDesc.getLocation() + " not found. Continuing."); - continue; // JAR not found. Keep going. - } - - // TODO: Should be toURI().toURL() - URL location = cachedFile.toURL(); - SecurityDesc jarSecurity = file.getSecurity(); + // TODO: Should be toURI().toURL() + URL location = cachedFile.toURL(); + SecurityDesc jarSecurity = file.getSecurity(); - if (file instanceof PluginBridge) { + if (file instanceof PluginBridge) { - URL codebase = null; + URL codebase = null; - if (file.getCodeBase() != null) { - codebase = file.getCodeBase(); - } else { - //Fixme: codebase should be the codebase of the Main Jar not - //the location. Although, it still works in the current state. - codebase = file.getResources().getMainJAR().getLocation(); - } + if (file.getCodeBase() != null) { + codebase = file.getCodeBase(); + } else { + //Fixme: codebase should be the codebase of the Main Jar not + //the location. Although, it still works in the current state. + codebase = file.getResources().getMainJAR().getLocation(); + } - jarSecurity = new SecurityDesc(file, + jarSecurity = new SecurityDesc(file, SecurityDesc.ALL_PERMISSIONS, codebase.getHost()); - } - - jarLocationSecurityMap.put(location, jarSecurity); - } catch (MalformedURLException mfe) { - System.err.println(mfe.getMessage()); - } } + jarLocationSecurityMap.put(location, jarSecurity); + } catch (MalformedURLException mfe) { + System.err.println(mfe.getMessage()); + } + } + activateJars(initialJars); } private void checkTrustWithUser(JarSigner js) throws LaunchException { if (!js.getRootInCacerts()) { //root cert is not in cacerts boolean b = SecurityWarning.showCertWarningDialog( - AccessType.UNVERIFIED, file, js); + AccessType.UNVERIFIED, file, js); if (!b) throw new LaunchException(null, null, R("LSFatal"), - R("LCLaunching"), R("LNotVerified"), ""); + R("LCLaunching"), R("LNotVerified"), ""); } else if (js.getRootInCacerts()) { //root cert is in cacerts boolean b = false; if (js.noSigningIssues()) @@ -516,7 +511,7 @@ public class JNLPClassLoader extends URLClassLoader { AccessType.SIGNING_ERROR, file, js); if (!b) throw new LaunchException(null, null, R("LSFatal"), - R("LCLaunching"), R("LCancelOnUserRequest"), ""); + R("LCLaunching"), R("LCancelOnUserRequest"), ""); } } @@ -527,7 +522,7 @@ public class JNLPClassLoader extends URLClassLoader { * loaded from the codebase are not cached. */ public void enableCodeBase() { - addURL( file.getCodeBase() ); // nothing happens if called more that once? + addURL(file.getCodeBase()); // nothing happens if called more that once? } /** @@ -569,7 +564,7 @@ public class JNLPClassLoader extends URLClassLoader { // access w/o security dialog once we actually check certificates. // copy security permissions from SecurityDesc element - if (security != null) { + if (security != null) { // Security desc. is used only to track security settings for the // application. However, an application may comprise of multiple // jars, and as such, security must be evaluated on a per jar basis. @@ -582,8 +577,7 @@ public class JNLPClassLoader extends URLClassLoader { // 2. ALL or J2EE permissions must be requested (note: plugin requests ALL automatically) if (cs.getCodeSigners() != null && (getCodeSourceSecurity(cs.getLocation()).getSecurityType().equals(SecurityDesc.ALL_PERMISSIONS) || - getCodeSourceSecurity(cs.getLocation()).getSecurityType().equals(SecurityDesc.J2EE_PERMISSIONS)) - ) { + getCodeSourceSecurity(cs.getLocation()).getSecurityType().equals(SecurityDesc.J2EE_PERMISSIONS))) { permissions = getCodeSourceSecurity(cs.getLocation()).getPermissions(); } @@ -594,12 +588,12 @@ public class JNLPClassLoader extends URLClassLoader { } // add in permission to read the cached JAR files - for (int i=0; i < resourcePermissions.size(); i++) + for (int i = 0; i < resourcePermissions.size(); i++) result.add(resourcePermissions.get(i)); // add in the permissions that the user granted. - for (int i=0; i < runtimePermissions.size(); i++) - result.add(runtimePermissions.get(i)); + for (int i = 0; i < runtimePermissions.size(); i++) + result.add(runtimePermissions.get(i)); return result; } @@ -614,10 +608,10 @@ public class JNLPClassLoader extends URLClassLoader { * in the same part). */ protected void fillInPartJars(List<JARDesc> jars) { - for (int i=0; i < jars.size(); i++) { + for (int i = 0; i < jars.size(); i++) { String part = jars.get(i).getPart(); - for (int a=0; a < available.size(); a++) { + for (int a = 0; a < available.size(); a++) { JARDesc jar = available.get(a); if (part != null && part.equals(jar.getPart())) @@ -642,7 +636,7 @@ public class JNLPClassLoader extends URLClassLoader { // transfer the Jars waitForJars(jars); - for (int i=0; i < jars.size(); i++) { + for (int i = 0; i < jars.size(); i++) { JARDesc jar = jars.get(i); available.remove(jar); @@ -725,13 +719,13 @@ public class JNLPClassLoader extends URLClassLoader { } jarSecurity = new SecurityDesc(file, - SecurityDesc.ALL_PERMISSIONS, - codebase.getHost()); + SecurityDesc.ALL_PERMISSIONS, + codebase.getHost()); } jarLocationSecurityMap.put(fileURL, jarSecurity); - } catch (MalformedURLException mfue) { + } catch (MalformedURLException mfue) { if (JNLPRuntime.isDebug()) System.err.println("Unable to add extracted nested jar to classpath"); @@ -756,7 +750,7 @@ public class JNLPClassLoader extends URLClassLoader { } if (JNLPRuntime.isDebug()) - System.err.println("Activate jar: "+location); + System.err.println("Activate jar: " + location); } catch (Exception ex) { if (JNLPRuntime.isDebug()) @@ -781,7 +775,7 @@ public class JNLPClassLoader extends URLClassLoader { */ protected void activateNative(JARDesc jar) { if (JNLPRuntime.isDebug()) - System.out.println("Activate native: "+jar.getLocation()); + System.out.println("Activate native: " + jar.getLocation()); File localFile = tracker.getCacheFile(jar.getLocation()); if (localFile == null) @@ -803,10 +797,10 @@ public class JNLPClassLoader extends URLClassLoader { String name = new File(e.getName()).getName(); boolean isLibrary = false; - for (String suffix: librarySuffixes) { + for (String suffix : librarySuffixes) { if (name.endsWith(suffix)) { - isLibrary = true; - break; + isLibrary = true; + break; } } if (!isLibrary) { @@ -824,8 +818,7 @@ public class JNLPClassLoader extends URLClassLoader { new FileOutputStream(outFile)); } - } - catch (IOException ex) { + } catch (IOException ex) { if (JNLPRuntime.isDebug()) ex.printStackTrace(); } @@ -879,7 +872,7 @@ public class JNLPClassLoader extends URLClassLoader { protected String findLibrary(String lib) { String syslib = System.mapLibraryName(lib); - for (File dir: getNativeDirectories()) { + for (File dir : getNativeDirectories()) { File target = new File(dir, syslib); if (target.exists()) return target.toString(); @@ -896,7 +889,7 @@ public class JNLPClassLoader extends URLClassLoader { * Try to find the library path from another peer classloader. */ protected String findLibraryExt(String lib) { - for (int i=0; i < loaders.length; i++) { + for (int i = 0; i < loaders.length; i++) { String result = null; if (loaders[i] != this) @@ -918,7 +911,7 @@ public class JNLPClassLoader extends URLClassLoader { private void waitForJars(List jars) { URL urls[] = new URL[jars.size()]; - for (int i=0; i < jars.size(); i++) { + for (int i = 0; i < jars.size(); i++) { JARDesc jar = (JARDesc) jars.get(i); urls[i] = jar.getLocation(); @@ -932,18 +925,18 @@ public class JNLPClassLoader extends URLClassLoader { * * @param jars the jars to be verified. */ - private JarSigner verifyJars(List<JARDesc> jars) throws Exception { + private JarSigner verifyJars(List<JARDesc> jars) throws Exception { - js = new JarSigner(); - js.verifyJars(jars, tracker); - return js; - } + js = new JarSigner(); + js.verifyJars(jars, tracker); + return js; + } /** * Find the loaded class in this loader or any of its extension loaders. */ protected Class findLoadedClassAll(String name) { - for (int i=0; i < loaders.length; i++) { + for (int i = 0; i < loaders.length; i++) { Class result = null; if (loaders[i] == this) @@ -975,8 +968,8 @@ public class JNLPClassLoader extends URLClassLoader { parent = ClassLoader.getSystemClassLoader(); return parent.loadClass(name); + } catch (ClassNotFoundException ex) { } - catch (ClassNotFoundException ex) { } } // filter out 'bad' package names like java, javax @@ -992,13 +985,13 @@ public class JNLPClassLoader extends URLClassLoader { // Currently this loads jars directly from the site. We cannot cache it because this // call is initiated from within the applet, which does not have disk read/write permissions - for (JarIndex index: jarIndexes) { + for (JarIndex index : jarIndexes) { // Non-generic code in sun.misc.JarIndex @SuppressWarnings("unchecked") - LinkedList<String> jarList = index.get(name.replace('.', '/')); + LinkedList<String> jarList = index.get(name.replace('.', '/')); if (jarList != null) { - for (String jarName: jarList) { + for (String jarName : jarList) { JARDesc desc; try { desc = new JARDesc(new URL(file.getCodeBase(), jarName), @@ -1012,7 +1005,7 @@ public class JNLPClassLoader extends URLClassLoader { tracker.addResource(desc.getLocation(), desc.getVersion(), JNLPRuntime.getDefaultUpdatePolicy() - ); + ); URL remoteURL; try { @@ -1047,15 +1040,15 @@ public class JNLPClassLoader extends URLClassLoader { * Find the class in this loader or any of its extension loaders. */ protected Class findClass(String name) throws ClassNotFoundException { - for (int i=0; i < loaders.length; i++) { + for (int i = 0; i < loaders.length; i++) { try { if (loaders[i] == this) return super.findClass(name); else return loaders[i].findClass(name); + } catch (ClassNotFoundException ex) { + } catch (ClassFormatError cfe) { } - catch(ClassNotFoundException ex) { } - catch(ClassFormatError cfe) {} } throw new ClassNotFoundException(name); @@ -1073,8 +1066,7 @@ public class JNLPClassLoader extends URLClassLoader { // find it try { return findClass(name); - } - catch(ClassNotFoundException ex) { + } catch (ClassNotFoundException ex) { } // add resources until found @@ -1086,8 +1078,7 @@ public class JNLPClassLoader extends URLClassLoader { try { return addedTo.findClass(name); - } - catch(ClassNotFoundException ex) { + } catch (ClassNotFoundException ex) { } } } @@ -1099,7 +1090,7 @@ public class JNLPClassLoader extends URLClassLoader { public URL getResource(String name) { URL result = super.getResource(name); - for (int i=1; i < loaders.length; i++) + for (int i = 1; i < loaders.length; i++) if (result == null) result = loaders[i].getResource(name); @@ -1114,7 +1105,7 @@ public class JNLPClassLoader extends URLClassLoader { public Enumeration<URL> findResources(String name) throws IOException { Vector<URL> resources = new Vector<URL>(); - for (int i=0; i < loaders.length; i++) { + for (int i = 0; i < loaders.length; i++) { Enumeration<URL> e; if (loaders[i] == this) @@ -1147,7 +1138,7 @@ public class JNLPClassLoader extends URLClassLoader { // go through available, check tracker for it and all of its // part brothers being available immediately, add them. - for (int i=1; i < loaders.length; i++) { + for (int i = 1; i < loaders.length; i++) { loaders[i].addAvailable(); } } @@ -1162,7 +1153,7 @@ public class JNLPClassLoader extends URLClassLoader { */ protected JNLPClassLoader addNextResource() { if (available.size() == 0) { - for (int i=1; i < loaders.length; i++) { + for (int i = 1; i < loaders.length; i++) { JNLPClassLoader result = loaders[i].addNextResource(); if (result != null) @@ -1207,50 +1198,50 @@ public class JNLPClassLoader extends URLClassLoader { return file.getFileLocation().toString(); } - public boolean getSigning() { - return signing; - } + public boolean getSigning() { + return signing; + } - protected SecurityDesc getSecurity() { - return security; - } + protected SecurityDesc getSecurity() { + return security; + } - /** - * Returns the security descriptor for given code source URL - * - * @param source The code source - * @return The SecurityDescriptor for that source - */ + /** + * Returns the security descriptor for given code source URL + * + * @param source The code source + * @return The SecurityDescriptor for that source + */ - protected SecurityDesc getCodeSourceSecurity(URL source) { - return jarLocationSecurityMap.get(source); - } + protected SecurityDesc getCodeSourceSecurity(URL source) { + return jarLocationSecurityMap.get(source); + } - /** - * Merges the code source/security descriptor mapping from another loader - * - * @param extLoader The loader form which to merge - * @throws SecurityException if the code is called from an untrusted source - */ - private void merge(JNLPClassLoader extLoader) { + /** + * Merges the code source/security descriptor mapping from another loader + * + * @param extLoader The loader form which to merge + * @throws SecurityException if the code is called from an untrusted source + */ + private void merge(JNLPClassLoader extLoader) { - try { - System.getSecurityManager().checkPermission(new AllPermission()); - } catch (SecurityException se) { - throw new SecurityException("JNLPClassLoader() may only be called from trusted sources!"); - } + try { + System.getSecurityManager().checkPermission(new AllPermission()); + } catch (SecurityException se) { + throw new SecurityException("JNLPClassLoader() may only be called from trusted sources!"); + } - // jars - for (URL u : extLoader.getURLs()) - addURL(u); + // jars + for (URL u : extLoader.getURLs()) + addURL(u); - // native search paths - for (File nativeDirectory: extLoader.getNativeDirectories()) + // native search paths + for (File nativeDirectory : extLoader.getNativeDirectories()) addNativeDirectory(nativeDirectory); // security descriptors - for (URL key: extLoader.jarLocationSecurityMap.keySet()) { - jarLocationSecurityMap.put(key, extLoader.jarLocationSecurityMap.get(key)); - } + for (URL key : extLoader.jarLocationSecurityMap.keySet()) { + jarLocationSecurityMap.put(key, extLoader.jarLocationSecurityMap.get(key)); } + } } diff --git a/netx/net/sourceforge/jnlp/runtime/JNLPPolicy.java b/netx/net/sourceforge/jnlp/runtime/JNLPPolicy.java index d839fbd..62b6967 100644 --- a/netx/net/sourceforge/jnlp/runtime/JNLPPolicy.java +++ b/netx/net/sourceforge/jnlp/runtime/JNLPPolicy.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.runtime; import java.security.*; @@ -41,7 +40,6 @@ public class JNLPPolicy extends Policy { /** the previous policy */ private static Policy systemPolicy; - protected JNLPPolicy() { shellSource = JNLPPolicy.class.getProtectionDomain().getCodeSource(); systemSource = Policy.class.getProtectionDomain().getCodeSource(); @@ -59,19 +57,19 @@ public class JNLPPolicy extends Policy { // if we check the SecurityDesc here then keep in mind that // code can add properties at runtime to the ResourcesDesc! if (JNLPRuntime.getApplication() != null) { - if (JNLPRuntime.getApplication().getClassLoader() instanceof JNLPClassLoader) { - JNLPClassLoader cl = (JNLPClassLoader) JNLPRuntime.getApplication().getClassLoader(); + if (JNLPRuntime.getApplication().getClassLoader() instanceof JNLPClassLoader) { + JNLPClassLoader cl = (JNLPClassLoader) JNLPRuntime.getApplication().getClassLoader(); - PermissionCollection clPermissions = cl.getPermissions(source); + PermissionCollection clPermissions = cl.getPermissions(source); - // systempolicy permissions need to be accounted for as well - CodeSource appletCS = new CodeSource(JNLPRuntime.getApplication().getJNLPFile().getSourceLocation(), (java.security.cert.Certificate[]) null); - Enumeration e = systemPolicy.getPermissions(appletCS).elements(); + // systempolicy permissions need to be accounted for as well + CodeSource appletCS = new CodeSource(JNLPRuntime.getApplication().getJNLPFile().getSourceLocation(), (java.security.cert.Certificate[]) null); + Enumeration e = systemPolicy.getPermissions(appletCS).elements(); while (e.hasMoreElements()) clPermissions.add((Permission) e.nextElement()); - return clPermissions; - } + return clPermissions; + } } // delegate to original Policy object; required to run under WebStart @@ -91,13 +89,13 @@ public class JNLPPolicy extends Policy { private Permissions getAllPermissions() { Permissions result = new Permissions(); - result.add( new AllPermission() ); + result.add(new AllPermission()); return result; } - public boolean implies(ProtectionDomain domain, Permission permission) { - //Include the permissions that may be added during runtime. - PermissionCollection pc = getPermissions(domain.getCodeSource()); - return super.implies(domain, permission) || pc.implies(permission); - } + public boolean implies(ProtectionDomain domain, Permission permission) { + //Include the permissions that may be added during runtime. + PermissionCollection pc = getPermissions(domain.getCodeSource()); + return super.implies(domain, permission) || pc.implies(permission); + } } diff --git a/netx/net/sourceforge/jnlp/runtime/JNLPRuntime.java b/netx/net/sourceforge/jnlp/runtime/JNLPRuntime.java index 848a198..1e3a91c 100644 --- a/netx/net/sourceforge/jnlp/runtime/JNLPRuntime.java +++ b/netx/net/sourceforge/jnlp/runtime/JNLPRuntime.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.runtime; import java.io.*; @@ -43,7 +42,6 @@ import net.sourceforge.jnlp.security.VariableX509TrustManager; import net.sourceforge.jnlp.services.*; import net.sourceforge.jnlp.util.*; - /** * Configure and access the runtime environment. This class * stores global jnlp properties such as default download @@ -98,8 +96,8 @@ public class JNLPRuntime { /** whether netx is in command-line mode (headless) */ private static boolean headless = false; - /** whether we'll be checking for jar signing */ - private static boolean verify = true; + /** whether we'll be checking for jar signing */ + private static boolean verify = true; /** whether the runtime uses security */ private static boolean securityEnabled = true; @@ -169,7 +167,7 @@ public class JNLPRuntime { //Setting the system property for javawebstart's version. //The version stored will be the same as java's version. System.setProperty("javawebstart.version", "javaws-" + - System.getProperty("java.version")); + System.getProperty("java.version")); if (headless == false) checkHeadless(); @@ -333,12 +331,13 @@ public class JNLPRuntime { return headless; } - /** - * Returns whether we are verifying code signing. - */ - public static boolean isVerifying() { - return verify; - } + /** + * Returns whether we are verifying code signing. + */ + public static boolean isVerifying() { + return verify; + } + /** * Sets whether the JNLP client will use any AWT/Swing * components. In headless mode, client features that use the @@ -352,13 +351,13 @@ public class JNLPRuntime { headless = enabled; } - /** - * Sets whether we will verify code signing. - * @throws IllegalStateException if the runtime was previously initialized - */ + /** + * Sets whether we will verify code signing. + * @throws IllegalStateException if the runtime was previously initialized + */ public static void setVerify(boolean enabled) { - checkInitialized(); - verify = enabled; + checkInitialized(); + verify = enabled; } /** @@ -518,12 +517,11 @@ public class JNLPRuntime { return null; else return result; - } - catch (Exception ex) { + } catch (Exception ex) { if (!key.equals("RNoResource")) - return getMessage("RNoResource", new Object[] {key}); + return getMessage("RNoResource", new Object[] { key }); else - return "Missing resource: "+key; + return "Missing resource: " + key; } } @@ -578,8 +576,7 @@ public class JNLPRuntime { try { if ("true".equalsIgnoreCase(System.getProperty("java.awt.headless"))) headless = true; - } - catch (SecurityException ex) { + } catch (SecurityException ex) { } } @@ -589,8 +586,7 @@ public class JNLPRuntime { private static void loadResources() { try { resources = ResourceBundle.getBundle("net.sourceforge.jnlp.resources.Messages"); - } - catch (Exception ex) { + } catch (Exception ex) { throw new IllegalStateException("Missing resource bundle in netx.jar:net/sourceforge/jnlp/resource/Messages.properties"); } } @@ -605,14 +601,12 @@ public class JNLPRuntime { try { windowIcon = new javax.swing.ImageIcon((new sun.misc.Launcher()) .getClassLoader().getResource("net/sourceforge/jnlp/resources/netx-icon.png")).getImage(); - } - catch (Exception ex) { + } catch (Exception ex) { if (JNLPRuntime.isDebug()) ex.printStackTrace(); } } - public static void setInitialArgments(List<String> args) { checkInitialized(); SecurityManager securityManager = System.getSecurityManager(); diff --git a/netx/net/sourceforge/jnlp/runtime/JNLPSecurityManager.java b/netx/net/sourceforge/jnlp/runtime/JNLPSecurityManager.java index 32a54f8..38a0545 100644 --- a/netx/net/sourceforge/jnlp/runtime/JNLPSecurityManager.java +++ b/netx/net/sourceforge/jnlp/runtime/JNLPSecurityManager.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.runtime; import static net.sourceforge.jnlp.runtime.Translator.R; @@ -95,14 +94,14 @@ class JNLPSecurityManager extends AWTSecurityManager { /** this exception prevents exiting the JVM */ private SecurityException closeAppEx = // making here prevents huge stack traces - new SecurityException(R("RShutdown")); + new SecurityException(R("RShutdown")); /** weak list of windows created */ private WeakList<Window> weakWindows = new WeakList<Window>(); /** weak list of applications corresponding to window list */ private WeakList<ApplicationInstance> weakApplications = - new WeakList<ApplicationInstance>(); + new WeakList<ApplicationInstance>(); /** weak reference to most app who's windows was most recently activated */ private WeakReference activeApplication = null; @@ -148,7 +147,7 @@ class JNLPSecurityManager extends AWTSecurityManager { if (exitClass == null) return true; - for (int i=0; i < stack.length; i++) + for (int i = 0; i < stack.length; i++) if (stack[i] == exitClass) return true; @@ -182,7 +181,7 @@ class JNLPSecurityManager extends AWTSecurityManager { * call from event dispatch thread). */ protected ApplicationInstance getApplication(Window window) { - for (int i = weakWindows.size(); i-->0;) { + for (int i = weakWindows.size(); i-- > 0;) { Window w = weakWindows.get(i); if (w == null) { weakWindows.remove(i); @@ -201,17 +200,17 @@ class JNLPSecurityManager extends AWTSecurityManager { */ protected ApplicationInstance getApplication(Class stack[], int maxDepth) { if (maxDepth <= 0) - maxDepth = stack.length; + maxDepth = stack.length; // this needs to be tightened up - for (int i=0; i < stack.length && i < maxDepth; i++) { - if (stack[i].getClassLoader() instanceof JNLPClassLoader) { - JNLPClassLoader loader = (JNLPClassLoader) stack[i].getClassLoader(); + for (int i = 0; i < stack.length && i < maxDepth; i++) { + if (stack[i].getClassLoader() instanceof JNLPClassLoader) { + JNLPClassLoader loader = (JNLPClassLoader) stack[i].getClassLoader(); - if (loader != null && loader.getApplication() != null) { - return loader.getApplication(); - } + if (loader != null && loader.getApplication() != null) { + return loader.getApplication(); } + } } return null; @@ -243,113 +242,112 @@ class JNLPSecurityManager extends AWTSecurityManager { // System.out.println("Checking permission: " + perm.toString()); if (!JNLPRuntime.isWebstartApplication() && - ("setPolicy".equals(name) || "setSecurityManager".equals(name))) + ("setPolicy".equals(name) || "setSecurityManager".equals(name))) throw new SecurityException(R("RCantReplaceSM")); try { // deny all permissions to stopped applications - // The call to getApplication() below might not work if an - // application hasn't been fully initialized yet. -// if (JNLPRuntime.isDebug()) { -// if (!"getClassLoader".equals(name)) { -// ApplicationInstance app = getApplication(); -// if (app != null && !app.isRunning()) -// throw new SecurityException(R("RDenyStopped")); -// } -// } + // The call to getApplication() below might not work if an + // application hasn't been fully initialized yet. + // if (JNLPRuntime.isDebug()) { + // if (!"getClassLoader".equals(name)) { + // ApplicationInstance app = getApplication(); + // if (app != null && !app.isRunning()) + // throw new SecurityException(R("RDenyStopped")); + // } + // } + + try { + super.checkPermission(perm); + } catch (SecurityException se) { + + //This section is a special case for dealing with SocketPermissions. + if (JNLPRuntime.isDebug()) + System.err.println("Requesting permission: " + perm.toString()); + + //Change this SocketPermission's action to connect and accept + //(and resolve). This is to avoid asking for connect permission + //on every address resolve. + Permission tmpPerm = null; + if (perm instanceof SocketPermission) { + tmpPerm = new SocketPermission(perm.getName(), + SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION); + + // before proceeding, check if we are trying to connect to same origin + ApplicationInstance app = getApplication(); + JNLPFile file = app.getJNLPFile(); + + String srcHost = file.getSourceLocation().getAuthority(); + String destHost = name; + + // host = abc.xyz.com or abc.xyz.com:<port> + if (destHost.indexOf(':') >= 0) + destHost = destHost.substring(0, destHost.indexOf(':')); + + // host = abc.xyz.com + String[] hostComponents = destHost.split("\\."); + int length = hostComponents.length; + if (length >= 2) { + + // address is in xxx.xxx.xxx format + destHost = hostComponents[length - 2] + "." + hostComponents[length - 1]; + + // host = xyz.com i.e. origin + boolean isDestHostName = false; + + // make sure that it is not an ip address try { - super.checkPermission(perm); - } catch (SecurityException se) { - - //This section is a special case for dealing with SocketPermissions. - if (JNLPRuntime.isDebug()) - System.err.println("Requesting permission: " + perm.toString()); - - //Change this SocketPermission's action to connect and accept - //(and resolve). This is to avoid asking for connect permission - //on every address resolve. - Permission tmpPerm = null; - if (perm instanceof SocketPermission) { - tmpPerm = new SocketPermission(perm.getName(), - SecurityConstants.SOCKET_CONNECT_ACCEPT_ACTION); + Integer.parseInt(hostComponents[length - 1]); + } catch (NumberFormatException e) { + isDestHostName = true; + } - // before proceeding, check if we are trying to connect to same origin - ApplicationInstance app = getApplication(); - JNLPFile file = app.getJNLPFile(); - - String srcHost = file.getSourceLocation().getAuthority(); - String destHost = name; - - // host = abc.xyz.com or abc.xyz.com:<port> - if (destHost.indexOf(':') >= 0) - destHost = destHost.substring(0, destHost.indexOf(':')); - - // host = abc.xyz.com - String[] hostComponents = destHost.split("\\."); - - int length = hostComponents.length; - if (length >= 2) { - - // address is in xxx.xxx.xxx format - destHost = hostComponents[length -2] + "." + hostComponents[length -1]; - - // host = xyz.com i.e. origin - boolean isDestHostName = false; - - // make sure that it is not an ip address - try { - Integer.parseInt(hostComponents[length -1]); - } catch (NumberFormatException e) { - isDestHostName = true; - } - - if (isDestHostName) { - // okay, destination is hostname. Now figure out if it is a subset of origin - if (srcHost.endsWith(destHost)) { - addPermission(tmpPerm); - return; - } - } - } - - } else if (perm instanceof SecurityPermission) { - - // JCE's initialization requires putProviderProperty permission - if (perm.equals(new SecurityPermission("putProviderProperty.SunJCE"))) { - if (inTrustedCallChain("com.sun.crypto.provider.SunJCE", "run")) { - return; - } - } - - } else if (perm instanceof RuntimePermission) { - - // KeyGenerator's init method requires internal spec access - if (perm.equals(new SecurityPermission("accessClassInPackage.sun.security.internal.spec"))) { - if (inTrustedCallChain("javax.crypto.KeyGenerator", "init")) { - return; - } - } - - } else { - tmpPerm = perm; - } - - if (tmpPerm != null) { - //askPermission will only prompt the user on SocketPermission - //meaning we're denying all other SecurityExceptions that may arise. - if (askPermission(tmpPerm)) { - addPermission(tmpPerm); - //return quietly. - } else { - throw se; - } - } + if (isDestHostName) { + // okay, destination is hostname. Now figure out if it is a subset of origin + if (srcHost.endsWith(destHost)) { + addPermission(tmpPerm); + return; + } } - } - catch (SecurityException ex) { + } + + } else if (perm instanceof SecurityPermission) { + + // JCE's initialization requires putProviderProperty permission + if (perm.equals(new SecurityPermission("putProviderProperty.SunJCE"))) { + if (inTrustedCallChain("com.sun.crypto.provider.SunJCE", "run")) { + return; + } + } + + } else if (perm instanceof RuntimePermission) { + + // KeyGenerator's init method requires internal spec access + if (perm.equals(new SecurityPermission("accessClassInPackage.sun.security.internal.spec"))) { + if (inTrustedCallChain("javax.crypto.KeyGenerator", "init")) { + return; + } + } + + } else { + tmpPerm = perm; + } + + if (tmpPerm != null) { + //askPermission will only prompt the user on SocketPermission + //meaning we're denying all other SecurityExceptions that may arise. + if (askPermission(tmpPerm)) { + addPermission(tmpPerm); + //return quietly. + } else { + throw se; + } + } + } + } catch (SecurityException ex) { if (JNLPRuntime.isDebug()) { - System.out.println("Denying permission: "+perm); + System.out.println("Denying permission: " + perm); } throw ex; } @@ -365,9 +363,9 @@ class JNLPSecurityManager extends AWTSecurityManager { */ private boolean inTrustedCallChain(String className, String methodName) { - StackTraceElement[] stack = Thread.currentThread().getStackTrace(); + StackTraceElement[] stack = Thread.currentThread().getStackTrace(); - for (int i=0; i < stack.length; i++) { + for (int i = 0; i < stack.length; i++) { // Everything up to the desired class/method must be trusted if (!stack[i].getClass().getProtectionDomain().implies(new AllPermission())) { @@ -375,7 +373,7 @@ class JNLPSecurityManager extends AWTSecurityManager { } if (stack[i].getClassName().equals(className) && - stack[i].getMethodName().equals(methodName)) { + stack[i].getMethodName().equals(methodName)) { return true; } } @@ -388,14 +386,14 @@ class JNLPSecurityManager extends AWTSecurityManager { * @param perm the permission to be granted * @return true if the permission was granted, false otherwise. */ - private boolean askPermission(Permission perm) { + private boolean askPermission(Permission perm) { ApplicationInstance app = getApplication(); if (app != null && !app.isSigned()) { - if (perm instanceof SocketPermission + if (perm instanceof SocketPermission && ServiceUtil.checkAccess(AccessType.NETWORK, perm.getName())) { - return true; - } + return true; + } } return false; @@ -408,17 +406,17 @@ class JNLPSecurityManager extends AWTSecurityManager { private void addPermission(Permission perm) { if (JNLPRuntime.getApplication().getClassLoader() instanceof JNLPClassLoader) { - JNLPClassLoader cl = (JNLPClassLoader) JNLPRuntime.getApplication().getClassLoader(); - cl.addPermission(perm); - if (JNLPRuntime.isDebug()) { - if (cl.getPermissions(null).implies(perm)) - System.err.println("Added permission: " + perm.toString()); - else - System.err.println("Unable to add permission: " + perm.toString()); - } + JNLPClassLoader cl = (JNLPClassLoader) JNLPRuntime.getApplication().getClassLoader(); + cl.addPermission(perm); + if (JNLPRuntime.isDebug()) { + if (cl.getPermissions(null).implies(perm)) + System.err.println("Added permission: " + perm.toString()); + else + System.err.println("Unable to add permission: " + perm.toString()); + } } else { - if (JNLPRuntime.isDebug()) - System.err.println("Unable to add permission: " + perm + ", classloader not JNLP."); + if (JNLPRuntime.isDebug()) + System.err.println("Unable to add permission: " + perm + ", classloader not JNLP."); } } @@ -435,7 +433,7 @@ class JNLPSecurityManager extends AWTSecurityManager { Window w = (Window) window; if (JNLPRuntime.isDebug()) - System.err.println("SM: app: "+app.getTitle()+" is adding a window: "+window+" with appContext "+AppContext.getAppContext()); + System.err.println("SM: app: " + app.getTitle() + " is adding a window: " + window + " with appContext " + AppContext.getAppContext()); weakWindows.add(w); // for mapping window -> app weakApplications.add(app); @@ -445,9 +443,9 @@ class JNLPSecurityManager extends AWTSecurityManager { // change coffee cup to netx for default icon if (window instanceof Window) - for (Window w = (Window)window; w != null; w = w.getOwner()) + for (Window w = (Window) window; w != null; w = w.getOwner()) if (window instanceof Frame) - ((Frame)window).setIconImage(JNLPRuntime.getWindowIcon()); + ((Frame) window).setIconImage(JNLPRuntime.getWindowIcon()); // todo: set awt.appletWarning to custom message // todo: logo on with glass pane on JFrame/JWindow? @@ -473,9 +471,9 @@ class JNLPSecurityManager extends AWTSecurityManager { // applets are not allowed to exit, but the plugin main class (primordial loader) is Class stack[] = getClassContext(); if (!exitAllowed) { - for (int i=0; i < stack.length; i++) - if (stack[i].getClassLoader() != null) - throw new AccessControlException("Applets may not call System.exit()"); + for (int i = 0; i < stack.length; i++) + if (stack[i].getClassLoader() != null) + throw new AccessControlException("Applets may not call System.exit()"); } super.checkExit(status); diff --git a/netx/net/sourceforge/jnlp/security/AccessWarningPane.java b/netx/net/sourceforge/jnlp/security/AccessWarningPane.java index 68b1ef4..d83e45c 100644 --- a/netx/net/sourceforge/jnlp/security/AccessWarningPane.java +++ b/netx/net/sourceforge/jnlp/security/AccessWarningPane.java @@ -71,142 +71,141 @@ import net.sourceforge.jnlp.util.FileUtils; */ public class AccessWarningPane extends SecurityDialogPanel { - JCheckBox alwaysAllow; - Object[] extras; - - public AccessWarningPane(SecurityWarningDialog x, CertVerifier certVerifier) { - super(x, certVerifier); - addComponents(); + JCheckBox alwaysAllow; + Object[] extras; + + public AccessWarningPane(SecurityWarningDialog x, CertVerifier certVerifier) { + super(x, certVerifier); + addComponents(); + } + + public AccessWarningPane(SecurityWarningDialog x, Object[] extras, CertVerifier certVerifier) { + super(x, certVerifier); + this.extras = extras; + addComponents(); + } + + /** + * Creates the actual GUI components, and adds it to this panel + */ + private void addComponents() { + AccessType type = parent.getAccessType(); + JNLPFile file = parent.getFile(); + + String name = ""; + String publisher = ""; + String from = ""; + + //We don't worry about exceptions when trying to fill in + //these strings -- we just want to fill in as many as possible. + try { + name = file.getInformation().getTitle() != null ? file.getInformation().getTitle() : R("SNoAssociatedCertificate"); + } catch (Exception e) { } - public AccessWarningPane(SecurityWarningDialog x, Object[] extras, CertVerifier certVerifier) { - super(x, certVerifier); - this.extras = extras; - addComponents(); + try { + publisher = file.getInformation().getVendor() != null ? file.getInformation().getVendor() : R("SNoAssociatedCertificate"); + } catch (Exception e) { } - /** - * Creates the actual GUI components, and adds it to this panel - */ - private void addComponents() { - AccessType type = parent.getAccessType(); - JNLPFile file = parent.getFile(); - - String name = ""; - String publisher = ""; - String from = ""; - - //We don't worry about exceptions when trying to fill in - //these strings -- we just want to fill in as many as possible. - try { - name = file.getInformation().getTitle() != null ? file.getInformation().getTitle() : R("SNoAssociatedCertificate"); - } catch (Exception e) { - } - - try { - publisher = file.getInformation().getVendor() != null ? file.getInformation().getVendor() : R("SNoAssociatedCertificate"); - } catch (Exception e) { - } + try { + from = !file.getInformation().getHomepage().toString().equals("") ? file.getInformation().getHomepage().toString() : file.getSourceLocation().getAuthority(); + } catch (Exception e) { + from = file.getSourceLocation().getAuthority(); + } - try { - from = !file.getInformation().getHomepage().toString().equals("") ? file.getInformation().getHomepage().toString() : file.getSourceLocation().getAuthority(); - } catch (Exception e) { - from = file.getSourceLocation().getAuthority(); + //Top label + String topLabelText = ""; + switch (type) { + case READ_FILE: + if (extras != null && extras.length > 0 && extras[0] instanceof String) { + topLabelText = R("SFileReadAccess", FileUtils.displayablePath((String) extras[0])); + } else { + topLabelText = R("SFileReadAccess", R("AFileOnTheMachine")); } - - //Top label - String topLabelText = ""; - switch (type) { - case READ_FILE: - if (extras != null && extras.length > 0 && extras[0] instanceof String) { - topLabelText = R("SFileReadAccess", FileUtils.displayablePath((String)extras[0])); - } else { - topLabelText = R("SFileReadAccess", R("AFileOnTheMachine")); - } - break; - case WRITE_FILE: - if (extras != null && extras.length > 0 && extras[0] instanceof String) { - topLabelText = R("SFileWriteAccess", FileUtils.displayablePath((String)extras[0])); - } else { - topLabelText = R("SFileWriteAccess", R("AFileOnTheMachine")); - } - break; - case CREATE_DESTKOP_SHORTCUT: - topLabelText = R("SDesktopShortcut"); - break; - case CLIPBOARD_READ: - topLabelText = R("SClipboardReadAccess"); - break; - case CLIPBOARD_WRITE: - topLabelText = R("SClipboardWriteAccess"); - break; - case PRINTER: - topLabelText = R("SPrinterAccess"); - break; - case NETWORK: - if (extras != null && extras.length >= 0) - topLabelText = R("SNetworkAccess", extras[0]); - else - topLabelText = R("SNetworkAccess", "(address here)"); + break; + case WRITE_FILE: + if (extras != null && extras.length > 0 && extras[0] instanceof String) { + topLabelText = R("SFileWriteAccess", FileUtils.displayablePath((String) extras[0])); + } else { + topLabelText = R("SFileWriteAccess", R("AFileOnTheMachine")); } - - ImageIcon icon = new ImageIcon((new sun.misc.Launcher()).getClassLoader().getResource("net/sourceforge/jnlp/resources/warning.png")); - JLabel topLabel = new JLabel(htmlWrap(topLabelText), icon, SwingConstants.LEFT); - topLabel.setFont(new Font(topLabel.getFont().toString(), - Font.BOLD, 12)); - JPanel topPanel = new JPanel(new BorderLayout()); - topPanel.setBackground(Color.WHITE); - topPanel.add(topLabel, BorderLayout.CENTER); - topPanel.setPreferredSize(new Dimension(450,100)); - topPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); - - //application info - JLabel nameLabel = new JLabel(R("Name") + ": " + name); - nameLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); - JLabel publisherLabel = new JLabel(R("Publisher") + ": " + publisher); - publisherLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); - JLabel fromLabel = new JLabel(R("From") + ": " + from); - fromLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); - - alwaysAllow = new JCheckBox(R("AlwaysAllowAction")); - alwaysAllow.setEnabled(false); - - JPanel infoPanel = new JPanel(new GridLayout(4,1)); - infoPanel.add(nameLabel); - infoPanel.add(publisherLabel); - infoPanel.add(fromLabel); - infoPanel.add(alwaysAllow); - infoPanel.setBorder(BorderFactory.createEmptyBorder(25,25,25,25)); - - //run and cancel buttons - JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); - - JButton run = new JButton(R("ButAllow")); - JButton cancel = new JButton(R("ButCancel")); - run.addActionListener(createSetValueListener(parent,0)); - run.addActionListener(new CheckBoxListener()); - cancel.addActionListener(createSetValueListener(parent, 1)); - initialFocusComponent = cancel; - buttonPanel.add(run); - buttonPanel.add(cancel); - buttonPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); - - //all of the above - setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); - add(topPanel); - add(infoPanel); - add(buttonPanel); - + break; + case CREATE_DESTKOP_SHORTCUT: + topLabelText = R("SDesktopShortcut"); + break; + case CLIPBOARD_READ: + topLabelText = R("SClipboardReadAccess"); + break; + case CLIPBOARD_WRITE: + topLabelText = R("SClipboardWriteAccess"); + break; + case PRINTER: + topLabelText = R("SPrinterAccess"); + break; + case NETWORK: + if (extras != null && extras.length >= 0) + topLabelText = R("SNetworkAccess", extras[0]); + else + topLabelText = R("SNetworkAccess", "(address here)"); } - - private class CheckBoxListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - if (alwaysAllow != null && alwaysAllow.isSelected()) { - // TODO: somehow tell the ApplicationInstance - // to stop asking for permission - } - } + ImageIcon icon = new ImageIcon((new sun.misc.Launcher()).getClassLoader().getResource("net/sourceforge/jnlp/resources/warning.png")); + JLabel topLabel = new JLabel(htmlWrap(topLabelText), icon, SwingConstants.LEFT); + topLabel.setFont(new Font(topLabel.getFont().toString(), + Font.BOLD, 12)); + JPanel topPanel = new JPanel(new BorderLayout()); + topPanel.setBackground(Color.WHITE); + topPanel.add(topLabel, BorderLayout.CENTER); + topPanel.setPreferredSize(new Dimension(450, 100)); + topPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + //application info + JLabel nameLabel = new JLabel(R("Name") + ": " + name); + nameLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); + JLabel publisherLabel = new JLabel(R("Publisher") + ": " + publisher); + publisherLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); + JLabel fromLabel = new JLabel(R("From") + ": " + from); + fromLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); + + alwaysAllow = new JCheckBox(R("AlwaysAllowAction")); + alwaysAllow.setEnabled(false); + + JPanel infoPanel = new JPanel(new GridLayout(4, 1)); + infoPanel.add(nameLabel); + infoPanel.add(publisherLabel); + infoPanel.add(fromLabel); + infoPanel.add(alwaysAllow); + infoPanel.setBorder(BorderFactory.createEmptyBorder(25, 25, 25, 25)); + + //run and cancel buttons + JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); + + JButton run = new JButton(R("ButAllow")); + JButton cancel = new JButton(R("ButCancel")); + run.addActionListener(createSetValueListener(parent, 0)); + run.addActionListener(new CheckBoxListener()); + cancel.addActionListener(createSetValueListener(parent, 1)); + initialFocusComponent = cancel; + buttonPanel.add(run); + buttonPanel.add(cancel); + buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + //all of the above + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + add(topPanel); + add(infoPanel); + add(buttonPanel); + + } + + private class CheckBoxListener implements ActionListener { + public void actionPerformed(ActionEvent e) { + if (alwaysAllow != null && alwaysAllow.isSelected()) { + // TODO: somehow tell the ApplicationInstance + // to stop asking for permission + } } + } } diff --git a/netx/net/sourceforge/jnlp/security/AppletWarningPane.java b/netx/net/sourceforge/jnlp/security/AppletWarningPane.java index 8bd14ef..5a959bc 100644 --- a/netx/net/sourceforge/jnlp/security/AppletWarningPane.java +++ b/netx/net/sourceforge/jnlp/security/AppletWarningPane.java @@ -49,67 +49,66 @@ import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; - public class AppletWarningPane extends SecurityDialogPanel { - public AppletWarningPane(SecurityWarningDialog x, CertVerifier certVerifier) { - super(x, certVerifier); - addComponents(); - } + public AppletWarningPane(SecurityWarningDialog x, CertVerifier certVerifier) { + super(x, certVerifier); + addComponents(); + } - protected void addComponents() { + protected void addComponents() { - //Top label - String topLabelText = "While support for verifying signed code" + + //Top label + String topLabelText = "While support for verifying signed code" + " has not been implemented yet, some applets will not run " + "properly under the default restricted security level."; - String bottomLabelText = "Do you want to run this applet under the " + + String bottomLabelText = "Do you want to run this applet under the " + "restricted security level? (clicking No will run this applet " + "without any security checking, and should only be done if you " + "trust the applet!)"; - JLabel topLabel = new JLabel(htmlWrap(topLabelText)); - topLabel.setFont(new Font(topLabel.getFont().toString(), + JLabel topLabel = new JLabel(htmlWrap(topLabelText)); + topLabel.setFont(new Font(topLabel.getFont().toString(), Font.BOLD, 12)); - JPanel topPanel = new JPanel(new BorderLayout()); - topPanel.setBackground(Color.WHITE); - topPanel.add(topLabel, BorderLayout.CENTER); - topPanel.setPreferredSize(new Dimension(400,80)); - topPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); - - JLabel bottomLabel = new JLabel(htmlWrap(bottomLabelText)); - JPanel infoPanel = new JPanel(new BorderLayout()); - infoPanel.add(bottomLabel, BorderLayout.CENTER); - infoPanel.setPreferredSize(new Dimension(400,80)); - infoPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); - - //run and cancel buttons - JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); - - JButton yes = new JButton("Yes"); - JButton no = new JButton("No"); - JButton cancel = new JButton("Cancel"); - int buttonWidth = cancel.getMinimumSize().width; - int buttonHeight = cancel.getMinimumSize().height; - Dimension d = new Dimension(buttonWidth, buttonHeight); - yes.setPreferredSize(d); - no.setPreferredSize(d); - cancel.setPreferredSize(d); - yes.addActionListener(createSetValueListener(parent, 0)); - no.addActionListener(createSetValueListener(parent, 1)); - cancel.addActionListener(createSetValueListener(parent, 2)); - initialFocusComponent = cancel; - buttonPanel.add(yes); - buttonPanel.add(no); - buttonPanel.add(cancel); - buttonPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); - - //all of the above - setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); - add(topPanel); - add(infoPanel); - add(buttonPanel); - - } + JPanel topPanel = new JPanel(new BorderLayout()); + topPanel.setBackground(Color.WHITE); + topPanel.add(topLabel, BorderLayout.CENTER); + topPanel.setPreferredSize(new Dimension(400, 80)); + topPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + JLabel bottomLabel = new JLabel(htmlWrap(bottomLabelText)); + JPanel infoPanel = new JPanel(new BorderLayout()); + infoPanel.add(bottomLabel, BorderLayout.CENTER); + infoPanel.setPreferredSize(new Dimension(400, 80)); + infoPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + //run and cancel buttons + JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); + + JButton yes = new JButton("Yes"); + JButton no = new JButton("No"); + JButton cancel = new JButton("Cancel"); + int buttonWidth = cancel.getMinimumSize().width; + int buttonHeight = cancel.getMinimumSize().height; + Dimension d = new Dimension(buttonWidth, buttonHeight); + yes.setPreferredSize(d); + no.setPreferredSize(d); + cancel.setPreferredSize(d); + yes.addActionListener(createSetValueListener(parent, 0)); + no.addActionListener(createSetValueListener(parent, 1)); + cancel.addActionListener(createSetValueListener(parent, 2)); + initialFocusComponent = cancel; + buttonPanel.add(yes); + buttonPanel.add(no); + buttonPanel.add(cancel); + buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + //all of the above + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + add(topPanel); + add(infoPanel); + add(buttonPanel); + + } } diff --git a/netx/net/sourceforge/jnlp/security/CertWarningPane.java b/netx/net/sourceforge/jnlp/security/CertWarningPane.java index 56105e9..215b365 100644 --- a/netx/net/sourceforge/jnlp/security/CertWarningPane.java +++ b/netx/net/sourceforge/jnlp/security/CertWarningPane.java @@ -81,162 +81,160 @@ import net.sourceforge.jnlp.util.FileUtils; */ public class CertWarningPane extends SecurityDialogPanel { - JCheckBox alwaysTrust; - CertVerifier certVerifier; + JCheckBox alwaysTrust; + CertVerifier certVerifier; - public CertWarningPane(SecurityWarningDialog x, CertVerifier certVerifier) { - super(x, certVerifier); - this.certVerifier = certVerifier; - addComponents(); - } - - /** - * Creates the actual GUI components, and adds it to this panel - */ - private void addComponents() { - AccessType type = parent.getAccessType(); - JNLPFile file = parent.getFile(); - Certificate c = parent.getJarSigner().getPublisher(); - - String name = ""; - String publisher = ""; - String from = ""; + public CertWarningPane(SecurityWarningDialog x, CertVerifier certVerifier) { + super(x, certVerifier); + this.certVerifier = certVerifier; + addComponents(); + } - //We don't worry about exceptions when trying to fill in - //these strings -- we just want to fill in as many as possible. - try { - if ((certVerifier instanceof HttpsCertVerifier) && + /** + * Creates the actual GUI components, and adds it to this panel + */ + private void addComponents() { + AccessType type = parent.getAccessType(); + JNLPFile file = parent.getFile(); + Certificate c = parent.getJarSigner().getPublisher(); + + String name = ""; + String publisher = ""; + String from = ""; + + //We don't worry about exceptions when trying to fill in + //these strings -- we just want to fill in as many as possible. + try { + if ((certVerifier instanceof HttpsCertVerifier) && (c instanceof X509Certificate)) - name = SecurityUtil.getCN(((X509Certificate)c) + name = SecurityUtil.getCN(((X509Certificate) c) .getSubjectX500Principal().getName()); - else if (file instanceof PluginBridge) - name = file.getTitle(); - else - name = file.getInformation().getTitle(); - } catch (Exception e) { - } + else if (file instanceof PluginBridge) + name = file.getTitle(); + else + name = file.getInformation().getTitle(); + } catch (Exception e) { + } - try { - if (c instanceof X509Certificate) { - publisher = SecurityUtil.getCN(((X509Certificate)c) + try { + if (c instanceof X509Certificate) { + publisher = SecurityUtil.getCN(((X509Certificate) c) .getSubjectX500Principal().getName()); - } - } catch (Exception e) { - } + } + } catch (Exception e) { + } - try { - if (file instanceof PluginBridge) - from = file.getCodeBase().getHost(); - else - from = file.getInformation().getHomepage().toString(); - } catch (Exception e) { - } + try { + if (file instanceof PluginBridge) + from = file.getCodeBase().getHost(); + else + from = file.getInformation().getHomepage().toString(); + } catch (Exception e) { + } - //Top label - String topLabelText = ""; - String propertyName = ""; - if (certVerifier instanceof HttpsCertVerifier) - { - topLabelText = R("SHttpsUnverified") + " " + + //Top label + String topLabelText = ""; + String propertyName = ""; + if (certVerifier instanceof HttpsCertVerifier) { + topLabelText = R("SHttpsUnverified") + " " + R("Continue"); - propertyName = "OptionPane.warningIcon"; - } - else - switch (type) { - case VERIFIED: - topLabelText = R("SSigVerified"); - propertyName = "OptionPane.informationIcon"; - break; - case UNVERIFIED: - topLabelText = R("SSigUnverified"); - propertyName = "OptionPane.warningIcon"; - break; - case SIGNING_ERROR: - topLabelText = R("SSignatureError"); - propertyName = "OptionPane.warningIcon"; - break; - } - ImageIcon icon = new ImageIcon((new sun.misc.Launcher()) + propertyName = "OptionPane.warningIcon"; + } else + switch (type) { + case VERIFIED: + topLabelText = R("SSigVerified"); + propertyName = "OptionPane.informationIcon"; + break; + case UNVERIFIED: + topLabelText = R("SSigUnverified"); + propertyName = "OptionPane.warningIcon"; + break; + case SIGNING_ERROR: + topLabelText = R("SSignatureError"); + propertyName = "OptionPane.warningIcon"; + break; + } + ImageIcon icon = new ImageIcon((new sun.misc.Launcher()) .getClassLoader().getResource("net/sourceforge/jnlp/resources/warning.png")); - JLabel topLabel = new JLabel(htmlWrap(topLabelText), icon, SwingConstants.LEFT); - topLabel.setFont(new Font(topLabel.getFont().toString(), + JLabel topLabel = new JLabel(htmlWrap(topLabelText), icon, SwingConstants.LEFT); + topLabel.setFont(new Font(topLabel.getFont().toString(), Font.BOLD, 12)); - JPanel topPanel = new JPanel(new BorderLayout()); - topPanel.setBackground(Color.WHITE); - topPanel.add(topLabel, BorderLayout.CENTER); - topPanel.setPreferredSize(new Dimension(400,60)); - topPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); - - //application info - JLabel nameLabel = new JLabel(R("Name") + ": " + name); - nameLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); - JLabel publisherLabel = new JLabel(R("Publisher") + ": " + publisher); - publisherLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); - JLabel fromLabel = new JLabel(R("From") + ": " + from); - fromLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); - - alwaysTrust = new JCheckBox(R("SAlwaysTrustPublisher")); - alwaysTrust.setEnabled(true); - - JPanel infoPanel = new JPanel(new GridLayout(4,1)); - infoPanel.add(nameLabel); - infoPanel.add(publisherLabel); - - if (!(certVerifier instanceof HttpsCertVerifier)) - infoPanel.add(fromLabel); - - infoPanel.add(alwaysTrust); - infoPanel.setBorder(BorderFactory.createEmptyBorder(25,25,25,25)); - - //run and cancel buttons - JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); - JButton run = new JButton(R("ButRun")); - JButton cancel = new JButton(R("ButCancel")); - int buttonWidth = Math.max(run.getMinimumSize().width, + JPanel topPanel = new JPanel(new BorderLayout()); + topPanel.setBackground(Color.WHITE); + topPanel.add(topLabel, BorderLayout.CENTER); + topPanel.setPreferredSize(new Dimension(400, 60)); + topPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + //application info + JLabel nameLabel = new JLabel(R("Name") + ": " + name); + nameLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); + JLabel publisherLabel = new JLabel(R("Publisher") + ": " + publisher); + publisherLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); + JLabel fromLabel = new JLabel(R("From") + ": " + from); + fromLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); + + alwaysTrust = new JCheckBox(R("SAlwaysTrustPublisher")); + alwaysTrust.setEnabled(true); + + JPanel infoPanel = new JPanel(new GridLayout(4, 1)); + infoPanel.add(nameLabel); + infoPanel.add(publisherLabel); + + if (!(certVerifier instanceof HttpsCertVerifier)) + infoPanel.add(fromLabel); + + infoPanel.add(alwaysTrust); + infoPanel.setBorder(BorderFactory.createEmptyBorder(25, 25, 25, 25)); + + //run and cancel buttons + JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); + JButton run = new JButton(R("ButRun")); + JButton cancel = new JButton(R("ButCancel")); + int buttonWidth = Math.max(run.getMinimumSize().width, cancel.getMinimumSize().width); - int buttonHeight = run.getMinimumSize().height; - Dimension d = new Dimension(buttonWidth, buttonHeight); - run.setPreferredSize(d); - cancel.setPreferredSize(d); - run.addActionListener(createSetValueListener(parent, 0)); - run.addActionListener(new CheckBoxListener()); - cancel.addActionListener(createSetValueListener(parent, 1)); - initialFocusComponent = cancel; - buttonPanel.add(run); - buttonPanel.add(cancel); - buttonPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); - - //all of the above - setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); - add(topPanel); - add(infoPanel); - add(buttonPanel); - - JLabel bottomLabel; - JButton moreInfo = new JButton(R("ButMoreInformation")); - moreInfo.addActionListener(new MoreInfoButtonListener()); - - if (parent.getJarSigner().getRootInCacerts()) - bottomLabel = new JLabel(htmlWrap(R("STrustedSource"))); - else - bottomLabel = new JLabel(htmlWrap(R("SUntrustedSource"))); - - JPanel bottomPanel = new JPanel(); - bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS)); - bottomPanel.add(bottomLabel); - bottomPanel.add(moreInfo); - bottomPanel.setPreferredSize(new Dimension(500,100)); - bottomPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); - add(bottomPanel); + int buttonHeight = run.getMinimumSize().height; + Dimension d = new Dimension(buttonWidth, buttonHeight); + run.setPreferredSize(d); + cancel.setPreferredSize(d); + run.addActionListener(createSetValueListener(parent, 0)); + run.addActionListener(new CheckBoxListener()); + cancel.addActionListener(createSetValueListener(parent, 1)); + initialFocusComponent = cancel; + buttonPanel.add(run); + buttonPanel.add(cancel); + buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + //all of the above + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + add(topPanel); + add(infoPanel); + add(buttonPanel); + + JLabel bottomLabel; + JButton moreInfo = new JButton(R("ButMoreInformation")); + moreInfo.addActionListener(new MoreInfoButtonListener()); + + if (parent.getJarSigner().getRootInCacerts()) + bottomLabel = new JLabel(htmlWrap(R("STrustedSource"))); + else + bottomLabel = new JLabel(htmlWrap(R("SUntrustedSource"))); + + JPanel bottomPanel = new JPanel(); + bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS)); + bottomPanel.add(bottomLabel); + bottomPanel.add(moreInfo); + bottomPanel.setPreferredSize(new Dimension(500, 100)); + bottomPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + add(bottomPanel); - } + } - private class MoreInfoButtonListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - SecurityWarningDialog.showMoreInfoDialog(parent.getJarSigner(), + private class MoreInfoButtonListener implements ActionListener { + public void actionPerformed(ActionEvent e) { + SecurityWarningDialog.showMoreInfoDialog(parent.getJarSigner(), parent); - } } + } /** * Updates the user's KeyStore of trusted Certificates. diff --git a/netx/net/sourceforge/jnlp/security/CertsInfoPane.java b/netx/net/sourceforge/jnlp/security/CertsInfoPane.java index 616dbfe..2c9a826 100644 --- a/netx/net/sourceforge/jnlp/security/CertsInfoPane.java +++ b/netx/net/sourceforge/jnlp/security/CertsInfoPane.java @@ -67,66 +67,66 @@ import net.sourceforge.jnlp.tools.*; */ public class CertsInfoPane extends SecurityDialogPanel { - private ArrayList<CertPath> certs; + private ArrayList<CertPath> certs; private JList list; - protected JTree tree; + protected JTree tree; private JTable table; private JTextArea output; private ListSelectionModel listSelectionModel; private ListSelectionModel tableSelectionModel; protected String[] certNames; private String[] columnNames = { R("Field"), R("Value") }; - protected ArrayList<String[][]> certsData; + protected ArrayList<String[][]> certsData; - public CertsInfoPane(SecurityWarningDialog x, CertVerifier certVerifier) { - super(x, certVerifier); - addComponents(); - } + public CertsInfoPane(SecurityWarningDialog x, CertVerifier certVerifier) { + super(x, certVerifier); + addComponents(); + } - /** - * Builds the JTree out of CertPaths. - */ - void buildTree() { - certs = parent.getJarSigner().getCerts(); - //for now, we're only going to display the first signer, even though - //jars can be signed by multiple people. - CertPath firstPath = certs.get(0); - X509Certificate firstCert = - ((X509Certificate)firstPath.getCertificates().get(0)); - String subjectString = + /** + * Builds the JTree out of CertPaths. + */ + void buildTree() { + certs = parent.getJarSigner().getCerts(); + //for now, we're only going to display the first signer, even though + //jars can be signed by multiple people. + CertPath firstPath = certs.get(0); + X509Certificate firstCert = + ((X509Certificate) firstPath.getCertificates().get(0)); + String subjectString = SecurityUtil.getCN(firstCert.getSubjectX500Principal().getName()); - String issuerString = + String issuerString = SecurityUtil.getCN(firstCert.getIssuerX500Principal().getName()); - DefaultMutableTreeNode top = + DefaultMutableTreeNode top = new DefaultMutableTreeNode(subjectString + " (" + issuerString + ")"); - //not self signed - if (!firstCert.getSubjectDN().equals(firstCert.getIssuerDN()) + //not self signed + if (!firstCert.getSubjectDN().equals(firstCert.getIssuerDN()) && (firstPath.getCertificates().size() > 1)) { - X509Certificate secondCert = - ((X509Certificate)firstPath.getCertificates().get(1)); - subjectString = + X509Certificate secondCert = + ((X509Certificate) firstPath.getCertificates().get(1)); + subjectString = SecurityUtil.getCN(secondCert.getSubjectX500Principal().getName()); - issuerString = + issuerString = SecurityUtil.getCN(secondCert.getIssuerX500Principal().getName()); - top.add(new DefaultMutableTreeNode(subjectString + top.add(new DefaultMutableTreeNode(subjectString + " (" + issuerString + ")")); - } + } - tree = new JTree(top); - tree.getSelectionModel().setSelectionMode + tree = new JTree(top); + tree.getSelectionModel().setSelectionMode (TreeSelectionModel.SINGLE_TREE_SELECTION); - tree.addTreeSelectionListener(new TreeSelectionHandler()); - } + tree.addTreeSelectionListener(new TreeSelectionHandler()); + } - /** - * Fills in certsNames, certsData with data from the certificates. - */ - protected void populateTable() { - certNames = new String[certs.get(0).getCertificates().size()]; - certsData = new ArrayList<String[][]>(); + /** + * Fills in certsNames, certsData with data from the certificates. + */ + protected void populateTable() { + certNames = new String[certs.get(0).getCertificates().size()]; + certsData = new ArrayList<String[][]>(); for (int i = 0; i < certs.get(0).getCertificates().size(); i++) { @@ -135,11 +135,11 @@ public class CertsInfoPane extends SecurityDialogPanel { certNames[i] = SecurityUtil.getCN(c.getSubjectX500Principal().getName()) + " (" + SecurityUtil.getCN(c.getIssuerX500Principal().getName()) + ")"; } - } + } - protected String[][] parseCert(X509Certificate c) { + protected String[][] parseCert(X509Certificate c) { - String version = ""+c.getVersion(); + String version = "" + c.getVersion(); String serialNumber = c.getSerialNumber().toString(); String signatureAlg = c.getSigAlgName(); String issuer = c.getIssuerX500Principal().toString(); @@ -151,146 +151,148 @@ public class CertsInfoPane extends SecurityDialogPanel { HexDumpEncoder encoder = new HexDumpEncoder(); String signature = encoder.encodeBuffer(c.getSignature()); - String md5Hash = ""; - String sha1Hash = ""; - try { - MessageDigest digest = MessageDigest.getInstance("MD5"); - digest.update(c.getEncoded()); - md5Hash = makeFingerprint(digest.digest()); - - digest = MessageDigest.getInstance("SHA-1"); - digest.update(c.getEncoded()); - sha1Hash = makeFingerprint(digest.digest()); - } catch (Exception e) { - //fail quietly - } + String md5Hash = ""; + String sha1Hash = ""; + try { + MessageDigest digest = MessageDigest.getInstance("MD5"); + digest.update(c.getEncoded()); + md5Hash = makeFingerprint(digest.digest()); + + digest = MessageDigest.getInstance("SHA-1"); + digest.update(c.getEncoded()); + sha1Hash = makeFingerprint(digest.digest()); + } catch (Exception e) { + //fail quietly + } - String[][] cert = { {R("Version"), version}, - {R("SSerial"), serialNumber}, - {R("SSignatureAlgorithm"), signatureAlg}, - {R("SIssuer"), issuer}, - {R("SValidity"), validity}, - {R("SSubject"), subject}, - {R("SSignature"), signature}, - {R("SMD5Fingerprint"), md5Hash}, - {R("SSHA1Fingerprint"), sha1Hash} + String[][] cert = { { R("Version"), version }, + { R("SSerial"), serialNumber }, + { R("SSignatureAlgorithm"), signatureAlg }, + { R("SIssuer"), issuer }, + { R("SValidity"), validity }, + { R("SSubject"), subject }, + { R("SSignature"), signature }, + { R("SMD5Fingerprint"), md5Hash }, + { R("SSHA1Fingerprint"), sha1Hash } }; return cert; - } + } + /** + * Constructs the GUI components of this panel + */ + protected void addComponents() { + buildTree(); + populateTable(); /** - * Constructs the GUI components of this panel - */ - protected void addComponents() { - buildTree(); - populateTable(); - /** - //List of Certs + //List of Certs list = new JList(certNames); - list.setSelectedIndex(0); //assuming there's at least 1 cert + list.setSelectedIndex(0); //assuming there's at least 1 cert listSelectionModel = list.getSelectionModel(); listSelectionModel.addListSelectionListener(new ListSelectionHandler()); JScrollPane listPane = new JScrollPane(list); - */ - JScrollPane listPane = new JScrollPane(tree); + */ + JScrollPane listPane = new JScrollPane(tree); //Table of field-value pairs DefaultTableModel tableModel = new DefaultTableModel(certsData.get(0), columnNames); table = new JTable(tableModel); - table.getTableHeader().setReorderingAllowed(false); + table.getTableHeader().setReorderingAllowed(false); tableSelectionModel = table.getSelectionModel(); tableSelectionModel.addListSelectionListener(new TableSelectionHandler()); table.setFillsViewportHeight(true); JScrollPane tablePane = new JScrollPane(table); - tablePane.setPreferredSize(new Dimension(500,200)); + tablePane.setPreferredSize(new Dimension(500, 200)); //Text area to display the larger values output = new JTextArea(); output.setEditable(false); JScrollPane outputPane = new JScrollPane(output, - ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, - ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); - outputPane.setPreferredSize(new Dimension(500,200)); + ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, + ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); + outputPane.setPreferredSize(new Dimension(500, 200)); - //split pane of the field-value pairs and textbox - JSplitPane rightSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, + //split pane of the field-value pairs and textbox + JSplitPane rightSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, tablePane, outputPane); - rightSplitPane.setDividerLocation(0.50); - rightSplitPane.setResizeWeight(0.50); + rightSplitPane.setDividerLocation(0.50); + rightSplitPane.setResizeWeight(0.50); - JSplitPane mainPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, + JSplitPane mainPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, listPane, rightSplitPane); - mainPane.setDividerLocation(0.30); - mainPane.setResizeWeight(0.30); - - JPanel buttonPane = new JPanel(new BorderLayout()); - JButton close = new JButton(R("ButClose")); - JButton copyToClipboard = new JButton(R("ButCopy")); - close.addActionListener(createSetValueListener(parent, 0)); - copyToClipboard.addActionListener(new CopyToClipboardHandler()); - buttonPane.add(close, BorderLayout.EAST); - buttonPane.add(copyToClipboard, BorderLayout.WEST); - buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); - - add(mainPane, BorderLayout.CENTER); - add(buttonPane, BorderLayout.SOUTH); - } + mainPane.setDividerLocation(0.30); + mainPane.setResizeWeight(0.30); + + JPanel buttonPane = new JPanel(new BorderLayout()); + JButton close = new JButton(R("ButClose")); + JButton copyToClipboard = new JButton(R("ButCopy")); + close.addActionListener(createSetValueListener(parent, 0)); + copyToClipboard.addActionListener(new CopyToClipboardHandler()); + buttonPane.add(close, BorderLayout.EAST); + buttonPane.add(copyToClipboard, BorderLayout.WEST); + buttonPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); + + add(mainPane, BorderLayout.CENTER); + add(buttonPane, BorderLayout.SOUTH); + } - /** - * Copies the currently selected certificate to the system Clipboard. - */ - private class CopyToClipboardHandler implements ActionListener { - public void actionPerformed(ActionEvent e) { - Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); - int certIndex = 0; - DefaultMutableTreeNode node = (DefaultMutableTreeNode) - tree.getLastSelectedPathComponent(); - if (node == null) return; + /** + * Copies the currently selected certificate to the system Clipboard. + */ + private class CopyToClipboardHandler implements ActionListener { + public void actionPerformed(ActionEvent e) { + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + int certIndex = 0; + DefaultMutableTreeNode node = (DefaultMutableTreeNode) + tree.getLastSelectedPathComponent(); + if (node == null) + return; if (node.isRoot()) - certIndex = 0; + certIndex = 0; else if (node.isLeaf()) - certIndex = 1; - - String[][] cert = certsData.get(certIndex); - int rows = cert.length; - int cols = cert[0].length; - - String certString = ""; - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { - certString += cert[i][j]; - certString += " "; - } - certString += "\n"; - } - - clipboard.setContents(new StringSelection(certString), null); + certIndex = 1; + + String[][] cert = certsData.get(certIndex); + int rows = cert.length; + int cols = cert[0].length; + + String certString = ""; + for (int i = 0; i < rows; i++) { + for (int j = 0; j < cols; j++) { + certString += cert[i][j]; + certString += " "; } + certString += "\n"; + } + + clipboard.setContents(new StringSelection(certString), null); } + } - /** - * Updates the JTable when the JTree selection has changed. - */ - protected class TreeSelectionHandler implements TreeSelectionListener { - public void valueChanged(TreeSelectionEvent e) { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) + /** + * Updates the JTable when the JTree selection has changed. + */ + protected class TreeSelectionHandler implements TreeSelectionListener { + public void valueChanged(TreeSelectionEvent e) { + DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); - if (node == null) return; - if (node.isRoot()) { - table.setModel(new DefaultTableModel(certsData.get(0), + if (node == null) + return; + if (node.isRoot()) { + table.setModel(new DefaultTableModel(certsData.get(0), columnNames)); - } else if (node.isLeaf()) { - table.setModel(new DefaultTableModel(certsData.get(1), + } else if (node.isLeaf()) { + table.setModel(new DefaultTableModel(certsData.get(1), columnNames)); - } - } + } } + } - /** - * Updates the JTable when the selection on the list has changed. - */ + /** + * Updates the JTable when the selection on the list has changed. + */ private class ListSelectionHandler implements ListSelectionListener { public void valueChanged(ListSelectionEvent e) { ListSelectionModel lsm = (ListSelectionModel) e.getSource(); @@ -320,24 +322,24 @@ public class CertsInfoPane extends SecurityDialogPanel { for (int i = minIndex; i <= maxIndex; i++) { if (lsm.isSelectedIndex(i)) { - output.setText((String) table.getValueAt(i,1)); + output.setText((String) table.getValueAt(i, 1)); } } } } - /** - * Makes a human readable hash fingerprint. - * For example: 11:22:33:44:AA:BB:CC:DD:EE:FF. - */ - private String makeFingerprint(byte[] hash) { - String fingerprint = ""; - for (int i = 0; i < hash.length; i++) { - if (!fingerprint.equals("")) - fingerprint += ":"; - fingerprint += Integer.toHexString( - ((hash[i] & 0xFF)|0x100)).substring(1,3); - } - return fingerprint.toUpperCase(); + /** + * Makes a human readable hash fingerprint. + * For example: 11:22:33:44:AA:BB:CC:DD:EE:FF. + */ + private String makeFingerprint(byte[] hash) { + String fingerprint = ""; + for (int i = 0; i < hash.length; i++) { + if (!fingerprint.equals("")) + fingerprint += ":"; + fingerprint += Integer.toHexString( + ((hash[i] & 0xFF) | 0x100)).substring(1, 3); } + return fingerprint.toUpperCase(); + } } diff --git a/netx/net/sourceforge/jnlp/security/HttpsCertVerifier.java b/netx/net/sourceforge/jnlp/security/HttpsCertVerifier.java index 966023b..3593291 100644 --- a/netx/net/sourceforge/jnlp/security/HttpsCertVerifier.java +++ b/netx/net/sourceforge/jnlp/security/HttpsCertVerifier.java @@ -86,7 +86,7 @@ public class HttpsCertVerifier implements CertVerifier { public ArrayList<CertPath> getCerts() { ArrayList<X509Certificate> list = new ArrayList<X509Certificate>(); - for (int i=0; i < chain.length; i++) + for (int i = 0; i < chain.length; i++) list.add(chain[i]); ArrayList<CertPath> certPaths = new ArrayList<CertPath>(); @@ -104,53 +104,51 @@ public class HttpsCertVerifier implements CertVerifier { public ArrayList<String> getDetails() { - boolean hasExpiredCert=false; - boolean hasExpiringCert=false; - boolean notYetValidCert=false; - boolean isUntrusted=false; + boolean hasExpiredCert = false; + boolean hasExpiringCert = false; + boolean notYetValidCert = false; + boolean isUntrusted = false; boolean CNMisMatch = !hostMatched; - if (! getAlreadyTrustPublisher()) - isUntrusted = true; - - for (int i=0; i < chain.length; i++) - { - X509Certificate cert = chain[i]; - - long now = System.currentTimeMillis(); - long SIX_MONTHS = 180*24*60*60*1000L; - long notAfter = cert.getNotAfter().getTime(); - if (notAfter < now) { - hasExpiredCert = true; - } else if (notAfter < now + SIX_MONTHS) { - hasExpiringCert = true; - } - - try { - cert.checkValidity(); - } catch (CertificateNotYetValidException cnyve) { - notYetValidCert = true; - } catch (CertificateExpiredException cee) { - hasExpiredCert = true; - } + if (!getAlreadyTrustPublisher()) + isUntrusted = true; + + for (int i = 0; i < chain.length; i++) { + X509Certificate cert = chain[i]; + + long now = System.currentTimeMillis(); + long SIX_MONTHS = 180 * 24 * 60 * 60 * 1000L; + long notAfter = cert.getNotAfter().getTime(); + if (notAfter < now) { + hasExpiredCert = true; + } else if (notAfter < now + SIX_MONTHS) { + hasExpiringCert = true; + } + + try { + cert.checkValidity(); + } catch (CertificateNotYetValidException cnyve) { + notYetValidCert = true; + } catch (CertificateExpiredException cee) { + hasExpiredCert = true; + } } String altNames = getNamesForCert(chain[0]); if (isUntrusted || hasExpiredCert || hasExpiringCert || notYetValidCert || CNMisMatch) { - if (isUntrusted) + if (isUntrusted) addToDetails(R("SUntrustedCertificate")); - if (hasExpiredCert) + if (hasExpiredCert) addToDetails(R("SHasExpiredCert")); - if (hasExpiringCert) + if (hasExpiringCert) addToDetails(R("SHasExpiringCert")); - if (notYetValidCert) + if (notYetValidCert) addToDetails(R("SNotYetValidCert")); - if (CNMisMatch) - addToDetails(R("SCNMisMatch", altNames, this.hostName)); + if (CNMisMatch) + addToDetails(R("SCNMisMatch", altNames, this.hostName)); } - return details; } @@ -158,7 +156,6 @@ public class HttpsCertVerifier implements CertVerifier { String names = ""; - // We use the specification from // http://java.sun.com/j2se/1.5.0/docs/api/java/security/cert/X509Certificate.html#getSubjectAlternativeNames() // to determine the type of address @@ -174,10 +171,9 @@ public class HttpsCertVerifier implements CertVerifier { if (subjAltNames != null) { for (List<?> next : subjAltNames) { - if ( ((Integer)next.get(0)).intValue() == ALTNAME_IP || - ((Integer)next.get(0)).intValue() == ALTNAME_DNS - ) { - names += ", " + (String)next.get(1); + if (((Integer) next.get(0)).intValue() == ALTNAME_IP || + ((Integer) next.get(0)).intValue() == ALTNAME_DNS) { + names += ", " + (String) next.get(1); } } } @@ -195,26 +191,26 @@ public class HttpsCertVerifier implements CertVerifier { } private void addToDetails(String detail) { - if (!details.contains(detail)) - details.add(detail); + if (!details.contains(detail)) + details.add(detail); } public Certificate getPublisher() { - if (chain.length > 0) - return (Certificate)chain[0]; - return null; + if (chain.length > 0) + return (Certificate) chain[0]; + return null; } public Certificate getRoot() { - if (chain.length > 0) - return (Certificate)chain[chain.length - 1]; - return null; + if (chain.length > 0) + return (Certificate) chain[chain.length - 1]; + return null; } public boolean getRootInCacerts() { try { KeyStore[] caCertsKeyStores = KeyStores.getCAKeyStores(); - return CertificateUtils.inKeyStores((X509Certificate)getRoot(), caCertsKeyStores); + return CertificateUtils.inKeyStores((X509Certificate) getRoot(), caCertsKeyStores); } catch (Exception e) { } return false; diff --git a/netx/net/sourceforge/jnlp/security/KeyStores.java b/netx/net/sourceforge/jnlp/security/KeyStores.java index de4aff3..cfabb20 100644 --- a/netx/net/sourceforge/jnlp/security/KeyStores.java +++ b/netx/net/sourceforge/jnlp/security/KeyStores.java @@ -368,5 +368,4 @@ public final class KeyStores { return ks; } - } diff --git a/netx/net/sourceforge/jnlp/security/MoreInfoPane.java b/netx/net/sourceforge/jnlp/security/MoreInfoPane.java index 28c9f71..c76002b 100644 --- a/netx/net/sourceforge/jnlp/security/MoreInfoPane.java +++ b/netx/net/sourceforge/jnlp/security/MoreInfoPane.java @@ -61,49 +61,49 @@ import javax.swing.SwingConstants; */ public class MoreInfoPane extends SecurityDialogPanel { - public MoreInfoPane(SecurityWarningDialog x, CertVerifier certVerifier) { - super(x, certVerifier); - addComponents(); - } + public MoreInfoPane(SecurityWarningDialog x, CertVerifier certVerifier) { + super(x, certVerifier); + addComponents(); + } - /** - * Constructs the GUI components of this panel - */ - private void addComponents() { - ArrayList<String> details = certVerifier.getDetails(); - - int numLabels = details.size(); - JPanel errorPanel = new JPanel(new GridLayout(numLabels,1)); - errorPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); - errorPanel.setPreferredSize(new Dimension(400, 70*(numLabels))); - - for (int i = 0; i < numLabels; i++) { - ImageIcon icon = null; - if (details.get(i).equals(R("STrustedCertificate"))) - icon = new ImageIcon((new sun.misc.Launcher()) + /** + * Constructs the GUI components of this panel + */ + private void addComponents() { + ArrayList<String> details = certVerifier.getDetails(); + + int numLabels = details.size(); + JPanel errorPanel = new JPanel(new GridLayout(numLabels, 1)); + errorPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + errorPanel.setPreferredSize(new Dimension(400, 70 * (numLabels))); + + for (int i = 0; i < numLabels; i++) { + ImageIcon icon = null; + if (details.get(i).equals(R("STrustedCertificate"))) + icon = new ImageIcon((new sun.misc.Launcher()) .getClassLoader().getResource("net/sourceforge/jnlp/resources/info-small.png")); - else - icon = new ImageIcon((new sun.misc.Launcher()) + else + icon = new ImageIcon((new sun.misc.Launcher()) .getClassLoader().getResource("net/sourceforge/jnlp/resources/warning-small.png")); - errorPanel.add(new JLabel(htmlWrap(details.get(i)), icon, SwingConstants.LEFT)); - } + errorPanel.add(new JLabel(htmlWrap(details.get(i)), icon, SwingConstants.LEFT)); + } - JPanel buttonsPanel = new JPanel(new BorderLayout()); - JButton certDetails = new JButton(R("SCertificateDetails")); - certDetails.addActionListener(new CertInfoButtonListener()); - JButton close = new JButton(R("ButClose")); - close.addActionListener(createSetValueListener(parent, 0)); + JPanel buttonsPanel = new JPanel(new BorderLayout()); + JButton certDetails = new JButton(R("SCertificateDetails")); + certDetails.addActionListener(new CertInfoButtonListener()); + JButton close = new JButton(R("ButClose")); + close.addActionListener(createSetValueListener(parent, 0)); buttonsPanel.add(certDetails, BorderLayout.WEST); buttonsPanel.add(close, BorderLayout.EAST); - buttonsPanel.setBorder(BorderFactory.createEmptyBorder(15,15,15,15)); + buttonsPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15)); add(errorPanel, BorderLayout.NORTH); add(buttonsPanel, BorderLayout.SOUTH); - } + } - private class CertInfoButtonListener implements ActionListener { + private class CertInfoButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { SecurityWarningDialog.showCertInfoDialog(parent.getJarSigner(), parent); diff --git a/netx/net/sourceforge/jnlp/security/NotAllSignedWarningPane.java b/netx/net/sourceforge/jnlp/security/NotAllSignedWarningPane.java index 6e5b56f..8d2919c 100644 --- a/netx/net/sourceforge/jnlp/security/NotAllSignedWarningPane.java +++ b/netx/net/sourceforge/jnlp/security/NotAllSignedWarningPane.java @@ -55,64 +55,63 @@ import javax.swing.SwingConstants; import net.sourceforge.jnlp.JNLPFile; - public class NotAllSignedWarningPane extends SecurityDialogPanel { - public NotAllSignedWarningPane(SecurityWarningDialog x) { - super(x); - addComponents(); - } + public NotAllSignedWarningPane(SecurityWarningDialog x) { + super(x); + addComponents(); + } - /** - * Creates the actual GUI components, and adds it to this panel - */ - private void addComponents() { - JNLPFile file = parent.getFile(); + /** + * Creates the actual GUI components, and adds it to this panel + */ + private void addComponents() { + JNLPFile file = parent.getFile(); - String topLabelText = R("SNotAllSignedSummary"); - String infoLabelText = R("SNotAllSignedDetail"); - String questionLabelText = R("SNotAllSignedQuestion"); + String topLabelText = R("SNotAllSignedSummary"); + String infoLabelText = R("SNotAllSignedDetail"); + String questionLabelText = R("SNotAllSignedQuestion"); - ImageIcon icon = new ImageIcon((new sun.misc.Launcher()).getClassLoader().getResource("net/sourceforge/jnlp/resources/warning.png")); - JLabel topLabel = new JLabel(htmlWrap(topLabelText), icon, SwingConstants.LEFT); - topLabel.setFont(new Font(topLabel.getFont().toString(), + ImageIcon icon = new ImageIcon((new sun.misc.Launcher()).getClassLoader().getResource("net/sourceforge/jnlp/resources/warning.png")); + JLabel topLabel = new JLabel(htmlWrap(topLabelText), icon, SwingConstants.LEFT); + topLabel.setFont(new Font(topLabel.getFont().toString(), Font.BOLD, 12)); - JPanel topPanel = new JPanel(new BorderLayout()); - topPanel.setBackground(Color.WHITE); - topPanel.add(topLabel, BorderLayout.CENTER); - topPanel.setPreferredSize(new Dimension(500,80)); - topPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); - - JLabel infoLabel = new JLabel(htmlWrap(infoLabelText)); - JPanel infoPanel = new JPanel(new BorderLayout()); - infoPanel.add(infoLabel, BorderLayout.CENTER); - infoPanel.setPreferredSize(new Dimension(500,100)); - infoPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); - - JLabel questionLabel = new JLabel(htmlWrap(questionLabelText)); - JPanel questionPanel = new JPanel(new BorderLayout()); - questionPanel.add(questionLabel, BorderLayout.CENTER); - questionPanel.setPreferredSize(new Dimension(500,100)); - questionPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); - - //run and cancel buttons - JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); - - JButton run = new JButton(R("ButProceed")); - JButton cancel = new JButton(R("ButCancel")); - run.addActionListener(createSetValueListener(parent,0)); - cancel.addActionListener(createSetValueListener(parent, 1)); - initialFocusComponent = cancel; - buttonPanel.add(run); - buttonPanel.add(cancel); - buttonPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); - - //all of the above - setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); - add(topPanel); - add(infoPanel); - add(questionPanel); - add(buttonPanel); - - } + JPanel topPanel = new JPanel(new BorderLayout()); + topPanel.setBackground(Color.WHITE); + topPanel.add(topLabel, BorderLayout.CENTER); + topPanel.setPreferredSize(new Dimension(500, 80)); + topPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + JLabel infoLabel = new JLabel(htmlWrap(infoLabelText)); + JPanel infoPanel = new JPanel(new BorderLayout()); + infoPanel.add(infoLabel, BorderLayout.CENTER); + infoPanel.setPreferredSize(new Dimension(500, 100)); + infoPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + JLabel questionLabel = new JLabel(htmlWrap(questionLabelText)); + JPanel questionPanel = new JPanel(new BorderLayout()); + questionPanel.add(questionLabel, BorderLayout.CENTER); + questionPanel.setPreferredSize(new Dimension(500, 100)); + questionPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + //run and cancel buttons + JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); + + JButton run = new JButton(R("ButProceed")); + JButton cancel = new JButton(R("ButCancel")); + run.addActionListener(createSetValueListener(parent, 0)); + cancel.addActionListener(createSetValueListener(parent, 1)); + initialFocusComponent = cancel; + buttonPanel.add(run); + buttonPanel.add(cancel); + buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + + //all of the above + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + add(topPanel); + add(infoPanel); + add(questionPanel); + add(buttonPanel); + + } } diff --git a/netx/net/sourceforge/jnlp/security/PasswordAuthenticationDialog.java b/netx/net/sourceforge/jnlp/security/PasswordAuthenticationDialog.java index 0014f94..b05debe 100644 --- a/netx/net/sourceforge/jnlp/security/PasswordAuthenticationDialog.java +++ b/netx/net/sourceforge/jnlp/security/PasswordAuthenticationDialog.java @@ -111,7 +111,6 @@ public class PasswordAuthenticationDialog extends JDialog { c.weightx = 1.0; add(jtfUserName, c); - c = new GridBagConstraints(); c.gridx = 0; c.gridy = 2; @@ -142,11 +141,11 @@ public class PasswordAuthenticationDialog extends JDialog { c.weightx = 0.0; add(jbOK, c); - setMinimumSize(new Dimension(400,150)); - setMaximumSize(new Dimension(1024,150)); + setMinimumSize(new Dimension(400, 150)); + setMaximumSize(new Dimension(1024, 150)); setAlwaysOnTop(true); - setSize(400,150); + setSize(400, 150); setLocationRelativeTo(null); // OK => read supplied info and pass it on @@ -202,7 +201,7 @@ public class PasswordAuthenticationDialog extends JDialog { " is requesting authentication. It says \"" + prompt + "\"</html>"); try { - SwingUtilities.invokeAndWait( new Runnable() { + SwingUtilities.invokeAndWait(new Runnable() { public void run() { // show dialog to user setVisible(true); diff --git a/netx/net/sourceforge/jnlp/security/SecurityDialogPanel.java b/netx/net/sourceforge/jnlp/security/SecurityDialogPanel.java index ed7921a..23109a8 100644 --- a/netx/net/sourceforge/jnlp/security/SecurityDialogPanel.java +++ b/netx/net/sourceforge/jnlp/security/SecurityDialogPanel.java @@ -1,5 +1,5 @@ - /* SecurityDialogPanel.java - Copyright (C) 2008-2010 Red Hat, Inc. +/* SecurityDialogPanel.java +Copyright (C) 2008-2010 Red Hat, Inc. This file is part of IcedTea. @@ -49,71 +49,71 @@ import javax.swing.JPanel; */ public abstract class SecurityDialogPanel extends JPanel { - protected SecurityWarningDialog parent; - - JComponent initialFocusComponent = null; - - CertVerifier certVerifier = null; - - public SecurityDialogPanel(SecurityWarningDialog dialog, CertVerifier certVerifier){ - this.parent = dialog; - this.certVerifier = certVerifier; - this.setLayout(new BorderLayout()); - } - - public SecurityDialogPanel(SecurityWarningDialog dialog) { - this.parent = dialog; - this.setLayout(new BorderLayout()); - } - - /** - * Needed to get word wrap working in JLabels. - */ - protected String htmlWrap (String s) { - return "<html>"+s+"</html>"; + protected SecurityWarningDialog parent; + + JComponent initialFocusComponent = null; + + CertVerifier certVerifier = null; + + public SecurityDialogPanel(SecurityWarningDialog dialog, CertVerifier certVerifier) { + this.parent = dialog; + this.certVerifier = certVerifier; + this.setLayout(new BorderLayout()); + } + + public SecurityDialogPanel(SecurityWarningDialog dialog) { + this.parent = dialog; + this.setLayout(new BorderLayout()); + } + + /** + * Needed to get word wrap working in JLabels. + */ + protected String htmlWrap(String s) { + return "<html>" + s + "</html>"; + } + + /** + * Create an ActionListener suitable for use with buttons. When this {@link ActionListener} + * is invoked, it will set the value of the {@link SecurityWarningDialog} and then dispossed. + * + * @param buttonIndex the index of the button. By convention 0 = Yes. 1 = No, 2 = Cancel + * @return + */ + protected ActionListener createSetValueListener(SecurityWarningDialog dialog, int buttonIndex) { + return new SetValueHandler(dialog, buttonIndex); + } + + @Override + public void setVisible(boolean aFlag) { + super.setVisible(aFlag); + requestFocusOnDefaultButton(); + } + + public void requestFocusOnDefaultButton() { + if (initialFocusComponent != null) { + initialFocusComponent.requestFocusInWindow(); } + } - /** - * Create an ActionListener suitable for use with buttons. When this {@link ActionListener} - * is invoked, it will set the value of the {@link SecurityWarningDialog} and then dispossed. - * - * @param buttonIndex the index of the button. By convention 0 = Yes. 1 = No, 2 = Cancel - * @return - */ - protected ActionListener createSetValueListener(SecurityWarningDialog dialog, int buttonIndex) { - return new SetValueHandler(dialog, buttonIndex); - } + /** + * Creates a handler that sets a dialog's value and then disposes it when activated + * + */ + private class SetValueHandler implements ActionListener { - @Override - public void setVisible(boolean aFlag) { - super.setVisible(aFlag); - requestFocusOnDefaultButton(); - } + Integer buttonIndex; + SecurityWarningDialog dialog; - public void requestFocusOnDefaultButton() { - if (initialFocusComponent != null) { - initialFocusComponent.requestFocusInWindow(); - } + public SetValueHandler(SecurityWarningDialog dialog, int buttonIndex) { + this.dialog = dialog; + this.buttonIndex = buttonIndex; } - /** - * Creates a handler that sets a dialog's value and then disposes it when activated - * - */ - private class SetValueHandler implements ActionListener { - - Integer buttonIndex; - SecurityWarningDialog dialog; - - public SetValueHandler(SecurityWarningDialog dialog, int buttonIndex) { - this.dialog = dialog; - this.buttonIndex = buttonIndex; - } - @Override public void actionPerformed(ActionEvent e) { dialog.setValue(buttonIndex); dialog.dispose(); } - } + } } diff --git a/netx/net/sourceforge/jnlp/security/SecurityUtil.java b/netx/net/sourceforge/jnlp/security/SecurityUtil.java index ebdab60..feb149d 100644 --- a/netx/net/sourceforge/jnlp/security/SecurityUtil.java +++ b/netx/net/sourceforge/jnlp/security/SecurityUtil.java @@ -48,15 +48,15 @@ import net.sourceforge.jnlp.security.KeyStores.Type; public class SecurityUtil { - private static final char[] password = "changeit".toCharArray(); + private static final char[] password = "changeit".toCharArray(); - public static String getTrustedCertsFilename() throws Exception{ - return KeyStores.getKeyStoreLocation(Level.USER, Type.CERTS); - } + public static String getTrustedCertsFilename() throws Exception { + return KeyStores.getKeyStoreLocation(Level.USER, Type.CERTS); + } - public static char[] getTrustedCertsPassword() { - return password; - } + public static char[] getTrustedCertsPassword() { + return password; + } /** * Extracts the CN field from a Certificate principal string. Or, if it @@ -98,55 +98,55 @@ public class SecurityUtil { for (int i = start + 3; i < principal.length(); i++) { char ch = principal.charAt(i); switch (ch) { - case '"': - if (escaped) { - commonName.append(ch); - escaped = false; - } else { - inQuotes = !inQuotes; - } - break; + case '"': + if (escaped) { + commonName.append(ch); + escaped = false; + } else { + inQuotes = !inQuotes; + } + break; - case '\\': - if (escaped) { - commonName.append(ch); - escaped = false; - } else { - escaped = true; - } - break; - - case ',': - /* fall through */ - case ';': - /* fall through */ - case '+': - if (escaped || inQuotes) { - commonName.append(ch); + case '\\': if (escaped) { + commonName.append(ch); escaped = false; + } else { + escaped = true; } - } else { - return commonName.toString(); - } - break; - - default: - if (escaped && isHexDigit(ch)) { - hexBits = new char[2]; - hexBits[0] = ch; - } else if (hexBits != null) { - if (!isHexDigit(ch)) { - /* error parsing */ - return ""; + break; + + case ',': + /* fall through */ + case ';': + /* fall through */ + case '+': + if (escaped || inQuotes) { + commonName.append(ch); + if (escaped) { + escaped = false; + } + } else { + return commonName.toString(); } - hexBits[1] = ch; - commonName.append((char) Integer.parseInt(new String(hexBits), 16)); - hexBits = null; - } else { - commonName.append(ch); - } - escaped = false; + break; + + default: + if (escaped && isHexDigit(ch)) { + hexBits = new char[2]; + hexBits[0] = ch; + } else if (hexBits != null) { + if (!isHexDigit(ch)) { + /* error parsing */ + return ""; + } + hexBits[1] = ch; + commonName.append((char) Integer.parseInt(new String(hexBits), 16)); + hexBits = null; + } else { + commonName.append(ch); + } + escaped = false; } } @@ -158,68 +158,68 @@ public class SecurityUtil { return ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f')); } - /** - * Checks the user's home directory to see if the trusted.certs file exists. - * If it does not exist, it tries to create an empty keystore. - * @return true if the trusted.certs file exists or a new trusted.certs - * was created successfully, otherwise false. - */ - public static boolean checkTrustedCertsFile() throws Exception { + /** + * Checks the user's home directory to see if the trusted.certs file exists. + * If it does not exist, it tries to create an empty keystore. + * @return true if the trusted.certs file exists or a new trusted.certs + * was created successfully, otherwise false. + */ + public static boolean checkTrustedCertsFile() throws Exception { - File certFile = new File(getTrustedCertsFilename()); + File certFile = new File(getTrustedCertsFilename()); - //file does not exist - if (!certFile.isFile()) { - File dir = certFile.getAbsoluteFile().getParentFile(); - boolean madeDir = false; - if (!dir.isDirectory()) { - madeDir = dir.mkdirs(); - } + //file does not exist + if (!certFile.isFile()) { + File dir = certFile.getAbsoluteFile().getParentFile(); + boolean madeDir = false; + if (!dir.isDirectory()) { + madeDir = dir.mkdirs(); + } - //made directory, or directory exists - if (madeDir || dir.isDirectory()) { - KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(null, password); - FileOutputStream fos = new FileOutputStream(certFile); - ks.store(fos, password); - fos.close(); - return true; - } else { - return false; - } - } else { - return true; - } + //made directory, or directory exists + if (madeDir || dir.isDirectory()) { + KeyStore ks = KeyStore.getInstance("JKS"); + ks.load(null, password); + FileOutputStream fos = new FileOutputStream(certFile); + ks.store(fos, password); + fos.close(); + return true; + } else { + return false; + } + } else { + return true; } + } - /** - * Returns the keystore associated with the user's trusted.certs file, - * or null otherwise. - */ - public static KeyStore getUserKeyStore() throws Exception { - - KeyStore ks = null; - FileInputStream fis = null; - - if (checkTrustedCertsFile()) { - - try { - File file = new File(getTrustedCertsFilename()); - if (file.exists()) { - fis = new FileInputStream(file); - ks = KeyStore.getInstance("JKS"); - ks.load(fis, password); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - if (fis != null) - fis.close(); - } + /** + * Returns the keystore associated with the user's trusted.certs file, + * or null otherwise. + */ + public static KeyStore getUserKeyStore() throws Exception { + + KeyStore ks = null; + FileInputStream fis = null; + + if (checkTrustedCertsFile()) { + + try { + File file = new File(getTrustedCertsFilename()); + if (file.exists()) { + fis = new FileInputStream(file); + ks = KeyStore.getInstance("JKS"); + ks.load(fis, password); } - return ks; + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + if (fis != null) + fis.close(); + } } + return ks; + } /** * Returns the keystore associated with the JDK cacerts file, @@ -227,54 +227,54 @@ public class SecurityUtil { */ public static KeyStore getCacertsKeyStore() throws Exception { - KeyStore caks = null; - FileInputStream fis = null; + KeyStore caks = null; + FileInputStream fis = null; - try { - File file = new File(System.getProperty("java.home") + try { + File file = new File(System.getProperty("java.home") + "/lib/security/cacerts"); - if (file.exists()) { - fis = new FileInputStream(file); - caks = KeyStore.getInstance("JKS"); - caks.load(fis, null); - } - } catch (Exception e) { - caks = null; - } finally { - if (fis != null) - fis.close(); - } + if (file.exists()) { + fis = new FileInputStream(file); + caks = KeyStore.getInstance("JKS"); + caks.load(fis, null); + } + } catch (Exception e) { + caks = null; + } finally { + if (fis != null) + fis.close(); + } - return caks; + return caks; } - /** - * Returns the keystore associated with the system certs file, - * or null otherwise. - */ - public static KeyStore getSystemCertStore() throws Exception { + /** + * Returns the keystore associated with the system certs file, + * or null otherwise. + */ + public static KeyStore getSystemCertStore() throws Exception { - KeyStore caks = null; - FileInputStream fis = null; + KeyStore caks = null; + FileInputStream fis = null; - try { - File file = new File(System.getProperty("javax.net.ssl.trustStore")); - String type = System.getProperty("javax.net.ssl.trustStoreType"); - //String provider = "SUN"; - char[] password = System.getProperty( + try { + File file = new File(System.getProperty("javax.net.ssl.trustStore")); + String type = System.getProperty("javax.net.ssl.trustStoreType"); + //String provider = "SUN"; + char[] password = System.getProperty( "javax.net.ssl.trustStorePassword").toCharArray(); - if (file.exists()) { - fis = new FileInputStream(file); - caks = KeyStore.getInstance(type); - caks.load(fis, password); - } - } catch (Exception e) { - caks = null; - } finally { - if (fis != null) - fis.close(); - } - - return caks; + if (file.exists()) { + fis = new FileInputStream(file); + caks = KeyStore.getInstance(type); + caks.load(fis, password); + } + } catch (Exception e) { + caks = null; + } finally { + if (fis != null) + fis.close(); } + + return caks; + } } diff --git a/netx/net/sourceforge/jnlp/security/SecurityWarning.java b/netx/net/sourceforge/jnlp/security/SecurityWarning.java index c0eda43..863cb2a 100644 --- a/netx/net/sourceforge/jnlp/security/SecurityWarning.java +++ b/netx/net/sourceforge/jnlp/security/SecurityWarning.java @@ -35,7 +35,6 @@ obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ - package net.sourceforge.jnlp.security; import java.awt.Dialog.ModalityType; @@ -97,7 +96,7 @@ public class SecurityWarning { * @return true if permission was granted by the user, false otherwise. */ public static boolean showAccessWarningDialog(AccessType accessType, JNLPFile file) { - return showAccessWarningDialog(accessType, file, null); + return showAccessWarningDialog(accessType, file, null); } /** @@ -111,7 +110,7 @@ public class SecurityWarning { * @return true if permission was granted by the user, false otherwise. */ public static boolean showAccessWarningDialog(final AccessType accessType, - final JNLPFile file, final Object[] extras) { + final JNLPFile file, final Object[] extras) { if (!shouldPromptUser()) { return false; @@ -161,7 +160,7 @@ public class SecurityWarning { if (selectedValue == null) { return false; } else if (selectedValue instanceof Integer) { - if (((Integer)selectedValue).intValue() == 0) { + if (((Integer) selectedValue).intValue() == 0) { return true; } else { return false; @@ -188,7 +187,7 @@ public class SecurityWarning { return false; } - final SecurityDialogMessage message = new SecurityDialogMessage(); + final SecurityDialogMessage message = new SecurityDialogMessage(); message.dialogType = DialogType.CERT_WARNING; message.accessType = accessType; message.file = file; diff --git a/netx/net/sourceforge/jnlp/security/SecurityWarningDialog.java b/netx/net/sourceforge/jnlp/security/SecurityWarningDialog.java index dc17174..60b13f0 100644 --- a/netx/net/sourceforge/jnlp/security/SecurityWarningDialog.java +++ b/netx/net/sourceforge/jnlp/security/SecurityWarningDialog.java @@ -62,175 +62,173 @@ import java.util.List; */ public class SecurityWarningDialog extends JDialog { - /** The type of dialog we want to show */ - private DialogType dialogType; + /** The type of dialog we want to show */ + private DialogType dialogType; - /** The type of access that this dialog is for */ - private AccessType accessType; + /** The type of access that this dialog is for */ + private AccessType accessType; - private SecurityDialogPanel panel; + private SecurityDialogPanel panel; - /** The application file associated with this security warning */ - private JNLPFile file; + /** The application file associated with this security warning */ + private JNLPFile file; - private CertVerifier certVerifier; + private CertVerifier certVerifier; - private X509Certificate cert; + private X509Certificate cert; - /** An optional String array that's only necessary when a dialog - * label requires some parameters (e.g. showing which address an application - * is trying to connect to). - */ - private Object[] extras; + /** An optional String array that's only necessary when a dialog + * label requires some parameters (e.g. showing which address an application + * is trying to connect to). + */ + private Object[] extras; - /** Whether or not this object has been fully initialized */ - private boolean initialized = false; + /** Whether or not this object has been fully initialized */ + private boolean initialized = false; /** * the return value of this dialog. result: 0 = Yes, 1 = No, 2 = Cancel, * null = Window closed. */ - private Object value; + private Object value; - SecurityWarningDialog(DialogType dialogType, AccessType accessType, + SecurityWarningDialog(DialogType dialogType, AccessType accessType, JNLPFile file, CertVerifier jarSigner, X509Certificate cert, Object[] extras) { - super(); - this.dialogType = dialogType; - this.accessType = accessType; - this.file = file; - this.certVerifier = jarSigner; - this.cert = cert; - this.extras = extras; - initialized = true; - - initDialog(); - } + super(); + this.dialogType = dialogType; + this.accessType = accessType; + this.file = file; + this.certVerifier = jarSigner; + this.cert = cert; + this.extras = extras; + initialized = true; + + initDialog(); + } - /** - * Construct a SecurityWarningDialog to display some sort of access warning - */ - SecurityWarningDialog(DialogType dialogType, AccessType accessType, + /** + * Construct a SecurityWarningDialog to display some sort of access warning + */ + SecurityWarningDialog(DialogType dialogType, AccessType accessType, JNLPFile file) { - this(dialogType, accessType, file, null, null, null); - } + this(dialogType, accessType, file, null, null, null); + } - /** - * Create a SecurityWarningDialog to display a certificate-related warning - */ - SecurityWarningDialog(DialogType dialogType, AccessType accessType, + /** + * Create a SecurityWarningDialog to display a certificate-related warning + */ + SecurityWarningDialog(DialogType dialogType, AccessType accessType, JNLPFile file, CertVerifier jarSigner) { - this(dialogType, accessType, file, jarSigner, null, null); - } + this(dialogType, accessType, file, jarSigner, null, null); + } - /** - * Create a SecurityWarningDialog to display a certificate-related warning - */ - SecurityWarningDialog(DialogType dialogType, AccessType accessType, + /** + * Create a SecurityWarningDialog to display a certificate-related warning + */ + SecurityWarningDialog(DialogType dialogType, AccessType accessType, CertVerifier certVerifier) { - this(dialogType, accessType, null, certVerifier, null, null); - } + this(dialogType, accessType, null, certVerifier, null, null); + } - /** - * Create a SecurityWarningDialog to display some sort of access warning - * with more information - */ - SecurityWarningDialog(DialogType dialogType, AccessType accessType, + /** + * Create a SecurityWarningDialog to display some sort of access warning + * with more information + */ + SecurityWarningDialog(DialogType dialogType, AccessType accessType, JNLPFile file, Object[] extras) { - this(dialogType, accessType, file, null, null, extras); - } + this(dialogType, accessType, file, null, null, extras); + } - /** - * Create a SecurityWarningDailog to display information about a single - * certificate - */ - SecurityWarningDialog(DialogType dialogType, X509Certificate c) { - this(dialogType, null, null, null, c, null); - } + /** + * Create a SecurityWarningDailog to display information about a single + * certificate + */ + SecurityWarningDialog(DialogType dialogType, X509Certificate c) { + this(dialogType, null, null, null, c, null); + } - /** - * Returns if this dialog has been fully initialized yet. - * @return true if this dialog has been initialized, and false otherwise. - */ - public boolean isInitialized(){ - return initialized; - } + /** + * Returns if this dialog has been fully initialized yet. + * @return true if this dialog has been initialized, and false otherwise. + */ + public boolean isInitialized() { + return initialized; + } - /** - * Shows more information regarding jar code signing - * - * @param jarSigner the JarSigner used to verify this application - * @param parent the parent option pane - */ - public static void showMoreInfoDialog( + /** + * Shows more information regarding jar code signing + * + * @param jarSigner the JarSigner used to verify this application + * @param parent the parent option pane + */ + public static void showMoreInfoDialog( CertVerifier jarSigner, SecurityWarningDialog parent) { - SecurityWarningDialog dialog = + SecurityWarningDialog dialog = new SecurityWarningDialog(DialogType.MORE_INFO, null, null, - jarSigner); - dialog.setModalityType(ModalityType.APPLICATION_MODAL); - dialog.setVisible(true); - dialog.dispose(); - } + jarSigner); + dialog.setModalityType(ModalityType.APPLICATION_MODAL); + dialog.setVisible(true); + dialog.dispose(); + } - /** - * Displays CertPath information in a readable table format. - * - * @param certs the certificates used in signing. - */ - public static void showCertInfoDialog(CertVerifier jarSigner, + /** + * Displays CertPath information in a readable table format. + * + * @param certs the certificates used in signing. + */ + public static void showCertInfoDialog(CertVerifier jarSigner, SecurityWarningDialog parent) { - SecurityWarningDialog dialog = new SecurityWarningDialog(DialogType.CERT_INFO, + SecurityWarningDialog dialog = new SecurityWarningDialog(DialogType.CERT_INFO, null, null, jarSigner); - dialog.setLocationRelativeTo(parent); - dialog.setModalityType(ModalityType.APPLICATION_MODAL); - dialog.setVisible(true); - dialog.dispose(); - } + dialog.setLocationRelativeTo(parent); + dialog.setModalityType(ModalityType.APPLICATION_MODAL); + dialog.setVisible(true); + dialog.dispose(); + } - /** - * Displays a single certificate's information. - * - * @param c - * @param optionPane - */ - public static void showSingleCertInfoDialog(X509Certificate c, + /** + * Displays a single certificate's information. + * + * @param c + * @param optionPane + */ + public static void showSingleCertInfoDialog(X509Certificate c, JDialog parent) { - SecurityWarningDialog dialog = new SecurityWarningDialog(DialogType.SINGLE_CERT_INFO, c); - dialog.setLocationRelativeTo(parent); - dialog.setModalityType(ModalityType.APPLICATION_MODAL); - dialog.setVisible(true); - dialog.dispose(); - } - - + SecurityWarningDialog dialog = new SecurityWarningDialog(DialogType.SINGLE_CERT_INFO, c); + dialog.setLocationRelativeTo(parent); + dialog.setModalityType(ModalityType.APPLICATION_MODAL); + dialog.setVisible(true); + dialog.dispose(); + } - private void initDialog() { - setSystemLookAndFeel(); + private void initDialog() { + setSystemLookAndFeel(); - String dialogTitle = ""; - if (dialogType == DialogType.CERT_WARNING) - dialogTitle = "Warning - Security"; - else if (dialogType == DialogType.MORE_INFO) - dialogTitle = "More Information"; - else if (dialogType == DialogType.CERT_INFO) - dialogTitle = "Details - Certificate"; - else if (dialogType == DialogType.ACCESS_WARNING) - dialogTitle = "Security Warning"; - else if (dialogType == DialogType.APPLET_WARNING) - dialogTitle = "Applet Warning"; - else if (dialogType == DialogType.NOTALLSIGNED_WARNING) - dialogTitle = "Security Warning"; + String dialogTitle = ""; + if (dialogType == DialogType.CERT_WARNING) + dialogTitle = "Warning - Security"; + else if (dialogType == DialogType.MORE_INFO) + dialogTitle = "More Information"; + else if (dialogType == DialogType.CERT_INFO) + dialogTitle = "Details - Certificate"; + else if (dialogType == DialogType.ACCESS_WARNING) + dialogTitle = "Security Warning"; + else if (dialogType == DialogType.APPLET_WARNING) + dialogTitle = "Applet Warning"; + else if (dialogType == DialogType.NOTALLSIGNED_WARNING) + dialogTitle = "Security Warning"; - setTitle(dialogTitle); - setModalityType(ModalityType.MODELESS); + setTitle(dialogTitle); + setModalityType(ModalityType.MODELESS); - setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setDefaultCloseOperation(DISPOSE_ON_CLOSE); - installPanel(); + installPanel(); - pack(); + pack(); - WindowAdapter adapter = new WindowAdapter() { + WindowAdapter adapter = new WindowAdapter() { private boolean gotFocus = false; @Override @@ -241,6 +239,7 @@ public class SecurityWarningDialog extends JDialog { gotFocus = true; } } + @Override public void windowOpened(WindowEvent e) { if (e.getSource() instanceof SecurityWarningDialog) { @@ -251,57 +250,57 @@ public class SecurityWarningDialog extends JDialog { } } }; - addWindowListener(adapter); - addWindowFocusListener(adapter); + addWindowListener(adapter); + addWindowFocusListener(adapter); - } + } - public AccessType getAccessType() { - return accessType; - } + public AccessType getAccessType() { + return accessType; + } - public JNLPFile getFile() { - return file; - } + public JNLPFile getFile() { + return file; + } - public CertVerifier getJarSigner() { - return certVerifier; - } + public CertVerifier getJarSigner() { + return certVerifier; + } - public X509Certificate getCert() { - return cert; - } + public X509Certificate getCert() { + return cert; + } - /** - * Adds the appropriate JPanel to this Dialog, based on {@link DialogType}. - */ - private void installPanel() { - - if (dialogType == DialogType.CERT_WARNING) - panel = new CertWarningPane(this, this.certVerifier); - else if (dialogType == DialogType.MORE_INFO) - panel = new MoreInfoPane(this, this.certVerifier); - else if (dialogType == DialogType.CERT_INFO) - panel = new CertsInfoPane(this, this.certVerifier); - else if (dialogType == DialogType.SINGLE_CERT_INFO) - panel = new SingleCertInfoPane(this, this.certVerifier); - else if (dialogType == DialogType.ACCESS_WARNING) - panel = new AccessWarningPane(this, extras, this.certVerifier); - else if (dialogType == DialogType.APPLET_WARNING) - panel = new AppletWarningPane(this, this.certVerifier); - else if (dialogType == DialogType.NOTALLSIGNED_WARNING) - panel = new NotAllSignedWarningPane(this); - - add(panel, BorderLayout.CENTER); - } + /** + * Adds the appropriate JPanel to this Dialog, based on {@link DialogType}. + */ + private void installPanel() { + + if (dialogType == DialogType.CERT_WARNING) + panel = new CertWarningPane(this, this.certVerifier); + else if (dialogType == DialogType.MORE_INFO) + panel = new MoreInfoPane(this, this.certVerifier); + else if (dialogType == DialogType.CERT_INFO) + panel = new CertsInfoPane(this, this.certVerifier); + else if (dialogType == DialogType.SINGLE_CERT_INFO) + panel = new SingleCertInfoPane(this, this.certVerifier); + else if (dialogType == DialogType.ACCESS_WARNING) + panel = new AccessWarningPane(this, extras, this.certVerifier); + else if (dialogType == DialogType.APPLET_WARNING) + panel = new AppletWarningPane(this, this.certVerifier); + else if (dialogType == DialogType.NOTALLSIGNED_WARNING) + panel = new NotAllSignedWarningPane(this); + + add(panel, BorderLayout.CENTER); + } - private static void centerDialog(JDialog dialog) { - Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); - Dimension dialogSize = dialog.getSize(); + private static void centerDialog(JDialog dialog) { + Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension dialogSize = dialog.getSize(); - dialog.setLocation((screen.width - dialogSize.width)/2, - (screen.height - dialogSize.height)/2); - } + dialog.setLocation((screen.width - dialogSize.width) / 2, + (screen.height - dialogSize.height) / 2); + } private void selectDefaultButton() { if (panel == null) { diff --git a/netx/net/sourceforge/jnlp/security/SingleCertInfoPane.java b/netx/net/sourceforge/jnlp/security/SingleCertInfoPane.java index 59b8ab8..c60a084 100644 --- a/netx/net/sourceforge/jnlp/security/SingleCertInfoPane.java +++ b/netx/net/sourceforge/jnlp/security/SingleCertInfoPane.java @@ -44,34 +44,33 @@ import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeSelectionModel; - public class SingleCertInfoPane extends CertsInfoPane { - public SingleCertInfoPane(SecurityWarningDialog x, CertVerifier certVerifier) { - super(x, certVerifier); - } + public SingleCertInfoPane(SecurityWarningDialog x, CertVerifier certVerifier) { + super(x, certVerifier); + } - protected void buildTree() { - X509Certificate cert = parent.getCert(); - String subjectString = + protected void buildTree() { + X509Certificate cert = parent.getCert(); + String subjectString = SecurityUtil.getCN(cert.getSubjectX500Principal().getName()); - String issuerString = + String issuerString = SecurityUtil.getCN(cert.getIssuerX500Principal().getName()); - DefaultMutableTreeNode top = new DefaultMutableTreeNode(subjectString + DefaultMutableTreeNode top = new DefaultMutableTreeNode(subjectString + " (" + issuerString + ")"); - tree = new JTree(top); - tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); - tree.addTreeSelectionListener(new TreeSelectionHandler()); - } - - protected void populateTable() { - X509Certificate c = parent.getCert(); - certNames = new String[1]; - certsData = new ArrayList<String[][]>(); - certsData.add(parseCert(c)); - certNames[0] = SecurityUtil.getCN(c.getSubjectX500Principal().getName()) + tree = new JTree(top); + tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); + tree.addTreeSelectionListener(new TreeSelectionHandler()); + } + + protected void populateTable() { + X509Certificate c = parent.getCert(); + certNames = new String[1]; + certsData = new ArrayList<String[][]>(); + certsData.add(parseCert(c)); + certNames[0] = SecurityUtil.getCN(c.getSubjectX500Principal().getName()) + " (" + SecurityUtil.getCN(c.getIssuerX500Principal().getName()) + ")"; - } + } } diff --git a/netx/net/sourceforge/jnlp/security/VariableX509TrustManager.java b/netx/net/sourceforge/jnlp/security/VariableX509TrustManager.java index d40513e..01689ba 100644 --- a/netx/net/sourceforge/jnlp/security/VariableX509TrustManager.java +++ b/netx/net/sourceforge/jnlp/security/VariableX509TrustManager.java @@ -123,7 +123,7 @@ final public class VariableX509TrustManager extends X509ExtendedTrustManager { // tm factory initialized, now get the managers so we can extract the X509 one TrustManager[] trustManagers = tmFactory.getTrustManagers(); - for (int i=0; i < trustManagers.length; i++) { + for (int i = 0; i < trustManagers.length; i++) { if (trustManagers[i] instanceof X509TrustManager) { caTrustManagers[j] = (X509TrustManager) trustManagers[i]; } @@ -147,7 +147,7 @@ final public class VariableX509TrustManager extends X509ExtendedTrustManager { // tm factory initialized, now get the managers so we can extract the X509 one TrustManager[] trustManagers = tmFactory.getTrustManagers(); - for (int i=0; i < trustManagers.length; i++) { + for (int i = 0; i < trustManagers.length; i++) { if (trustManagers[i] instanceof X509TrustManager) { clientTrustManagers[j] = (X509TrustManager) trustManagers[i]; } diff --git a/netx/net/sourceforge/jnlp/security/viewer/CertificatePane.java b/netx/net/sourceforge/jnlp/security/viewer/CertificatePane.java index c85c856..21666d7 100644 --- a/netx/net/sourceforge/jnlp/security/viewer/CertificatePane.java +++ b/netx/net/sourceforge/jnlp/security/viewer/CertificatePane.java @@ -81,224 +81,222 @@ import net.sourceforge.jnlp.util.FileUtils; public class CertificatePane extends JPanel { - /** - * The certificates stored in the certificates file. - */ - private ArrayList<X509Certificate> certs = null; + /** + * The certificates stored in the certificates file. + */ + private ArrayList<X509Certificate> certs = null; - private static final Dimension TABLE_DIMENSION = new Dimension(500,200); + private static final Dimension TABLE_DIMENSION = new Dimension(500, 200); - /** - * "Issued To" and "Issued By" string pairs for certs. - */ - private String[][] issuedToAndBy = null; - private final String[] columnNames = { R("CVIssuedTo"), R("CVIssuedBy") }; + /** + * "Issued To" and "Issued By" string pairs for certs. + */ + private String[][] issuedToAndBy = null; + private final String[] columnNames = { R("CVIssuedTo"), R("CVIssuedBy") }; - private final CertificateType[] certificateTypes = new CertificateType[] { + private final CertificateType[] certificateTypes = new CertificateType[] { new CertificateType(KeyStores.Type.CA_CERTS), new CertificateType(KeyStores.Type.JSSE_CA_CERTS), new CertificateType(KeyStores.Type.CERTS), new CertificateType(KeyStores.Type.JSSE_CERTS), }; - JTabbedPane tabbedPane; - private final JTable userTable; - private final JTable systemTable; - private JComboBox certificateTypeCombo; - private KeyStores.Type currentKeyStoreType; - private KeyStores.Level currentKeyStoreLevel; - - /** JComponents that should be disbled for system store */ - private final List<JComponent> disableForSystem; + JTabbedPane tabbedPane; + private final JTable userTable; + private final JTable systemTable; + private JComboBox certificateTypeCombo; + private KeyStores.Type currentKeyStoreType; + private KeyStores.Level currentKeyStoreLevel; - private JDialog parent; - private JComponent defaultFocusComponent = null; + /** JComponents that should be disbled for system store */ + private final List<JComponent> disableForSystem; - /** - * The Current KeyStore. Only one table/tab is visible for interaction to - * the user. This KeyStore corresponds to that. - */ - private KeyStore keyStore = null; + private JDialog parent; + private JComponent defaultFocusComponent = null; - public CertificatePane(JDialog parent) { - super(); - this.parent = parent; + /** + * The Current KeyStore. Only one table/tab is visible for interaction to + * the user. This KeyStore corresponds to that. + */ + private KeyStore keyStore = null; - userTable = new JTable(null); - systemTable = new JTable(null); - disableForSystem = new ArrayList<JComponent>(); + public CertificatePane(JDialog parent) { + super(); + this.parent = parent; - addComponents(); + userTable = new JTable(null); + systemTable = new JTable(null); + disableForSystem = new ArrayList<JComponent>(); - currentKeyStoreType = ((CertificateType)(certificateTypeCombo.getSelectedItem())).getType(); - if (tabbedPane.getSelectedIndex() == 0) { - currentKeyStoreLevel = Level.USER; - } else { - currentKeyStoreLevel = Level.SYSTEM; - } + addComponents(); - repopulateTables(); + currentKeyStoreType = ((CertificateType) (certificateTypeCombo.getSelectedItem())).getType(); + if (tabbedPane.getSelectedIndex() == 0) { + currentKeyStoreLevel = Level.USER; + } else { + currentKeyStoreLevel = Level.SYSTEM; } - /** - * Reads the user's trusted.cacerts keystore. - */ - private void initializeKeyStore() { - try { - keyStore = KeyStores.getKeyStore(currentKeyStoreLevel, currentKeyStoreType); - } catch (Exception e) { - e.printStackTrace(); - } + repopulateTables(); + } + + /** + * Reads the user's trusted.cacerts keystore. + */ + private void initializeKeyStore() { + try { + keyStore = KeyStores.getKeyStore(currentKeyStoreLevel, currentKeyStoreType); + } catch (Exception e) { + e.printStackTrace(); } + } - //create the GUI here. - protected void addComponents() { + //create the GUI here. + protected void addComponents() { - JPanel main = new JPanel(new BorderLayout()); + JPanel main = new JPanel(new BorderLayout()); - JPanel certificateTypePanel = new JPanel(new BorderLayout()); - certificateTypePanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); + JPanel certificateTypePanel = new JPanel(new BorderLayout()); + certificateTypePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); - JLabel certificateTypeLabel = new JLabel(R("CVCertificateType")); + JLabel certificateTypeLabel = new JLabel(R("CVCertificateType")); - certificateTypeCombo = new JComboBox(certificateTypes); - certificateTypeCombo.addActionListener(new CertificateTypeListener()); + certificateTypeCombo = new JComboBox(certificateTypes); + certificateTypeCombo.addActionListener(new CertificateTypeListener()); - certificateTypePanel.add(certificateTypeLabel, BorderLayout.LINE_START); - certificateTypePanel.add(certificateTypeCombo, BorderLayout.CENTER); + certificateTypePanel.add(certificateTypeLabel, BorderLayout.LINE_START); + certificateTypePanel.add(certificateTypeCombo, BorderLayout.CENTER); - JPanel tablePanel = new JPanel(new BorderLayout()); + JPanel tablePanel = new JPanel(new BorderLayout()); - // User Table - DefaultTableModel userTableModel - = new DefaultTableModel(issuedToAndBy, columnNames); - userTable.setModel(userTableModel); - userTable.getTableHeader().setReorderingAllowed(false); - userTable.setFillsViewportHeight(true); - JScrollPane userTablePane = new JScrollPane(userTable); - userTablePane.setPreferredSize(TABLE_DIMENSION); - userTablePane.setSize(TABLE_DIMENSION); - userTablePane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); + // User Table + DefaultTableModel userTableModel = new DefaultTableModel(issuedToAndBy, columnNames); + userTable.setModel(userTableModel); + userTable.getTableHeader().setReorderingAllowed(false); + userTable.setFillsViewportHeight(true); + JScrollPane userTablePane = new JScrollPane(userTable); + userTablePane.setPreferredSize(TABLE_DIMENSION); + userTablePane.setSize(TABLE_DIMENSION); + userTablePane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); - // System Table - DefaultTableModel systemTableModel = new DefaultTableModel(issuedToAndBy, columnNames); - systemTable.setModel(systemTableModel); - systemTable.getTableHeader().setReorderingAllowed(false); - systemTable.setFillsViewportHeight(true); - JScrollPane systemTablePane = new JScrollPane(systemTable); - systemTablePane.setPreferredSize(TABLE_DIMENSION); - systemTablePane.setSize(TABLE_DIMENSION); - systemTablePane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); + // System Table + DefaultTableModel systemTableModel = new DefaultTableModel(issuedToAndBy, columnNames); + systemTable.setModel(systemTableModel); + systemTable.getTableHeader().setReorderingAllowed(false); + systemTable.setFillsViewportHeight(true); + JScrollPane systemTablePane = new JScrollPane(systemTable); + systemTablePane.setPreferredSize(TABLE_DIMENSION); + systemTablePane.setSize(TABLE_DIMENSION); + systemTablePane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); - tabbedPane = new JTabbedPane(); - tabbedPane.addTab(R("CVUser"), userTablePane); - tabbedPane.addTab(R("CVSystem"), systemTablePane); - tabbedPane.addChangeListener(new TabChangeListener()); + tabbedPane = new JTabbedPane(); + tabbedPane.addTab(R("CVUser"), userTablePane); + tabbedPane.addTab(R("CVSystem"), systemTablePane); + tabbedPane.addChangeListener(new TabChangeListener()); - JPanel buttonPanel = new JPanel(new FlowLayout()); + JPanel buttonPanel = new JPanel(new FlowLayout()); - String[] buttonNames = {R("CVImport"), R("CVExport"), R("CVRemove"), R("CVDetails")}; - char[] buttonMnemonics = { KeyEvent.VK_I, + String[] buttonNames = { R("CVImport"), R("CVExport"), R("CVRemove"), R("CVDetails") }; + char[] buttonMnemonics = { KeyEvent.VK_I, KeyEvent.VK_E, KeyEvent.VK_M, - KeyEvent.VK_D}; - ActionListener[] listeners = { new ImportButtonListener(), + KeyEvent.VK_D }; + ActionListener[] listeners = { new ImportButtonListener(), new ExportButtonListener(), new RemoveButtonListener(), new DetailsButtonListener() }; - JButton button; + JButton button; - //get the max width - int maxWidth = 0; - for (int i = 0; i < buttonNames.length; i++) { - button = new JButton(buttonNames[i]); - maxWidth = Math.max(maxWidth, button.getMinimumSize().width); - } + //get the max width + int maxWidth = 0; + for (int i = 0; i < buttonNames.length; i++) { + button = new JButton(buttonNames[i]); + maxWidth = Math.max(maxWidth, button.getMinimumSize().width); + } - for (int i = 0; i < buttonNames.length; i++) { - button = new JButton(buttonNames[i]); - button.setMnemonic(buttonMnemonics[i]); - button.addActionListener(listeners[i]); - button.setSize(maxWidth, button.getSize().height); - // import and remove buttons - if (i == 0 || i == 2) { - disableForSystem.add(button); - } - buttonPanel.add(button); - } + for (int i = 0; i < buttonNames.length; i++) { + button = new JButton(buttonNames[i]); + button.setMnemonic(buttonMnemonics[i]); + button.addActionListener(listeners[i]); + button.setSize(maxWidth, button.getSize().height); + // import and remove buttons + if (i == 0 || i == 2) { + disableForSystem.add(button); + } + buttonPanel.add(button); + } - tablePanel.add(tabbedPane, BorderLayout.CENTER); - tablePanel.add(buttonPanel, BorderLayout.SOUTH); - - main.add(certificateTypePanel, BorderLayout.NORTH); - main.add(tablePanel, BorderLayout.CENTER); - - if (parent != null){ - JPanel closePanel = new JPanel(new BorderLayout()); - closePanel.setBorder(BorderFactory.createEmptyBorder(7,7,7,7)); - JButton closeButton = new JButton(R("ButClose")); - closeButton.addActionListener(new CloseButtonListener()); - defaultFocusComponent = closeButton; - closePanel.add(closeButton, BorderLayout.EAST); - main.add(closePanel, BorderLayout.SOUTH); - } - add(main); + tablePanel.add(tabbedPane, BorderLayout.CENTER); + tablePanel.add(buttonPanel, BorderLayout.SOUTH); - } + main.add(certificateTypePanel, BorderLayout.NORTH); + main.add(tablePanel, BorderLayout.CENTER); - /** - * Read in the optionPane's keystore to issuedToAndBy. - */ - private void readKeyStore() { + if (parent != null) { + JPanel closePanel = new JPanel(new BorderLayout()); + closePanel.setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7)); + JButton closeButton = new JButton(R("ButClose")); + closeButton.addActionListener(new CloseButtonListener()); + defaultFocusComponent = closeButton; + closePanel.add(closeButton, BorderLayout.EAST); + main.add(closePanel, BorderLayout.SOUTH); + } + add(main); - Enumeration<String> aliases = null; - certs = new ArrayList<X509Certificate>(); - try { + } - //Get all of the X509Certificates and put them into an ArrayList - aliases = keyStore.aliases(); - while (aliases.hasMoreElements()) { - Certificate c = keyStore.getCertificate(aliases.nextElement()); - if (c instanceof X509Certificate) - certs.add((X509Certificate)c); - } + /** + * Read in the optionPane's keystore to issuedToAndBy. + */ + private void readKeyStore() { + + Enumeration<String> aliases = null; + certs = new ArrayList<X509Certificate>(); + try { + + //Get all of the X509Certificates and put them into an ArrayList + aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + Certificate c = keyStore.getCertificate(aliases.nextElement()); + if (c instanceof X509Certificate) + certs.add((X509Certificate) c); + } - //get the publisher and root information - issuedToAndBy = new String[certs.size()][2]; - for (int i = 0; i < certs.size(); i++) { - X509Certificate c = certs.get(i); - issuedToAndBy[i][0] = + //get the publisher and root information + issuedToAndBy = new String[certs.size()][2]; + for (int i = 0; i < certs.size(); i++) { + X509Certificate c = certs.get(i); + issuedToAndBy[i][0] = SecurityUtil.getCN(c.getSubjectX500Principal().getName()); - issuedToAndBy[i][1] = + issuedToAndBy[i][1] = SecurityUtil.getCN(c.getIssuerX500Principal().getName()); - } - } catch (Exception e) { - //TODO - e.printStackTrace(); - } + } + } catch (Exception e) { + //TODO + e.printStackTrace(); } + } - /** - * Re-reads the certs file and repopulates the JTable. This is typically - * called after a certificate was deleted from the keystore. - */ - private void repopulateTables() { - initializeKeyStore(); - readKeyStore(); - DefaultTableModel tableModel - = new DefaultTableModel(issuedToAndBy, columnNames); + /** + * Re-reads the certs file and repopulates the JTable. This is typically + * called after a certificate was deleted from the keystore. + */ + private void repopulateTables() { + initializeKeyStore(); + readKeyStore(); + DefaultTableModel tableModel = new DefaultTableModel(issuedToAndBy, columnNames); - userTable.setModel(tableModel); + userTable.setModel(tableModel); - tableModel = new DefaultTableModel(issuedToAndBy, columnNames); - systemTable.setModel(tableModel); - } + tableModel = new DefaultTableModel(issuedToAndBy, columnNames); + systemTable.setModel(tableModel); + } - public void focusOnDefaultButton() { - if (defaultFocusComponent != null) { - defaultFocusComponent.requestFocusInWindow(); - } + public void focusOnDefaultButton() { + if (defaultFocusComponent != null) { + defaultFocusComponent.requestFocusInWindow(); } + } /** Allows storing KeyStores.Types in a JComponent */ private class CertificateType { @@ -355,74 +353,73 @@ public class CertificatePane extends JPanel { } } - private class ImportButtonListener implements ActionListener { + private class ImportButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { - JFileChooser chooser = new JFileChooser(); - int returnVal = chooser.showOpenDialog(parent); - if(returnVal == JFileChooser.APPROVE_OPTION) { - try { - KeyStore ks = keyStore; - CertificateUtils.addToKeyStore(chooser.getSelectedFile(), ks); - File keyStoreFile = new File(KeyStores + JFileChooser chooser = new JFileChooser(); + int returnVal = chooser.showOpenDialog(parent); + if (returnVal == JFileChooser.APPROVE_OPTION) { + try { + KeyStore ks = keyStore; + CertificateUtils.addToKeyStore(chooser.getSelectedFile(), ks); + File keyStoreFile = new File(KeyStores .getKeyStoreLocation(currentKeyStoreLevel, currentKeyStoreType)); - if (!keyStoreFile.isFile()) { - FileUtils.createRestrictedFile(keyStoreFile, true); - } - - OutputStream os = new FileOutputStream(keyStoreFile); - ks.store(os, KeyStores.getPassword()); - repopulateTables(); - } catch (Exception ex) { - // TODO: handle exception - ex.printStackTrace(); - } + if (!keyStoreFile.isFile()) { + FileUtils.createRestrictedFile(keyStoreFile, true); + } + + OutputStream os = new FileOutputStream(keyStoreFile); + ks.store(os, KeyStores.getPassword()); + repopulateTables(); + } catch (Exception ex) { + // TODO: handle exception + ex.printStackTrace(); } + } } } - private class ExportButtonListener implements ActionListener { - public void actionPerformed(ActionEvent e) { - - JTable table = null; - if (currentKeyStoreLevel == Level.USER) { - table = userTable; - } else { - table = systemTable; - } + private class ExportButtonListener implements ActionListener { + public void actionPerformed(ActionEvent e) { - //For now, let's just export in -rfc mode as keytool does. - //we'll write to a file the exported certificate. + JTable table = null; + if (currentKeyStoreLevel == Level.USER) { + table = userTable; + } else { + table = systemTable; + } + //For now, let's just export in -rfc mode as keytool does. + //we'll write to a file the exported certificate. - try { - int selectedRow = table.getSelectedRow(); - if (selectedRow != -1) { - JFileChooser chooser = new JFileChooser(); - int returnVal = chooser.showOpenDialog(parent); - if(returnVal == JFileChooser.APPROVE_OPTION) { - String alias = keyStore.getCertificateAlias(certs + try { + int selectedRow = table.getSelectedRow(); + if (selectedRow != -1) { + JFileChooser chooser = new JFileChooser(); + int returnVal = chooser.showOpenDialog(parent); + if (returnVal == JFileChooser.APPROVE_OPTION) { + String alias = keyStore.getCertificateAlias(certs .get(selectedRow)); - if (alias != null) { - Certificate c = keyStore.getCertificate(alias); - PrintStream ps = new PrintStream(chooser.getSelectedFile().getAbsolutePath()); - CertificateUtils.dump(c, ps); - repopulateTables(); - } - } - } - } catch (Exception ex) { - // TODO - ex.printStackTrace(); + if (alias != null) { + Certificate c = keyStore.getCertificate(alias); + PrintStream ps = new PrintStream(chooser.getSelectedFile().getAbsolutePath()); + CertificateUtils.dump(c, ps); + repopulateTables(); } + } } + } catch (Exception ex) { + // TODO + ex.printStackTrace(); + } } + } - private class RemoveButtonListener implements ActionListener { + private class RemoveButtonListener implements ActionListener { - /** - * Removes a certificate from the keyStore and writes changes to disk. - */ + /** + * Removes a certificate from the keyStore and writes changes to disk. + */ public void actionPerformed(ActionEvent e) { JTable table = null; @@ -431,44 +428,44 @@ public class CertificatePane extends JPanel { } else { table = systemTable; } - try { - int selectedRow = table.getSelectedRow(); + try { + int selectedRow = table.getSelectedRow(); - if (selectedRow != -1){ - String alias = keyStore.getCertificateAlias(certs.get(selectedRow)); - if (alias != null) { + if (selectedRow != -1) { + String alias = keyStore.getCertificateAlias(certs.get(selectedRow)); + if (alias != null) { - int i = JOptionPane.showConfirmDialog(parent, + int i = JOptionPane.showConfirmDialog(parent, R("CVRemoveConfirmMessage"), R("CVRemoveConfirmTitle"), JOptionPane.YES_NO_OPTION); - if (i == 0) { - keyStore.deleteEntry(alias); - File keyStoreFile = new File(KeyStores + if (i == 0) { + keyStore.deleteEntry(alias); + File keyStoreFile = new File(KeyStores .getKeyStoreLocation(currentKeyStoreLevel, currentKeyStoreType)); - if (!keyStoreFile.isFile()) { - FileUtils.createRestrictedFile(keyStoreFile, true); - } - FileOutputStream fos = new FileOutputStream(keyStoreFile); - keyStore.store(fos, KeyStores.getPassword()); - fos.close(); - } - } - repopulateTables(); + if (!keyStoreFile.isFile()) { + FileUtils.createRestrictedFile(keyStoreFile, true); + } + FileOutputStream fos = new FileOutputStream(keyStoreFile); + keyStore.store(fos, KeyStores.getPassword()); + fos.close(); } - } catch (Exception ex) { - // TODO - ex.printStackTrace(); + } + repopulateTables(); } + } catch (Exception ex) { + // TODO + ex.printStackTrace(); + } } } - private class DetailsButtonListener implements ActionListener { + private class DetailsButtonListener implements ActionListener { - /** - * Shows the details of a trusted certificate. - */ + /** + * Shows the details of a trusted certificate. + */ public void actionPerformed(ActionEvent e) { JTable table = null; @@ -478,19 +475,19 @@ public class CertificatePane extends JPanel { table = systemTable; } - int selectedRow = table.getSelectedRow(); - if (selectedRow != -1 && selectedRow >= 0) { - X509Certificate c = certs.get(selectedRow); - SecurityWarningDialog.showSingleCertInfoDialog(c, parent); - } + int selectedRow = table.getSelectedRow(); + if (selectedRow != -1 && selectedRow >= 0) { + X509Certificate c = certs.get(selectedRow); + SecurityWarningDialog.showSingleCertInfoDialog(c, parent); + } } } - private class CloseButtonListener implements ActionListener { - @Override - public void actionPerformed(ActionEvent e) { - parent.dispose(); - } + private class CloseButtonListener implements ActionListener { + @Override + public void actionPerformed(ActionEvent e) { + parent.dispose(); } + } } diff --git a/netx/net/sourceforge/jnlp/security/viewer/CertificateViewer.java b/netx/net/sourceforge/jnlp/security/viewer/CertificateViewer.java index 57bafd3..c497308 100644 --- a/netx/net/sourceforge/jnlp/security/viewer/CertificateViewer.java +++ b/netx/net/sourceforge/jnlp/security/viewer/CertificateViewer.java @@ -59,8 +59,8 @@ public class CertificateViewer extends JDialog { CertificatePane panel; - public CertificateViewer() { - super((Frame)null, dialogTitle, true); + public CertificateViewer() { + super((Frame) null, dialogTitle, true); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); @@ -84,32 +84,31 @@ public class CertificateViewer extends JDialog { }; addWindowFocusListener(adapter); - initialized = true; - } - - public boolean isInitialized(){ - return initialized; - } + initialized = true; + } - private void centerDialog() { - Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); - Dimension dialogSize = getSize(); + public boolean isInitialized() { + return initialized; + } - setLocation((screen.width - dialogSize.width)/2, - (screen.height - dialogSize.height)/2); - } + private void centerDialog() { + Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension dialogSize = getSize(); + setLocation((screen.width - dialogSize.width) / 2, + (screen.height - dialogSize.height) / 2); + } - public static void showCertificateViewer() throws Exception { - JNLPRuntime.initialize(true); - setSystemLookAndFeel(); + public static void showCertificateViewer() throws Exception { + JNLPRuntime.initialize(true); + setSystemLookAndFeel(); - CertificateViewer cv = new CertificateViewer(); - cv.setResizable(true); - cv.centerDialog(); - cv.setVisible(true); - cv.dispose(); - } + CertificateViewer cv = new CertificateViewer(); + cv.setResizable(true); + cv.centerDialog(); + cv.setVisible(true); + cv.dispose(); + } private static void setSystemLookAndFeel() { try { @@ -119,7 +118,7 @@ public class CertificateViewer extends JDialog { } } - public static void main(String[] args) throws Exception { - CertificateViewer.showCertificateViewer(); - } + public static void main(String[] args) throws Exception { + CertificateViewer.showCertificateViewer(); + } } diff --git a/netx/net/sourceforge/jnlp/services/ServiceUtil.java b/netx/net/sourceforge/jnlp/services/ServiceUtil.java index 62ce28f..96d040a 100644 --- a/netx/net/sourceforge/jnlp/services/ServiceUtil.java +++ b/netx/net/sourceforge/jnlp/services/ServiceUtil.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.services; import java.lang.reflect.InvocationHandler; @@ -143,8 +142,7 @@ public class ServiceUtil { private static Object getService(String name) { try { return ServiceManager.lookup(name); - } - catch (UnavailableServiceException ex) { + } catch (UnavailableServiceException ex) { return null; } } @@ -174,10 +172,10 @@ public class ServiceUtil { public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable { if (JNLPRuntime.isDebug()) { - System.err.println("call privileged method: "+method.getName()); + System.err.println("call privileged method: " + method.getName()); if (args != null) - for (int i=0; i < args.length; i++) - System.err.println(" arg: "+args[i]); + for (int i = 0; i < args.length; i++) + System.err.println(" arg: " + args[i]); } PrivilegedExceptionAction<Object> invoker = new PrivilegedExceptionAction<Object>() { @@ -190,7 +188,7 @@ public class ServiceUtil { Object result = AccessController.doPrivileged(invoker); if (JNLPRuntime.isDebug()) - System.err.println(" result: "+result); + System.err.println(" result: " + result); return result; } catch (PrivilegedActionException e) { @@ -238,57 +236,57 @@ public class ServiceUtil { Object... extras) { if (app == null) - app = JNLPRuntime.getApplication(); + app = JNLPRuntime.getApplication(); boolean codeTrusted = true; - StackTraceElement[] stack = Thread.currentThread().getStackTrace(); + StackTraceElement[] stack = Thread.currentThread().getStackTrace(); - for (int i=0; i < stack.length; i++) { + for (int i = 0; i < stack.length; i++) { - Class c = null; + Class c = null; + try { + c = Class.forName(stack[i].getClassName()); + } catch (Exception e1) { try { - c = Class.forName(stack[i].getClassName()); - } catch (Exception e1) { - try { - c = Class.forName(stack[i].getClassName(), false, app.getClassLoader()); - } catch (Exception e2) { - System.err.println(e2.getMessage()); - } + c = Class.forName(stack[i].getClassName(), false, app.getClassLoader()); + } catch (Exception e2) { + System.err.println(e2.getMessage()); } + } // Everything up to the desired class/method must be trusted if (c == null || // class not found - ( c.getProtectionDomain().getCodeSource() != null && // class is not in bootclasspath - c.getProtectionDomain().getCodeSource().getCodeSigners() == null) // class is trusted - ) { + (c.getProtectionDomain().getCodeSource() != null && // class is not in bootclasspath + c.getProtectionDomain().getCodeSource().getCodeSigners() == null) // class is trusted + ) { codeTrusted = false; } } if (!codeTrusted) { - if (!shouldPromptUser()) { - return false; - } + if (!shouldPromptUser()) { + return false; + } - final AccessType tmpType = type; - final Object[] tmpExtras = extras; - final ApplicationInstance tmpApp = app; + final AccessType tmpType = type; + final Object[] tmpExtras = extras; + final ApplicationInstance tmpApp = app; - //We need to do this to allow proper icon loading for unsigned - //applets, otherwise permissions won't be granted to load icons - //from resources.jar. - Boolean b = AccessController.doPrivileged(new PrivilegedAction<Boolean>() { - public Boolean run() { - boolean b = SecurityWarning.showAccessWarningDialog(tmpType, + //We need to do this to allow proper icon loading for unsigned + //applets, otherwise permissions won't be granted to load icons + //from resources.jar. + Boolean b = AccessController.doPrivileged(new PrivilegedAction<Boolean>() { + public Boolean run() { + boolean b = SecurityWarning.showAccessWarningDialog(tmpType, tmpApp.getJNLPFile(), tmpExtras); - return new Boolean(b); - } - }); + return new Boolean(b); + } + }); - return b.booleanValue(); + return b.booleanValue(); } return true; //allow diff --git a/netx/net/sourceforge/jnlp/services/XBasicService.java b/netx/net/sourceforge/jnlp/services/XBasicService.java index a46a309..124025c 100644 --- a/netx/net/sourceforge/jnlp/services/XBasicService.java +++ b/netx/net/sourceforge/jnlp/services/XBasicService.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.services; import java.io.IOException; @@ -48,7 +47,6 @@ class XBasicService implements BasicService { /** whether the command was loaded / prompted for */ private boolean initialized = false; - protected XBasicService() { } @@ -128,7 +126,7 @@ class XBasicService implements BasicService { } JARDesc[] jarDescs = jnlpFile.getResources().getJARs(); - for (JARDesc jarDesc: jarDescs) { + for (JARDesc jarDesc : jarDescs) { return jarDesc.getLocation(); } } @@ -159,15 +157,14 @@ class XBasicService implements BasicService { * * @return whether the document was opened */ - public boolean showDocument(URL url) { + public boolean showDocument(URL url) { initialize(); if (url.toString().endsWith(".jnlp")) { try { new Launcher().launchExternal(url); return true; - } - catch (Exception ex) { + } catch (Exception ex) { return false; } } @@ -181,8 +178,7 @@ class XBasicService implements BasicService { //Runtime.getRuntime().exec(new String[]{command,url.toString()}); return true; - } - catch(IOException ex){ + } catch (IOException ex) { if (JNLPRuntime.isDebug()) ex.printStackTrace(); } @@ -196,17 +192,16 @@ class XBasicService implements BasicService { return; initialized = true; - if(isWindows()) { + if (isWindows()) { command = "rundll32 url.dll,FileProtocolHandler "; - } - else { + } else { DeploymentConfiguration config = JNLPRuntime.getConfiguration(); command = config.getProperty(DeploymentConfiguration.KEY_BROWSER_PATH); - if(command == null) { // prompt & store + if (command == null) { // prompt & store command = promptForCommand(null); - if(command != null) { + if (command != null) { config.setProperty(DeploymentConfiguration.KEY_BROWSER_PATH, command); try { config.save(); @@ -220,7 +215,7 @@ class XBasicService implements BasicService { private boolean isWindows() { String os = System.getProperty("os.name"); - if(os != null && os.startsWith("Windows")) + if (os != null && os.startsWith("Windows")) return true; else return false; diff --git a/netx/net/sourceforge/jnlp/services/XClipboardService.java b/netx/net/sourceforge/jnlp/services/XClipboardService.java index b00e6da..6f462e5 100644 --- a/netx/net/sourceforge/jnlp/services/XClipboardService.java +++ b/netx/net/sourceforge/jnlp/services/XClipboardService.java @@ -51,31 +51,31 @@ import java.awt.Toolkit; */ class XClipboardService implements ClipboardService { - protected XClipboardService() { - } + protected XClipboardService() { + } - /** - * Returns the contents of the system clipboard. - */ - public java.awt.datatransfer.Transferable getContents(){ + /** + * Returns the contents of the system clipboard. + */ + public java.awt.datatransfer.Transferable getContents() { - if (ServiceUtil.checkAccess(AccessType.CLIPBOARD_READ)) { - Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); - return (Transferable) ServiceUtil.createPrivilegedProxy( + if (ServiceUtil.checkAccess(AccessType.CLIPBOARD_READ)) { + Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null); + return (Transferable) ServiceUtil.createPrivilegedProxy( Transferable.class, t); - } else { - return null; - } + } else { + return null; } - - /** - * Sets the contents of the system clipboard. - */ - public void setContents(java.awt.datatransfer.Transferable contents) { - if (ServiceUtil.checkAccess(AccessType.CLIPBOARD_WRITE)) { - Toolkit.getDefaultToolkit().getSystemClipboard().setContents( + } + + /** + * Sets the contents of the system clipboard. + */ + public void setContents(java.awt.datatransfer.Transferable contents) { + if (ServiceUtil.checkAccess(AccessType.CLIPBOARD_WRITE)) { + Toolkit.getDefaultToolkit().getSystemClipboard().setContents( contents, null); - } } + } } diff --git a/netx/net/sourceforge/jnlp/services/XDownloadService.java b/netx/net/sourceforge/jnlp/services/XDownloadService.java index 174071a..8d2f6d3 100644 --- a/netx/net/sourceforge/jnlp/services/XDownloadService.java +++ b/netx/net/sourceforge/jnlp/services/XDownloadService.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.services; import java.io.*; diff --git a/netx/net/sourceforge/jnlp/services/XExtendedService.java b/netx/net/sourceforge/jnlp/services/XExtendedService.java index 296740d..88da724 100644 --- a/netx/net/sourceforge/jnlp/services/XExtendedService.java +++ b/netx/net/sourceforge/jnlp/services/XExtendedService.java @@ -35,7 +35,7 @@ public class XExtendedService implements ExtendedService { public FileContents openFile(File file) throws IOException { /* FIXME: this opens a file with read/write mode, not just read or write */ - if (ServiceUtil.checkAccess(AccessType.READ_FILE, new Object[]{ file.getAbsolutePath() })) { + if (ServiceUtil.checkAccess(AccessType.READ_FILE, new Object[] { file.getAbsolutePath() })) { return (FileContents) ServiceUtil.createPrivilegedProxy(FileContents.class, new XFileContents(file)); } else { diff --git a/netx/net/sourceforge/jnlp/services/XExtensionInstallerService.java b/netx/net/sourceforge/jnlp/services/XExtensionInstallerService.java index 7fea6bb..b60218b 100644 --- a/netx/net/sourceforge/jnlp/services/XExtensionInstallerService.java +++ b/netx/net/sourceforge/jnlp/services/XExtensionInstallerService.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.services; import java.io.*; diff --git a/netx/net/sourceforge/jnlp/services/XFileContents.java b/netx/net/sourceforge/jnlp/services/XFileContents.java index c7b331a..48904c5 100644 --- a/netx/net/sourceforge/jnlp/services/XFileContents.java +++ b/netx/net/sourceforge/jnlp/services/XFileContents.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.services; import java.io.*; @@ -117,5 +116,4 @@ class XFileContents implements FileContents { return maxlength; } - } diff --git a/netx/net/sourceforge/jnlp/services/XFileOpenService.java b/netx/net/sourceforge/jnlp/services/XFileOpenService.java index 61d2bdb..e238b16 100644 --- a/netx/net/sourceforge/jnlp/services/XFileOpenService.java +++ b/netx/net/sourceforge/jnlp/services/XFileOpenService.java @@ -64,8 +64,8 @@ class XFileOpenService implements FileOpenService { /** * Prompts the user to select a single file. */ - public FileContents openFileDialog (java.lang.String pathHint, - java.lang.String[] extensions) throws java.io.IOException { + public FileContents openFileDialog(java.lang.String pathHint, + java.lang.String[] extensions) throws java.io.IOException { if (ServiceUtil.checkAccess(AccessType.READ_FILE)) { @@ -87,7 +87,7 @@ class XFileOpenService implements FileOpenService { /** * Prompts the user to select one or more files. */ - public FileContents[] openMultiFileDialog (java.lang.String pathHint, + public FileContents[] openMultiFileDialog(java.lang.String pathHint, java.lang.String[] extensions) throws java.io.IOException { if (ServiceUtil.checkAccess(AccessType.WRITE_FILE)) { diff --git a/netx/net/sourceforge/jnlp/services/XFileSaveService.java b/netx/net/sourceforge/jnlp/services/XFileSaveService.java index c4e856b..1477b8c 100644 --- a/netx/net/sourceforge/jnlp/services/XFileSaveService.java +++ b/netx/net/sourceforge/jnlp/services/XFileSaveService.java @@ -64,8 +64,8 @@ class XFileSaveService implements FileSaveService { * Prompts the user to save a file. */ public FileContents saveFileDialog(java.lang.String pathHint, - java.lang.String[] extensions, java.io.InputStream stream, - java.lang.String name) throws java.io.IOException { + java.lang.String[] extensions, java.io.InputStream stream, + java.lang.String name) throws java.io.IOException { if (ServiceUtil.checkAccess(AccessType.WRITE_FILE)) { JFileChooser chooser = new JFileChooser(); @@ -88,7 +88,7 @@ class XFileSaveService implements FileSaveService { * Prompts the user to save a file, with an optional pre-set filename. */ public FileContents saveAsFileDialog(java.lang.String pathHint, - java.lang.String[] extensions, FileContents contents) throws java.io.IOException { + java.lang.String[] extensions, FileContents contents) throws java.io.IOException { if (ServiceUtil.checkAccess(AccessType.WRITE_FILE)) { JFileChooser chooser = new JFileChooser(); @@ -117,7 +117,7 @@ class XFileSaveService implements FileSaveService { if (!file.createNewFile()) { //file exists boolean replace = (JOptionPane.showConfirmDialog(null, file.getAbsolutePath() + " already exists.\n" - +"Do you want to replace it?", + + "Do you want to replace it?", "Warning - File Exists", JOptionPane.YES_NO_OPTION) == 0); if (!replace) return; diff --git a/netx/net/sourceforge/jnlp/services/XJNLPRandomAccessFile.java b/netx/net/sourceforge/jnlp/services/XJNLPRandomAccessFile.java index 8e97743..b8eca83 100644 --- a/netx/net/sourceforge/jnlp/services/XJNLPRandomAccessFile.java +++ b/netx/net/sourceforge/jnlp/services/XJNLPRandomAccessFile.java @@ -44,160 +44,160 @@ import javax.jnlp.JNLPRandomAccessFile; public class XJNLPRandomAccessFile implements JNLPRandomAccessFile { - private RandomAccessFile raf; + private RandomAccessFile raf; - public XJNLPRandomAccessFile(File file, String mode) throws IOException { - raf = new RandomAccessFile(file, mode); + public XJNLPRandomAccessFile(File file, String mode) throws IOException { + raf = new RandomAccessFile(file, mode); - } + } - public void close() throws IOException { - raf.close(); - } + public void close() throws IOException { + raf.close(); + } - public long getFilePointer() throws IOException { - return raf.getFilePointer(); - } + public long getFilePointer() throws IOException { + return raf.getFilePointer(); + } - public long length() throws IOException { - return raf.length(); - } + public long length() throws IOException { + return raf.length(); + } - public int read() throws IOException { - return raf.read(); - } + public int read() throws IOException { + return raf.read(); + } - public int read(byte[] b, int off, int len) throws IOException { - return raf.read(b, off, len); - } + public int read(byte[] b, int off, int len) throws IOException { + return raf.read(b, off, len); + } - public int read(byte[] b) throws IOException { - return raf.read(b); - } + public int read(byte[] b) throws IOException { + return raf.read(b); + } - public boolean readBoolean() throws IOException { - return raf.readBoolean(); - } + public boolean readBoolean() throws IOException { + return raf.readBoolean(); + } - public byte readByte() throws IOException { - return raf.readByte(); - } + public byte readByte() throws IOException { + return raf.readByte(); + } - public char readChar() throws IOException { - return raf.readChar(); - } + public char readChar() throws IOException { + return raf.readChar(); + } - public double readDouble() throws IOException { - return raf.readDouble(); - } + public double readDouble() throws IOException { + return raf.readDouble(); + } - public float readFloat() throws IOException { - return raf.readFloat(); - } + public float readFloat() throws IOException { + return raf.readFloat(); + } - public void readFully(byte[] b) throws IOException { - raf.readFully(b); - } + public void readFully(byte[] b) throws IOException { + raf.readFully(b); + } - public void readFully(byte[] b, int off, int len) throws IOException { - raf.readFully(b, off, len); - } + public void readFully(byte[] b, int off, int len) throws IOException { + raf.readFully(b, off, len); + } - public int readInt() throws IOException { - return raf.readInt(); - } + public int readInt() throws IOException { + return raf.readInt(); + } - public String readLine() throws IOException { - return raf.readLine(); - } + public String readLine() throws IOException { + return raf.readLine(); + } - public long readLong() throws IOException { - return raf.readLong(); - } + public long readLong() throws IOException { + return raf.readLong(); + } - public short readShort() throws IOException { - return raf.readShort(); - } + public short readShort() throws IOException { + return raf.readShort(); + } - public String readUTF() throws IOException { - return raf.readUTF(); - } + public String readUTF() throws IOException { + return raf.readUTF(); + } - public int readUnsignedByte() throws IOException { - return raf.readUnsignedByte(); - } + public int readUnsignedByte() throws IOException { + return raf.readUnsignedByte(); + } - public int readUnsignedShort() throws IOException { - return raf.readUnsignedShort(); - } + public int readUnsignedShort() throws IOException { + return raf.readUnsignedShort(); + } - public void seek(long pos) throws IOException { - raf.seek(pos); - } + public void seek(long pos) throws IOException { + raf.seek(pos); + } - public void setLength(long newLength) throws IOException { - raf.setLength(newLength); - } + public void setLength(long newLength) throws IOException { + raf.setLength(newLength); + } - public int skipBytes(int n) throws IOException { - return raf.skipBytes(n); - } + public int skipBytes(int n) throws IOException { + return raf.skipBytes(n); + } - public void write(int b) throws IOException { - raf.write(b); + public void write(int b) throws IOException { + raf.write(b); - } + } - public void write(byte[] b) throws IOException { - raf.write(b); - } + public void write(byte[] b) throws IOException { + raf.write(b); + } - public void write(byte[] b, int off, int len) throws IOException { - raf.write(b, off, len); - } + public void write(byte[] b, int off, int len) throws IOException { + raf.write(b, off, len); + } - public void writeBoolean(boolean v) throws IOException { - raf.writeBoolean(v); - } + public void writeBoolean(boolean v) throws IOException { + raf.writeBoolean(v); + } - public void writeByte(int v) throws IOException { - raf.writeByte(v); - } + public void writeByte(int v) throws IOException { + raf.writeByte(v); + } - public void writeBytes(String s) throws IOException { - raf.writeBytes(s); - } + public void writeBytes(String s) throws IOException { + raf.writeBytes(s); + } - public void writeChar(int v) throws IOException { - raf.writeChar(v); - } + public void writeChar(int v) throws IOException { + raf.writeChar(v); + } - public void writeChars(String s) throws IOException { - raf.writeChars(s); - } + public void writeChars(String s) throws IOException { + raf.writeChars(s); + } - public void writeDouble(double v) throws IOException { - raf.writeDouble(v); - } + public void writeDouble(double v) throws IOException { + raf.writeDouble(v); + } - public void writeFloat(float v) throws IOException { - raf.writeFloat(v); - } + public void writeFloat(float v) throws IOException { + raf.writeFloat(v); + } - public void writeInt(int v) throws IOException { - raf.writeInt(v); - } + public void writeInt(int v) throws IOException { + raf.writeInt(v); + } - public void writeLong(long v) throws IOException { - raf.writeLong(v); - } + public void writeLong(long v) throws IOException { + raf.writeLong(v); + } - public void writeShort(int v) throws IOException { - raf.writeShort(v); - } + public void writeShort(int v) throws IOException { + raf.writeShort(v); + } - public void writeUTF(String str) throws IOException { - raf.writeUTF(str); - } + public void writeUTF(String str) throws IOException { + raf.writeUTF(str); + } } diff --git a/netx/net/sourceforge/jnlp/services/XPersistenceService.java b/netx/net/sourceforge/jnlp/services/XPersistenceService.java index b409f82..5388438 100644 --- a/netx/net/sourceforge/jnlp/services/XPersistenceService.java +++ b/netx/net/sourceforge/jnlp/services/XPersistenceService.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.services; import java.io.*; @@ -67,8 +66,8 @@ class XPersistenceService implements PersistenceService { requestPath = ""; if (JNLPRuntime.isDebug()) { - System.out.println("codebase path: "+source.getFile()); - System.out.println("request path: "+requestPath); + System.out.println("codebase path: " + source.getFile()); + System.out.println("request path: " + requestPath); } if (!source.getFile().startsWith(requestPath)) @@ -82,7 +81,7 @@ class XPersistenceService implements PersistenceService { */ protected File toCacheFile(URL location) throws MalformedURLException { String pcache = JNLPRuntime.getConfiguration() - .getProperty(DeploymentConfiguration.KEY_USER_PERSISTENCE_CACHE_DIR); + .getProperty(DeploymentConfiguration.KEY_USER_PERSISTENCE_CACHE_DIR); return CacheUtil.urlToPath(location, pcache); } @@ -125,7 +124,7 @@ class XPersistenceService implements PersistenceService { File file = toCacheFile(location); if (!file.exists()) throw new FileNotFoundException("Persistence store for " - + location.toString() + " is not found."); + + location.toString() + " is not found."); file.getParentFile().mkdirs(); return (FileContents) ServiceUtil.createPrivilegedProxy(FileContents.class, new XFileContents(file)); @@ -138,7 +137,6 @@ class XPersistenceService implements PersistenceService { public String[] getNames(URL location) throws MalformedURLException, IOException { checkLocation(location); - File file = toCacheFile(location); if (!file.isDirectory()) return new String[0]; @@ -147,7 +145,7 @@ class XPersistenceService implements PersistenceService { // check whether this is right: only add files and not directories. File entries[] = file.listFiles(); - for (int i=0; i < entries.length; i++) + for (int i = 0; i < entries.length; i++) if (entries[i].isFile()) result.add(entries[i].getName()); diff --git a/netx/net/sourceforge/jnlp/services/XPrintService.java b/netx/net/sourceforge/jnlp/services/XPrintService.java index f2f75dd..ddbeb98 100644 --- a/netx/net/sourceforge/jnlp/services/XPrintService.java +++ b/netx/net/sourceforge/jnlp/services/XPrintService.java @@ -50,74 +50,74 @@ import net.sourceforge.jnlp.runtime.JNLPRuntime; public class XPrintService implements PrintService { - // If pj is null, then we do not have a printer to use. - private PrinterJob pj; - - public XPrintService() { - pj = PrinterJob.getPrinterJob(); + // If pj is null, then we do not have a printer to use. + private PrinterJob pj; + + public XPrintService() { + pj = PrinterJob.getPrinterJob(); + } + + public PageFormat getDefaultPage() { + if (pj != null) + return pj.defaultPage(); + else { + showWarning(); + return new PageFormat(); // might not have default settings. } - - public PageFormat getDefaultPage() { - if (pj != null) - return pj.defaultPage(); - else { - showWarning(); - return new PageFormat(); // might not have default settings. - } + } + + public PageFormat showPageFormatDialog(PageFormat page) { + if (pj != null) + return pj.pageDialog(page); + else { + showWarning(); + return page; } - public PageFormat showPageFormatDialog(PageFormat page) { - if (pj != null) - return pj.pageDialog(page); - else { - showWarning(); - return page; + } + + public boolean print(Pageable document) { + if (pj != null) { + pj.setPageable(document); + if (pj.printDialog()) { + try { + pj.print(); + return true; + } catch (PrinterException pe) { + System.err.println("Could not print: " + pe); + return false; + } + } + } else + showWarning(); + + return false; + } + + public boolean print(Printable painter) { + if (pj != null) { + pj.setPrintable(painter); + if (pj.printDialog()) { + try { + pj.print(); + return true; + } catch (PrinterException pe) { + System.err.println("Could not print: " + pe); + return false; } - } - - public boolean print(Pageable document) { - if (pj != null) { - pj.setPageable(document); - if (pj.printDialog()) { - try { - pj.print(); - return true; - } catch(PrinterException pe) { - System.err.println("Could not print: " + pe); - return false; - } - } - } else - showWarning(); - - return false; - } + } + } else + showWarning(); - public boolean print(Printable painter) { - if (pj != null) { - pj.setPrintable(painter); - if (pj.printDialog()) { - try { - pj.print(); - return true; - } catch(PrinterException pe) { - System.err.println("Could not print: " + pe); - return false; - } - - } - } else - showWarning(); - - return false; - } + return false; + } - private void showWarning() { - JOptionPane.showMessageDialog(null, + private void showWarning() { + JOptionPane.showMessageDialog(null, "Unable to find a default printer.", "Warning", JOptionPane.WARNING_MESSAGE); - System.err.println("Unable to print: Unable to find default printer."); - } + System.err.println("Unable to print: Unable to find default printer."); + } } diff --git a/netx/net/sourceforge/jnlp/services/XServiceManagerStub.java b/netx/net/sourceforge/jnlp/services/XServiceManagerStub.java index 756b412..325ec73 100644 --- a/netx/net/sourceforge/jnlp/services/XServiceManagerStub.java +++ b/netx/net/sourceforge/jnlp/services/XServiceManagerStub.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.services; import java.io.*; @@ -42,33 +41,32 @@ public class XServiceManagerStub implements ServiceManagerStub { // run less code in the secure environment (or avoid privileged // actions by giving permission to the code source). - private static String serviceNames[] = { - "javax.jnlp.BasicService", // required - "javax.jnlp.DownloadService", // required - "javax.jnlp.ExtendedService", - "javax.jnlp.ExtensionInstallerService", // required - "javax.jnlp.PersistenceService", - "javax.jnlp.FileOpenService", - "javax.jnlp.FileSaveService", - "javax.jnlp.ClipboardService", - "javax.jnlp.PrintService", - "javax.jnlp.SingleInstanceService" + private static String serviceNames[] = { + "javax.jnlp.BasicService", // required + "javax.jnlp.DownloadService", // required + "javax.jnlp.ExtendedService", + "javax.jnlp.ExtensionInstallerService", // required + "javax.jnlp.PersistenceService", + "javax.jnlp.FileOpenService", + "javax.jnlp.FileSaveService", + "javax.jnlp.ClipboardService", + "javax.jnlp.PrintService", + "javax.jnlp.SingleInstanceService" }; private static Object services[] = { - ServiceUtil.createPrivilegedProxy(BasicService.class, new XBasicService()), - ServiceUtil.createPrivilegedProxy(DownloadService.class, new XDownloadService()), - ServiceUtil.createPrivilegedProxy(ExtendedService.class, new XExtendedService()), - ServiceUtil.createPrivilegedProxy(ExtensionInstallerService.class, new XExtensionInstallerService()), - ServiceUtil.createPrivilegedProxy(PersistenceService.class, new XPersistenceService()), - ServiceUtil.createPrivilegedProxy(FileOpenService.class, new XFileOpenService()), - ServiceUtil.createPrivilegedProxy(FileSaveService.class, new XFileSaveService()), - ServiceUtil.createPrivilegedProxy(ClipboardService.class, new XClipboardService()), - ServiceUtil.createPrivilegedProxy(PrintService.class, new XPrintService()), - ServiceUtil.createPrivilegedProxy(ExtendedSingleInstanceService.class, new XSingleInstanceService()) + ServiceUtil.createPrivilegedProxy(BasicService.class, new XBasicService()), + ServiceUtil.createPrivilegedProxy(DownloadService.class, new XDownloadService()), + ServiceUtil.createPrivilegedProxy(ExtendedService.class, new XExtendedService()), + ServiceUtil.createPrivilegedProxy(ExtensionInstallerService.class, new XExtensionInstallerService()), + ServiceUtil.createPrivilegedProxy(PersistenceService.class, new XPersistenceService()), + ServiceUtil.createPrivilegedProxy(FileOpenService.class, new XFileOpenService()), + ServiceUtil.createPrivilegedProxy(FileSaveService.class, new XFileSaveService()), + ServiceUtil.createPrivilegedProxy(ClipboardService.class, new XClipboardService()), + ServiceUtil.createPrivilegedProxy(PrintService.class, new XPrintService()), + ServiceUtil.createPrivilegedProxy(ExtendedSingleInstanceService.class, new XSingleInstanceService()) }; - public XServiceManagerStub() { } @@ -91,16 +89,16 @@ public class XServiceManagerStub implements ServiceManagerStub { */ public Object lookup(String name) throws UnavailableServiceException { // exact match - for (int i=0; i < serviceNames.length; i++) + for (int i = 0; i < serviceNames.length; i++) if (serviceNames[i].equals(name)) return services[i]; // substring match - for (int i=0; i < serviceNames.length; i++) + for (int i = 0; i < serviceNames.length; i++) if (-1 != serviceNames[i].indexOf(name)) return services[i]; - throw new UnavailableServiceException(""+name); + throw new UnavailableServiceException("" + name); } } diff --git a/netx/net/sourceforge/jnlp/tools/CharacterEncoder.java b/netx/net/sourceforge/jnlp/tools/CharacterEncoder.java index 2d8af4f..7913114 100644 --- a/netx/net/sourceforge/jnlp/tools/CharacterEncoder.java +++ b/netx/net/sourceforge/jnlp/tools/CharacterEncoder.java @@ -33,7 +33,6 @@ import java.io.PrintStream; import java.io.IOException; import java.nio.ByteBuffer; - /** * This class defines the encoding half of character encoders. * A character encoder is an algorithim for transforming 8 bit binary @@ -102,7 +101,7 @@ public abstract class CharacterEncoder { * Encode the prefix that starts every output line. */ protected void encodeLinePrefix(OutputStream aStream, int aLength) - throws IOException { + throws IOException { } /** @@ -122,12 +121,12 @@ public abstract class CharacterEncoder { * read method. */ protected int readFully(InputStream in, byte buffer[]) - throws java.io.IOException { + throws java.io.IOException { for (int i = 0; i < buffer.length; i++) { int q = in.read(); if (q == -1) return i; - buffer[i] = (byte)q; + buffer[i] = (byte) q; } return buffer.length; } @@ -139,10 +138,10 @@ public abstract class CharacterEncoder { * line that is shorter than bytesPerLine(). */ public void encode(InputStream inStream, OutputStream outStream) - throws IOException { - int j; - int numBytes; - byte tmpbuffer[] = new byte[bytesPerLine()]; + throws IOException { + int j; + int numBytes; + byte tmpbuffer[] = new byte[bytesPerLine()]; encodeBufferPrefix(outStream); @@ -157,7 +156,7 @@ public abstract class CharacterEncoder { if ((j + bytesPerAtom()) <= numBytes) { encodeAtom(outStream, tmpbuffer, j, bytesPerAtom()); } else { - encodeAtom(outStream, tmpbuffer, j, (numBytes)- j); + encodeAtom(outStream, tmpbuffer, j, (numBytes) - j); } } if (numBytes < bytesPerLine()) { @@ -174,7 +173,7 @@ public abstract class CharacterEncoder { * result to the OutputStream <i>aStream</i>. */ public void encode(byte aBuffer[], OutputStream aStream) - throws IOException { + throws IOException { ByteArrayInputStream inStream = new ByteArrayInputStream(aBuffer); encode(inStream, aStream); } @@ -184,8 +183,8 @@ public abstract class CharacterEncoder { * bytes and returns a string containing the encoded buffer. */ public String encode(byte aBuffer[]) { - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - ByteArrayInputStream inStream = new ByteArrayInputStream(aBuffer); + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + ByteArrayInputStream inStream = new ByteArrayInputStream(aBuffer); String retVal = null; try { encode(inStream, outStream); @@ -207,19 +206,19 @@ public abstract class CharacterEncoder { * byte array backing the ByteBuffer. If this is not possible, a * new byte array will be created. */ - private byte [] getBytes(ByteBuffer bb) { + private byte[] getBytes(ByteBuffer bb) { /* * This should never return a BufferOverflowException, as we're * careful to allocate just the right amount. */ - byte [] buf = null; + byte[] buf = null; /* * If it has a usable backing byte buffer, use it. Use only * if the array exactly represents the current ByteBuffer. */ if (bb.hasArray()) { - byte [] tmp = bb.array(); + byte[] tmp = bb.array(); if ((tmp.length == bb.capacity()) && (tmp.length == bb.remaining())) { buf = tmp; @@ -251,8 +250,8 @@ public abstract class CharacterEncoder { * The ByteBuffer's position will be advanced to ByteBuffer's limit. */ public void encode(ByteBuffer aBuffer, OutputStream aStream) - throws IOException { - byte [] buf = getBytes(aBuffer); + throws IOException { + byte[] buf = getBytes(aBuffer); encode(buf, aStream); } @@ -263,7 +262,7 @@ public abstract class CharacterEncoder { * The ByteBuffer's position will be advanced to ByteBuffer's limit. */ public String encode(ByteBuffer aBuffer) { - byte [] buf = getBytes(aBuffer); + byte[] buf = getBytes(aBuffer); return encode(buf); } @@ -274,10 +273,10 @@ public abstract class CharacterEncoder { * line at the end of a final line that is shorter than bytesPerLine(). */ public void encodeBuffer(InputStream inStream, OutputStream outStream) - throws IOException { - int j; - int numBytes; - byte tmpbuffer[] = new byte[bytesPerLine()]; + throws IOException { + int j; + int numBytes; + byte tmpbuffer[] = new byte[bytesPerLine()]; encodeBufferPrefix(outStream); @@ -291,7 +290,7 @@ public abstract class CharacterEncoder { if ((j + bytesPerAtom()) <= numBytes) { encodeAtom(outStream, tmpbuffer, j, bytesPerAtom()); } else { - encodeAtom(outStream, tmpbuffer, j, (numBytes)- j); + encodeAtom(outStream, tmpbuffer, j, (numBytes) - j); } } encodeLineSuffix(outStream); @@ -307,7 +306,7 @@ public abstract class CharacterEncoder { * result to the OutputStream <i>aStream</i>. */ public void encodeBuffer(byte aBuffer[], OutputStream aStream) - throws IOException { + throws IOException { ByteArrayInputStream inStream = new ByteArrayInputStream(aBuffer); encodeBuffer(inStream, aStream); } @@ -317,8 +316,8 @@ public abstract class CharacterEncoder { * bytes and returns a string containing the encoded buffer. */ public String encodeBuffer(byte aBuffer[]) { - ByteArrayOutputStream outStream = new ByteArrayOutputStream(); - ByteArrayInputStream inStream = new ByteArrayInputStream(aBuffer); + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + ByteArrayInputStream inStream = new ByteArrayInputStream(aBuffer); try { encodeBuffer(inStream, outStream); } catch (Exception IOException) { @@ -335,8 +334,8 @@ public abstract class CharacterEncoder { * The ByteBuffer's position will be advanced to ByteBuffer's limit. */ public void encodeBuffer(ByteBuffer aBuffer, OutputStream aStream) - throws IOException { - byte [] buf = getBytes(aBuffer); + throws IOException { + byte[] buf = getBytes(aBuffer); encodeBuffer(buf, aStream); } @@ -347,7 +346,7 @@ public abstract class CharacterEncoder { * The ByteBuffer's position will be advanced to ByteBuffer's limit. */ public String encodeBuffer(ByteBuffer aBuffer) { - byte [] buf = getBytes(aBuffer); + byte[] buf = getBytes(aBuffer); return encodeBuffer(buf); } diff --git a/netx/net/sourceforge/jnlp/tools/HexDumpEncoder.java b/netx/net/sourceforge/jnlp/tools/HexDumpEncoder.java index 4f7c27f..7b6b242 100644 --- a/netx/net/sourceforge/jnlp/tools/HexDumpEncoder.java +++ b/netx/net/sourceforge/jnlp/tools/HexDumpEncoder.java @@ -55,15 +55,15 @@ public class HexDumpEncoder extends CharacterEncoder { c = (char) ((x >> 4) & 0xf); if (c > 9) - c = (char) ((c-10) + 'A'); + c = (char) ((c - 10) + 'A'); else - c = (char)(c + '0'); + c = (char) (c + '0'); p.write(c); c = (char) (x & 0xf); if (c > 9) - c = (char)((c-10) + 'A'); + c = (char) ((c - 10) + 'A'); else - c = (char)(c + '0'); + c = (char) (c + '0'); p.write(c); } @@ -81,8 +81,8 @@ public class HexDumpEncoder extends CharacterEncoder { } protected void encodeLinePrefix(OutputStream o, int len) throws IOException { - hexDigit(pStream, (byte)((offset >>> 8) & 0xff)); - hexDigit(pStream, (byte)(offset & 0xff)); + hexDigit(pStream, (byte) ((offset >>> 8) & 0xff)); + hexDigit(pStream, (byte) (offset & 0xff)); pStream.print(": "); currentByte = 0; thisLineLength = len; diff --git a/netx/net/sourceforge/jnlp/tools/JarRunner.java b/netx/net/sourceforge/jnlp/tools/JarRunner.java index 52e86da..33c056f 100644 --- a/netx/net/sourceforge/jnlp/tools/JarRunner.java +++ b/netx/net/sourceforge/jnlp/tools/JarRunner.java @@ -1,15 +1,14 @@ package net.sourceforge.jnlp.tools; import net.sourceforge.jnlp.tools.JarSigner; -public class JarRunner { - - public static void main(String[] args) throws Exception{ +public class JarRunner { + public static void main(String[] args) throws Exception { - //JarSigner.main(args); - JarSigner js = new JarSigner(); - js.verifyJar(args[0]); - } + //JarSigner.main(args); + JarSigner js = new JarSigner(); + js.verifyJar(args[0]); + } } diff --git a/netx/net/sourceforge/jnlp/tools/JarSigner.java b/netx/net/sourceforge/jnlp/tools/JarSigner.java index da7cf13..0630702 100644 --- a/netx/net/sourceforge/jnlp/tools/JarSigner.java +++ b/netx/net/sourceforge/jnlp/tools/JarSigner.java @@ -64,15 +64,16 @@ public class JarSigner implements CertVerifier { // prefix for new signature-related files in META-INF directory private static final String SIG_PREFIX = META_INF + "SIG-"; - - private static final long SIX_MONTHS = 180*24*60*60*1000L; //milliseconds + private static final long SIX_MONTHS = 180 * 24 * 60 * 60 * 1000L; //milliseconds static final String VERSION = "1.0"; static final int IN_KEYSTORE = 0x01; static final int IN_SCOPE = 0x02; - static enum verifyResult {UNSIGNED, SIGNED_OK, SIGNED_NOT_OK} + static enum verifyResult { + UNSIGNED, SIGNED_OK, SIGNED_NOT_OK + } // signer's certificate chain (when composing) X509Certificate[] certChain; @@ -86,14 +87,14 @@ public class JarSigner implements CertVerifier { String keystore; // key store file boolean nullStream = false; // null keystore input stream (NONE) boolean token = false; // token-based keystore - String jarfile; // jar file to sign - String alias; // alias to sign jar with + String jarfile; // jar file to sign + String alias; // alias to sign jar with char[] storepass; // keystore password boolean protectedPath; // protected authentication path String storetype; // keystore type String providerName; // provider name Vector<String> providers = null; // list of providers - HashMap<String,String> providerArgs = new HashMap<String, String>(); // arguments for provider constructors + HashMap<String, String> providerArgs = new HashMap<String, String>(); // arguments for provider constructors char[] keypass; // private key password String sigfile; // name of .SF file String sigalg; // name of signature algorithm @@ -165,7 +166,7 @@ public class JarSigner implements CertVerifier { */ public boolean hasSigningIssues() { return hasExpiredCert || notYetValidCert || badKeyUsage - || badExtendedKeyUsage || badNetscapeCertType; + || badExtendedKeyUsage || badNetscapeCertType; } /* (non-Javadoc) @@ -194,7 +195,7 @@ public class JarSigner implements CertVerifier { } public void verifyJars(List<JARDesc> jars, ResourceTracker tracker) - throws Exception { + throws Exception { certs = new ArrayList<CertPath>(); for (int i = 0; i < jars.size(); i++) { @@ -224,7 +225,7 @@ public class JarSigner implements CertVerifier { } else if (result == verifyResult.SIGNED_OK) { verifiedJars.add(localFile); } - } catch (Exception e){ + } catch (Exception e) { // We may catch exceptions from using verifyJar() // or from checkTrustedCerts throw e; @@ -267,7 +268,8 @@ public class JarSigner implements CertVerifier { } if (jarFile.getManifest() != null) { - if (verbose) System.out.println(); + if (verbose) + System.out.println(); Enumeration<JarEntry> e = entriesVec.elements(); long now = System.currentTimeMillis(); @@ -290,16 +292,16 @@ public class JarSigner implements CertVerifier { certs.add(certPath); //we really only want the first certPath - if (!certPath.equals(this.certPath)){ + if (!certPath.equals(this.certPath)) { this.certPath = certPath; } Certificate cert = signers[i].getSignerCertPath() - .getCertificates().get(0); + .getCertificates().get(0); if (cert instanceof X509Certificate) { - checkCertUsage((X509Certificate)cert, null); + checkCertUsage((X509Certificate) cert, null); if (!showcerts) { - long notAfter = ((X509Certificate)cert) + long notAfter = ((X509Certificate) cert) .getNotAfter().getTime(); if (notAfter < now) { @@ -358,8 +360,7 @@ public class JarSigner implements CertVerifier { //anySigned does not guarantee that all files were signed. return (anySigned && !(hasUnsignedEntry || hasExpiredCert - || badKeyUsage || badExtendedKeyUsage || badNetscapeCertType - || notYetValidCert)) ? verifyResult.SIGNED_OK : verifyResult.SIGNED_NOT_OK; + || badKeyUsage || badExtendedKeyUsage || badNetscapeCertType || notYetValidCert)) ? verifyResult.SIGNED_OK : verifyResult.SIGNED_NOT_OK; } /** @@ -368,24 +369,24 @@ public class JarSigner implements CertVerifier { */ private void checkTrustedCerts() throws Exception { if (certPath != null) { - try { - X509Certificate publisher = (X509Certificate) getPublisher(); - KeyStore[] certKeyStores = KeyStores.getCertKeyStores(); - alreadyTrustPublisher = CertificateUtils.inKeyStores(publisher, certKeyStores); - X509Certificate root = (X509Certificate) getRoot(); - KeyStore[] caKeyStores = KeyStores.getCAKeyStores(); - rootInCacerts = CertificateUtils.inKeyStores(root, caKeyStores); - } catch (Exception e) { - // TODO: Warn user about not being able to - // look through their cacerts/trusted.certs - // file depending on exception. - throw e; - } + try { + X509Certificate publisher = (X509Certificate) getPublisher(); + KeyStore[] certKeyStores = KeyStores.getCertKeyStores(); + alreadyTrustPublisher = CertificateUtils.inKeyStores(publisher, certKeyStores); + X509Certificate root = (X509Certificate) getRoot(); + KeyStore[] caKeyStores = KeyStores.getCAKeyStores(); + rootInCacerts = CertificateUtils.inKeyStores(root, caKeyStores); + } catch (Exception e) { + // TODO: Warn user about not being able to + // look through their cacerts/trusted.certs + // file depending on exception. + throw e; + } - if (!rootInCacerts) - addToDetails(R("SUntrustedCertificate")); - else - addToDetails(R("STrustedCertificate")); + if (!rootInCacerts) + addToDetails(R("SUntrustedCertificate")); + else + addToDetails(R("STrustedCertificate")); } } @@ -394,15 +395,14 @@ public class JarSigner implements CertVerifier { */ public Certificate getPublisher() { if (certPath != null) { - List<? extends Certificate> certList - = certPath.getCertificates(); - if (certList.size() > 0) { - return (Certificate)certList.get(0); - } else { - return null; - } - } else { + List<? extends Certificate> certList = certPath.getCertificates(); + if (certList.size() > 0) { + return (Certificate) certList.get(0); + } else { return null; + } + } else { + return null; } } @@ -411,26 +411,25 @@ public class JarSigner implements CertVerifier { */ public Certificate getRoot() { if (certPath != null) { - List<? extends Certificate> certList - = certPath.getCertificates(); - if (certList.size() > 0) { - return (Certificate)certList.get( + List<? extends Certificate> certList = certPath.getCertificates(); + if (certList.size() > 0) { + return (Certificate) certList.get( certList.size() - 1); - } else { - return null; - } - } else { + } else { return null; + } + } else { + return null; } } - private void addToDetails(String detail) { - if (!details.contains(detail)) - details.add(detail); - } + private void addToDetails(String detail) { + if (!details.contains(detail)) + details.add(detail); + } Hashtable<Certificate, String> storeHash = - new Hashtable<Certificate, String>(); + new Hashtable<Certificate, String>(); /** * signature-related files include: @@ -498,7 +497,7 @@ public class JarSigner implements CertVerifier { List<String> xKeyUsage = userCert.getExtendedKeyUsage(); if (xKeyUsage != null) { if (!xKeyUsage.contains("2.5.29.37.0") // anyExtendedKeyUsage - && !xKeyUsage.contains("1.3.6.1.5.5.7.3.3")) { // codeSigning + && !xKeyUsage.contains("1.3.6.1.5.5.7.3.3")) { // codeSigning if (bad != null) { bad[1] = true; } else { @@ -518,12 +517,12 @@ public class JarSigner implements CertVerifier { DerInputStream in = new DerInputStream(netscapeEx); byte[] encoded = in.getOctetString(); encoded = new DerValue(encoded).getUnalignedBitString() - .toByteArray(); + .toByteArray(); NetscapeCertTypeExtension extn = - new NetscapeCertTypeExtension(encoded); + new NetscapeCertTypeExtension(encoded); - Boolean val = (Boolean)extn.get( + Boolean val = (Boolean) extn.get( NetscapeCertTypeExtension.OBJECT_SIGNING); if (!val) { if (bad != null) { @@ -538,14 +537,13 @@ public class JarSigner implements CertVerifier { } } - /** * Returns if all jars are signed. * * @return True if all jars are signed, false if there are one or more unsigned jars */ public boolean allJarsSigned() { - return this.unverifiedJars.size() == 0; + return this.unverifiedJars.size() == 0; } } diff --git a/netx/net/sourceforge/jnlp/tools/JarSignerResources.java b/netx/net/sourceforge/jnlp/tools/JarSignerResources.java index 50655ab..7d02b66 100644 --- a/netx/net/sourceforge/jnlp/tools/JarSignerResources.java +++ b/netx/net/sourceforge/jnlp/tools/JarSignerResources.java @@ -34,169 +34,169 @@ public class JarSignerResources extends java.util.ListResourceBundle { private static final Object[][] contents = { - // shared (from jarsigner) - {" ", " "}, - {" ", " "}, - {" ", " "}, - {", ", ", "}, + // shared (from jarsigner) + { " ", " " }, + { " ", " " }, + { " ", " " }, + { ", ", ", " }, - {"provName not a provider", "{0} not a provider"}, - {"signerClass is not a signing mechanism", "{0} is not a signing mechanism"}, - {"jarsigner error: ", "jarsigner error: "}, - {"Illegal option: ", "Illegal option: "}, - {"-keystore must be NONE if -storetype is {0}", - "-keystore must be NONE if -storetype is {0}"}, - {"-keypass can not be specified if -storetype is {0}", - "-keypass can not be specified if -storetype is {0}"}, - {"If -protected is specified, then -storepass and -keypass must not be specified", - "If -protected is specified, then -storepass and -keypass must not be specified"}, - {"If keystore is not password protected, then -storepass and -keypass must not be specified", - "If keystore is not password protected, then -storepass and -keypass must not be specified"}, - {"Usage: jarsigner [options] jar-file alias", - "Usage: jarsigner [options] jar-file alias"}, - {" jarsigner -verify [options] jar-file", - " jarsigner -verify [options] jar-file"}, - {"[-keystore <url>] keystore location", - "[-keystore <url>] keystore location"}, - {"[-storepass <password>] password for keystore integrity", - "[-storepass <password>] password for keystore integrity"}, - {"[-storetype <type>] keystore type", - "[-storetype <type>] keystore type"}, - {"[-keypass <password>] password for private key (if different)", - "[-keypass <password>] password for private key (if different)"}, - {"[-sigfile <file>] name of .SF/.DSA file", - "[-sigfile <file>] name of .SF/.DSA file"}, - {"[-signedjar <file>] name of signed JAR file", - "[-signedjar <file>] name of signed JAR file"}, - {"[-digestalg <algorithm>] name of digest algorithm", - "[-digestalg <algorithm>] name of digest algorithm"}, - {"[-sigalg <algorithm>] name of signature algorithm", - "[-sigalg <algorithm>] name of signature algorithm"}, - {"[-verify] verify a signed JAR file", - "[-verify] verify a signed JAR file"}, - {"[-verbose] verbose output when signing/verifying", - "[-verbose] verbose output when signing/verifying"}, - {"[-certs] display certificates when verbose and verifying", - "[-certs] display certificates when verbose and verifying"}, - {"[-tsa <url>] location of the Timestamping Authority", - "[-tsa <url>] location of the Timestamping Authority"}, - {"[-tsacert <alias>] public key certificate for Timestamping Authority", - "[-tsacert <alias>] public key certificate for Timestamping Authority"}, - {"[-altsigner <class>] class name of an alternative signing mechanism", - "[-altsigner <class>] class name of an alternative signing mechanism"}, - {"[-altsignerpath <pathlist>] location of an alternative signing mechanism", - "[-altsignerpath <pathlist>] location of an alternative signing mechanism"}, - {"[-internalsf] include the .SF file inside the signature block", - "[-internalsf] include the .SF file inside the signature block"}, - {"[-sectionsonly] don't compute hash of entire manifest", - "[-sectionsonly] don't compute hash of entire manifest"}, - {"[-protected] keystore has protected authentication path", - "[-protected] keystore has protected authentication path"}, - {"[-providerName <name>] provider name", - "[-providerName <name>] provider name"}, - {"[-providerClass <class> name of cryptographic service provider's", - "[-providerClass <class> name of cryptographic service provider's"}, - {" [-providerArg <arg>]] ... master class file and constructor argument", - " [-providerArg <arg>]] ... master class file and constructor argument"}, - {"s", "s"}, - {"m", "m"}, - {"k", "k"}, - {"i", "i"}, - {" s = signature was verified ", - " s = signature was verified "}, - {" m = entry is listed in manifest", - " m = entry is listed in manifest"}, - {" k = at least one certificate was found in keystore", - " k = at least one certificate was found in keystore"}, - {" i = at least one certificate was found in identity scope", - " i = at least one certificate was found in identity scope"}, - {"no manifest.", "no manifest."}, - {"jar is unsigned. (signatures missing or not parsable)", - "jar is unsigned. (signatures missing or not parsable)"}, - {"jar verified.", "jar verified."}, - {"jarsigner: ", "jarsigner: "}, - {"signature filename must consist of the following characters: A-Z, 0-9, _ or -", - "signature filename must consist of the following characters: A-Z, 0-9, _ or -"}, - {"unable to open jar file: ", "unable to open jar file: "}, - {"unable to create: ", "unable to create: "}, - {" adding: ", " adding: "}, - {" updating: ", " updating: "}, - {" signing: ", " signing: "}, - {"attempt to rename signedJarFile to jarFile failed", - "attempt to rename {0} to {1} failed"}, - {"attempt to rename jarFile to origJar failed", - "attempt to rename {0} to {1} failed"}, - {"unable to sign jar: ", "unable to sign jar: "}, - {"Enter Passphrase for keystore: ", "Enter Passphrase for keystore: "}, - {"keystore load: ", "keystore load: "}, - {"certificate exception: ", "certificate exception: "}, - {"unable to instantiate keystore class: ", - "unable to instantiate keystore class: "}, - {"Certificate chain not found for: alias. alias must reference a valid KeyStore key entry containing a private key and corresponding public key certificate chain.", - "Certificate chain not found for: {0}. {1} must reference a valid KeyStore key entry containing a private key and corresponding public key certificate chain."}, - {"found non-X.509 certificate in signer's chain", - "found non-X.509 certificate in signer's chain"}, - {"incomplete certificate chain", "incomplete certificate chain"}, - {"Enter key password for alias: ", "Enter key password for {0}: "}, - {"unable to recover key from keystore", - "unable to recover key from keystore"}, - {"key associated with alias not a private key", - "key associated with {0} not a private key"}, - {"you must enter key password", "you must enter key password"}, - {"unable to read password: ", "unable to read password: "}, - {"certificate is valid from", "certificate is valid from {0} to {1}"}, - {"certificate expired on", "certificate expired on {0}"}, - {"certificate is not valid until", - "certificate is not valid until {0}"}, - {"certificate will expire on", "certificate will expire on {0}"}, - {"requesting a signature timestamp", - "requesting a signature timestamp"}, - {"TSA location: ", "TSA location: "}, - {"TSA certificate: ", "TSA certificate: "}, - {"no response from the Timestamping Authority. ", - "no response from the Timestamping Authority. "}, - {"When connecting from behind a firewall then an HTTP proxy may need to be specified. ", - "When connecting from behind a firewall then an HTTP proxy may need to be specified. "}, - {"Supply the following options to jarsigner: ", - "Supply the following options to jarsigner: "}, - {"Certificate not found for: alias. alias must reference a valid KeyStore entry containing an X.509 public key certificate for the Timestamping Authority.", - "Certificate not found for: {0}. {1} must reference a valid KeyStore entry containing an X.509 public key certificate for the Timestamping Authority."}, - {"using an alternative signing mechanism", - "using an alternative signing mechanism"}, - {"entry was signed on", "entry was signed on {0}"}, - {"Warning: ", "Warning: "}, - {"This jar contains unsigned entries which have not been integrity-checked. ", - "This jar contains unsigned entries which have not been integrity-checked. "}, - {"This jar contains entries whose signer certificate has expired. ", - "This jar contains entries whose signer certificate has expired. "}, - {"This jar contains entries whose signer certificate will expire within six months. ", - "This jar contains entries whose signer certificate will expire within six months. "}, - {"This jar contains entries whose signer certificate is not yet valid. ", - "This jar contains entries whose signer certificate is not yet valid. "}, - {"Re-run with the -verbose option for more details.", - "Re-run with the -verbose option for more details."}, - {"Re-run with the -verbose and -certs options for more details.", - "Re-run with the -verbose and -certs options for more details."}, - {"The signer certificate has expired.", - "The signer certificate has expired."}, - {"The signer certificate will expire within six months.", - "The signer certificate will expire within six months."}, - {"The signer certificate is not yet valid.", - "The signer certificate is not yet valid."}, - {"The signer certificate's KeyUsage extension doesn't allow code signing.", - "The signer certificate's KeyUsage extension doesn't allow code signing."}, - {"The signer certificate's ExtendedKeyUsage extension doesn't allow code signing.", - "The signer certificate's ExtendedKeyUsage extension doesn't allow code signing."}, - {"The signer certificate's NetscapeCertType extension doesn't allow code signing.", - "The signer certificate's NetscapeCertType extension doesn't allow code signing."}, - {"This jar contains entries whose signer certificate's KeyUsage extension doesn't allow code signing.", - "This jar contains entries whose signer certificate's KeyUsage extension doesn't allow code signing."}, - {"This jar contains entries whose signer certificate's ExtendedKeyUsage extension doesn't allow code signing.", - "This jar contains entries whose signer certificate's ExtendedKeyUsage extension doesn't allow code signing."}, - {"This jar contains entries whose signer certificate's NetscapeCertType extension doesn't allow code signing.", - "This jar contains entries whose signer certificate's NetscapeCertType extension doesn't allow code signing."}, - {"[{0} extension does not support code signing]", - "[{0} extension does not support code signing]"}, + { "provName not a provider", "{0} not a provider" }, + { "signerClass is not a signing mechanism", "{0} is not a signing mechanism" }, + { "jarsigner error: ", "jarsigner error: " }, + { "Illegal option: ", "Illegal option: " }, + { "-keystore must be NONE if -storetype is {0}", + "-keystore must be NONE if -storetype is {0}" }, + { "-keypass can not be specified if -storetype is {0}", + "-keypass can not be specified if -storetype is {0}" }, + { "If -protected is specified, then -storepass and -keypass must not be specified", + "If -protected is specified, then -storepass and -keypass must not be specified" }, + { "If keystore is not password protected, then -storepass and -keypass must not be specified", + "If keystore is not password protected, then -storepass and -keypass must not be specified" }, + { "Usage: jarsigner [options] jar-file alias", + "Usage: jarsigner [options] jar-file alias" }, + { " jarsigner -verify [options] jar-file", + " jarsigner -verify [options] jar-file" }, + { "[-keystore <url>] keystore location", + "[-keystore <url>] keystore location" }, + { "[-storepass <password>] password for keystore integrity", + "[-storepass <password>] password for keystore integrity" }, + { "[-storetype <type>] keystore type", + "[-storetype <type>] keystore type" }, + { "[-keypass <password>] password for private key (if different)", + "[-keypass <password>] password for private key (if different)" }, + { "[-sigfile <file>] name of .SF/.DSA file", + "[-sigfile <file>] name of .SF/.DSA file" }, + { "[-signedjar <file>] name of signed JAR file", + "[-signedjar <file>] name of signed JAR file" }, + { "[-digestalg <algorithm>] name of digest algorithm", + "[-digestalg <algorithm>] name of digest algorithm" }, + { "[-sigalg <algorithm>] name of signature algorithm", + "[-sigalg <algorithm>] name of signature algorithm" }, + { "[-verify] verify a signed JAR file", + "[-verify] verify a signed JAR file" }, + { "[-verbose] verbose output when signing/verifying", + "[-verbose] verbose output when signing/verifying" }, + { "[-certs] display certificates when verbose and verifying", + "[-certs] display certificates when verbose and verifying" }, + { "[-tsa <url>] location of the Timestamping Authority", + "[-tsa <url>] location of the Timestamping Authority" }, + { "[-tsacert <alias>] public key certificate for Timestamping Authority", + "[-tsacert <alias>] public key certificate for Timestamping Authority" }, + { "[-altsigner <class>] class name of an alternative signing mechanism", + "[-altsigner <class>] class name of an alternative signing mechanism" }, + { "[-altsignerpath <pathlist>] location of an alternative signing mechanism", + "[-altsignerpath <pathlist>] location of an alternative signing mechanism" }, + { "[-internalsf] include the .SF file inside the signature block", + "[-internalsf] include the .SF file inside the signature block" }, + { "[-sectionsonly] don't compute hash of entire manifest", + "[-sectionsonly] don't compute hash of entire manifest" }, + { "[-protected] keystore has protected authentication path", + "[-protected] keystore has protected authentication path" }, + { "[-providerName <name>] provider name", + "[-providerName <name>] provider name" }, + { "[-providerClass <class> name of cryptographic service provider's", + "[-providerClass <class> name of cryptographic service provider's" }, + { " [-providerArg <arg>]] ... master class file and constructor argument", + " [-providerArg <arg>]] ... master class file and constructor argument" }, + { "s", "s" }, + { "m", "m" }, + { "k", "k" }, + { "i", "i" }, + { " s = signature was verified ", + " s = signature was verified " }, + { " m = entry is listed in manifest", + " m = entry is listed in manifest" }, + { " k = at least one certificate was found in keystore", + " k = at least one certificate was found in keystore" }, + { " i = at least one certificate was found in identity scope", + " i = at least one certificate was found in identity scope" }, + { "no manifest.", "no manifest." }, + { "jar is unsigned. (signatures missing or not parsable)", + "jar is unsigned. (signatures missing or not parsable)" }, + { "jar verified.", "jar verified." }, + { "jarsigner: ", "jarsigner: " }, + { "signature filename must consist of the following characters: A-Z, 0-9, _ or -", + "signature filename must consist of the following characters: A-Z, 0-9, _ or -" }, + { "unable to open jar file: ", "unable to open jar file: " }, + { "unable to create: ", "unable to create: " }, + { " adding: ", " adding: " }, + { " updating: ", " updating: " }, + { " signing: ", " signing: " }, + { "attempt to rename signedJarFile to jarFile failed", + "attempt to rename {0} to {1} failed" }, + { "attempt to rename jarFile to origJar failed", + "attempt to rename {0} to {1} failed" }, + { "unable to sign jar: ", "unable to sign jar: " }, + { "Enter Passphrase for keystore: ", "Enter Passphrase for keystore: " }, + { "keystore load: ", "keystore load: " }, + { "certificate exception: ", "certificate exception: " }, + { "unable to instantiate keystore class: ", + "unable to instantiate keystore class: " }, + { "Certificate chain not found for: alias. alias must reference a valid KeyStore key entry containing a private key and corresponding public key certificate chain.", + "Certificate chain not found for: {0}. {1} must reference a valid KeyStore key entry containing a private key and corresponding public key certificate chain." }, + { "found non-X.509 certificate in signer's chain", + "found non-X.509 certificate in signer's chain" }, + { "incomplete certificate chain", "incomplete certificate chain" }, + { "Enter key password for alias: ", "Enter key password for {0}: " }, + { "unable to recover key from keystore", + "unable to recover key from keystore" }, + { "key associated with alias not a private key", + "key associated with {0} not a private key" }, + { "you must enter key password", "you must enter key password" }, + { "unable to read password: ", "unable to read password: " }, + { "certificate is valid from", "certificate is valid from {0} to {1}" }, + { "certificate expired on", "certificate expired on {0}" }, + { "certificate is not valid until", + "certificate is not valid until {0}" }, + { "certificate will expire on", "certificate will expire on {0}" }, + { "requesting a signature timestamp", + "requesting a signature timestamp" }, + { "TSA location: ", "TSA location: " }, + { "TSA certificate: ", "TSA certificate: " }, + { "no response from the Timestamping Authority. ", + "no response from the Timestamping Authority. " }, + { "When connecting from behind a firewall then an HTTP proxy may need to be specified. ", + "When connecting from behind a firewall then an HTTP proxy may need to be specified. " }, + { "Supply the following options to jarsigner: ", + "Supply the following options to jarsigner: " }, + { "Certificate not found for: alias. alias must reference a valid KeyStore entry containing an X.509 public key certificate for the Timestamping Authority.", + "Certificate not found for: {0}. {1} must reference a valid KeyStore entry containing an X.509 public key certificate for the Timestamping Authority." }, + { "using an alternative signing mechanism", + "using an alternative signing mechanism" }, + { "entry was signed on", "entry was signed on {0}" }, + { "Warning: ", "Warning: " }, + { "This jar contains unsigned entries which have not been integrity-checked. ", + "This jar contains unsigned entries which have not been integrity-checked. " }, + { "This jar contains entries whose signer certificate has expired. ", + "This jar contains entries whose signer certificate has expired. " }, + { "This jar contains entries whose signer certificate will expire within six months. ", + "This jar contains entries whose signer certificate will expire within six months. " }, + { "This jar contains entries whose signer certificate is not yet valid. ", + "This jar contains entries whose signer certificate is not yet valid. " }, + { "Re-run with the -verbose option for more details.", + "Re-run with the -verbose option for more details." }, + { "Re-run with the -verbose and -certs options for more details.", + "Re-run with the -verbose and -certs options for more details." }, + { "The signer certificate has expired.", + "The signer certificate has expired." }, + { "The signer certificate will expire within six months.", + "The signer certificate will expire within six months." }, + { "The signer certificate is not yet valid.", + "The signer certificate is not yet valid." }, + { "The signer certificate's KeyUsage extension doesn't allow code signing.", + "The signer certificate's KeyUsage extension doesn't allow code signing." }, + { "The signer certificate's ExtendedKeyUsage extension doesn't allow code signing.", + "The signer certificate's ExtendedKeyUsage extension doesn't allow code signing." }, + { "The signer certificate's NetscapeCertType extension doesn't allow code signing.", + "The signer certificate's NetscapeCertType extension doesn't allow code signing." }, + { "This jar contains entries whose signer certificate's KeyUsage extension doesn't allow code signing.", + "This jar contains entries whose signer certificate's KeyUsage extension doesn't allow code signing." }, + { "This jar contains entries whose signer certificate's ExtendedKeyUsage extension doesn't allow code signing.", + "This jar contains entries whose signer certificate's ExtendedKeyUsage extension doesn't allow code signing." }, + { "This jar contains entries whose signer certificate's NetscapeCertType extension doesn't allow code signing.", + "This jar contains entries whose signer certificate's NetscapeCertType extension doesn't allow code signing." }, + { "[{0} extension does not support code signing]", + "[{0} extension does not support code signing]" }, }; /** diff --git a/netx/net/sourceforge/jnlp/tools/KeyStoreUtil.java b/netx/net/sourceforge/jnlp/tools/KeyStoreUtil.java index 5f497ef..017bbea 100644 --- a/netx/net/sourceforge/jnlp/tools/KeyStoreUtil.java +++ b/netx/net/sourceforge/jnlp/tools/KeyStoreUtil.java @@ -44,7 +44,6 @@ public class KeyStoreUtil { // this class is not meant to be instantiated } - /** * Returns true if KeyStore has a password. This is true except for * MSCAPI KeyStores @@ -60,7 +59,7 @@ public class KeyStoreUtil { public static String niceStoreTypeName(String storetype) { if (storetype.equalsIgnoreCase("Windows-MY")) { return "Windows-MY"; - } else if(storetype.equalsIgnoreCase("Windows-ROOT")) { + } else if (storetype.equalsIgnoreCase("Windows-ROOT")) { return "Windows-ROOT"; } else { return storetype.toUpperCase(); diff --git a/netx/net/sourceforge/jnlp/tools/KeyTool.java b/netx/net/sourceforge/jnlp/tools/KeyTool.java index 7e7d4e7..eeda0aa 100644 --- a/netx/net/sourceforge/jnlp/tools/KeyTool.java +++ b/netx/net/sourceforge/jnlp/tools/KeyTool.java @@ -53,137 +53,137 @@ import net.sourceforge.jnlp.security.SecurityUtil; */ public class KeyTool { - // The user's keystore. - private KeyStore usercerts = null; - // JDK cacerts - private KeyStore cacerts = null; - // System ca-bundle.crt - private KeyStore systemcerts = null; + // The user's keystore. + private KeyStore usercerts = null; + // JDK cacerts + private KeyStore cacerts = null; + // System ca-bundle.crt + private KeyStore systemcerts = null; - private String fullCertPath = SecurityUtil.getTrustedCertsFilename(); + private String fullCertPath = SecurityUtil.getTrustedCertsFilename(); - private FileOutputStream fos = null; + private FileOutputStream fos = null; - /** - * Whether we trust the system cacerts file. - */ - private boolean trustcacerts = true; + /** + * Whether we trust the system cacerts file. + */ + private boolean trustcacerts = true; - private final char[] password = "changeit".toCharArray(); + private final char[] password = "changeit".toCharArray(); - /** - * Whether we prompt for user input. - */ - private boolean noprompt = true; + /** + * Whether we prompt for user input. + */ + private boolean noprompt = true; - public KeyTool() throws Exception { + public KeyTool() throws Exception { - // Initialize all the keystores. - usercerts = SecurityUtil.getUserKeyStore(); - cacerts = SecurityUtil.getCacertsKeyStore(); - systemcerts = SecurityUtil.getSystemCertStore(); - } + // Initialize all the keystores. + usercerts = SecurityUtil.getUserKeyStore(); + cacerts = SecurityUtil.getCacertsKeyStore(); + systemcerts = SecurityUtil.getSystemCertStore(); + } - /** - * Adds a trusted certificate to the user's keystore. - * @return true if the add was successful, false otherwise. - */ - public boolean importCert(File file) throws Exception { - - BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); - CertificateFactory cf = CertificateFactory.getInstance("X509"); - X509Certificate cert = null; - - if (bis.available() >= 1) { - try { - cert = (X509Certificate)cf.generateCertificate(bis); - } catch (ClassCastException cce) { - throw new Exception("Input file is not an X509 Certificate"); - } catch (CertificateException ce) { - throw new Exception("Input file is not an X509 Certificate"); - } - } + /** + * Adds a trusted certificate to the user's keystore. + * @return true if the add was successful, false otherwise. + */ + public boolean importCert(File file) throws Exception { - return importCert((Certificate)cert); + BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); + CertificateFactory cf = CertificateFactory.getInstance("X509"); + X509Certificate cert = null; + + if (bis.available() >= 1) { + try { + cert = (X509Certificate) cf.generateCertificate(bis); + } catch (ClassCastException cce) { + throw new Exception("Input file is not an X509 Certificate"); + } catch (CertificateException ce) { + throw new Exception("Input file is not an X509 Certificate"); + } } - /** - * Adds a trusted certificate to the user's keystore. - * @return true if the add was successful, false otherwise. - */ - public boolean importCert(Certificate cert) throws Exception { + return importCert((Certificate) cert); + } - String alias = usercerts.getCertificateAlias(cert); + /** + * Adds a trusted certificate to the user's keystore. + * @return true if the add was successful, false otherwise. + */ + public boolean importCert(Certificate cert) throws Exception { - if (alias != null) { //cert already exists - return true; - } else { - String newAlias = getRandomAlias(); - //check to make sure this alias doesn't exist - while (usercerts.getCertificate(newAlias) != null) - newAlias = getRandomAlias(); - return addTrustedCert(newAlias, cert); - } - } + String alias = usercerts.getCertificateAlias(cert); - /** - * Generates a random alias for storing a trusted Certificate. - */ - private String getRandomAlias() { - Random r = new Random(); - String token = Long.toString(Math.abs(r.nextLong()), 36); - return "trustedCert-" + token; + if (alias != null) { //cert already exists + return true; + } else { + String newAlias = getRandomAlias(); + //check to make sure this alias doesn't exist + while (usercerts.getCertificate(newAlias) != null) + newAlias = getRandomAlias(); + return addTrustedCert(newAlias, cert); } + } - /** - * Prints all keystore entries. + /** + * Generates a random alias for storing a trusted Certificate. */ - private void doPrintEntries(PrintStream out) throws Exception { + private String getRandomAlias() { + Random r = new Random(); + String token = Long.toString(Math.abs(r.nextLong()), 36); + return "trustedCert-" + token; + } + + /** + * Prints all keystore entries. + */ + private void doPrintEntries(PrintStream out) throws Exception { - out.println("KeyStore type: " + usercerts.getType()); - out.println("KeyStore provider: " + usercerts.getProvider().toString()); - out.println(); + out.println("KeyStore type: " + usercerts.getType()); + out.println("KeyStore provider: " + usercerts.getProvider().toString()); + out.println(); - for (Enumeration<String> e = usercerts.aliases(); e.hasMoreElements();) { - String alias = e.nextElement(); - doPrintEntry(alias, out, false); - } + for (Enumeration<String> e = usercerts.aliases(); e.hasMoreElements();) { + String alias = e.nextElement(); + doPrintEntry(alias, out, false); } + } /** * Prints a single keystore entry. */ - private void doPrintEntry(String alias, PrintStream out, + private void doPrintEntry(String alias, PrintStream out, boolean printWarning) throws Exception { - if (usercerts.containsAlias(alias) == false) { - throw new Exception("Alias does not exist"); - } + if (usercerts.containsAlias(alias) == false) { + throw new Exception("Alias does not exist"); + } - if (usercerts.entryInstanceOf(alias, + if (usercerts.entryInstanceOf(alias, KeyStore.TrustedCertificateEntry.class)) { - Certificate cert = usercerts.getCertificate(alias); + Certificate cert = usercerts.getCertificate(alias); - out.println("Alias: " + alias); - out.println("Date Created: " + usercerts.getCreationDate(alias)); - out.println("Subject: " + SecurityUtil.getCN(((X509Certificate)usercerts + out.println("Alias: " + alias); + out.println("Date Created: " + usercerts.getCreationDate(alias)); + out.println("Subject: " + SecurityUtil.getCN(((X509Certificate) usercerts .getCertificate(alias)).getSubjectX500Principal().getName())); - out.println("Certificate fingerprint (MD5): " + out.println("Certificate fingerprint (MD5): " + getCertFingerPrint("MD5", cert)); - out.println(); - } + out.println(); } + } /** * Gets the requested finger print of the certificate. */ - private String getCertFingerPrint(String mdAlg, Certificate cert) + private String getCertFingerPrint(String mdAlg, Certificate cert) throws Exception { - byte[] encCertInfo = cert.getEncoded(); - MessageDigest md = MessageDigest.getInstance(mdAlg); - byte[] digest = md.digest(encCertInfo); - return toHexString(digest); - } + byte[] encCertInfo = cert.getEncoded(); + MessageDigest md = MessageDigest.getInstance(mdAlg); + byte[] digest = md.digest(encCertInfo); + return toHexString(digest); + } /** * Converts a byte to hex digit and writes to the supplied buffer @@ -204,31 +204,31 @@ public class KeyTool { StringBuffer buf = new StringBuffer(); int len = block.length; for (int i = 0; i < len; i++) { - byte2hex(block[i], buf); - if (i < len-1) { - buf.append(":"); - } + byte2hex(block[i], buf); + if (i < len - 1) { + buf.append(":"); + } } return buf.toString(); } - /** - * Adds a certificate to the keystore, and writes new keystore to disk. - */ + /** + * Adds a certificate to the keystore, and writes new keystore to disk. + */ private boolean addTrustedCert(String alias, Certificate cert) - throws Exception { + throws Exception { - if (isSelfSigned((X509Certificate)cert)) { - //will throw exception if this fails - cert.verify(cert.getPublicKey()); - } + if (isSelfSigned((X509Certificate) cert)) { + //will throw exception if this fails + cert.verify(cert.getPublicKey()); + } if (noprompt) { - usercerts.setCertificateEntry(alias, cert); - fos = new FileOutputStream(fullCertPath); - usercerts.store(fos, password); - fos.close(); - return true; + usercerts.setCertificateEntry(alias, cert); + fos = new FileOutputStream(fullCertPath); + usercerts.store(fos, password); + fos.close(); + return true; } return false; @@ -239,12 +239,12 @@ public class KeyTool { */ public boolean isTrusted(Certificate cert) throws Exception { if (cert != null) { - if (usercerts.getCertificateAlias(cert) != null) { - return true; // found in own keystore - } - return false; + if (usercerts.getCertificateAlias(cert) != null) { + return true; // found in own keystore + } + return false; } else { - return false; + return false; } } @@ -265,23 +265,23 @@ public class KeyTool { public boolean checkCacertsForCertificate(Certificate c) throws Exception { if (c != null) { - String alias = null; + String alias = null; - //first try jdk cacerts. - if (cacerts != null) { - alias = cacerts.getCertificateAlias(c); + //first try jdk cacerts. + if (cacerts != null) { + alias = cacerts.getCertificateAlias(c); - //if we can't find it here, try the system certs. - if (alias == null && systemcerts != null) - alias = systemcerts.getCertificateAlias(c); - } - //otherwise try the system certs if you can't use the jdk certs. - else if (systemcerts != null) - alias = systemcerts.getCertificateAlias(c); + //if we can't find it here, try the system certs. + if (alias == null && systemcerts != null) + alias = systemcerts.getCertificateAlias(c); + } + //otherwise try the system certs if you can't use the jdk certs. + else if (systemcerts != null) + alias = systemcerts.getCertificateAlias(c); - return (alias != null); + return (alias != null); } else - return false; + return false; } /** @@ -294,8 +294,7 @@ public class KeyTool { */ public boolean establishCertChain(Certificate userCert, Certificate certToVerify) - throws Exception - { + throws Exception { if (userCert != null) { // Make sure that the public key of the certificate reply matches // the original public key in the keystore @@ -325,8 +324,8 @@ public class KeyTool { keystorecerts2Hashtable(usercerts, certs); } if (trustcacerts) { //if we're trusting the cacerts - KeyStore caks = SecurityUtil.getCacertsKeyStore(); - if (caks!=null && caks.size()>0) { + KeyStore caks = SecurityUtil.getCacertsKeyStore(); + if (caks != null && caks.size() > 0) { if (certs == null) { certs = new Hashtable<Principal, Vector<Certificate>>(11); } @@ -336,13 +335,13 @@ public class KeyTool { // start building chain Vector<Certificate> chain = new Vector<Certificate>(2); - if (buildChain((X509Certificate)certToVerify, chain, certs)) { + if (buildChain((X509Certificate) certToVerify, chain, certs)) { Certificate[] newChain = new Certificate[chain.size()]; // buildChain() returns chain with self-signed root-cert first and // user-cert last, so we need to invert the chain before we store // it - int j=0; - for (int i=chain.size()-1; i>=0; i--) { + int j = 0; + for (int i = chain.size() - 1; i >= 0; i--) { newChain[j] = chain.elementAt(i); j++; } @@ -360,14 +359,13 @@ public class KeyTool { */ private void keystorecerts2Hashtable(KeyStore ks, Hashtable<Principal, Vector<Certificate>> hash) - throws Exception { + throws Exception { - for (Enumeration<String> aliases = ks.aliases(); - aliases.hasMoreElements(); ) { + for (Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements();) { String alias = aliases.nextElement(); Certificate cert = ks.getCertificate(alias); if (cert != null) { - Principal subjectDN = ((X509Certificate)cert).getSubjectDN(); + Principal subjectDN = ((X509Certificate) cert).getSubjectDN(); Vector<Certificate> vec = hash.get(subjectDN); if (vec == null) { vec = new Vector<Certificate>(); @@ -412,10 +410,8 @@ public class KeyTool { // Try out each certificate in the vector, until we find one // whose public key verifies the signature of the certificate // in question. - for (Enumeration<Certificate> issuerCerts = vec.elements(); - issuerCerts.hasMoreElements(); ) { - X509Certificate issuerCert - = (X509Certificate)issuerCerts.nextElement(); + for (Enumeration<Certificate> issuerCerts = vec.elements(); issuerCerts.hasMoreElements();) { + X509Certificate issuerCert = (X509Certificate) issuerCerts.nextElement(); PublicKey issuerPubKey = issuerCert.getPublicKey(); try { certToVerify.verify(issuerPubKey); @@ -430,8 +426,8 @@ public class KeyTool { return false; } - public static void main(String[] args) throws Exception { - KeyTool kt = new KeyTool(); - kt.doPrintEntries(System.out); - } + public static void main(String[] args) throws Exception { + KeyTool kt = new KeyTool(); + kt.doPrintEntries(System.out); + } } diff --git a/netx/net/sourceforge/jnlp/util/FileUtils.java b/netx/net/sourceforge/jnlp/util/FileUtils.java index b006424..51081ed 100644 --- a/netx/net/sourceforge/jnlp/util/FileUtils.java +++ b/netx/net/sourceforge/jnlp/util/FileUtils.java @@ -192,7 +192,7 @@ public final class FileUtils { return path.substring(path.length() - visibleChars); } - int affixLength = (visibleChars - OMITTED_LENGTH)/2; + int affixLength = (visibleChars - OMITTED_LENGTH) / 2; String prefix = path.substring(0, affixLength); String suffix = path.substring(path.length() - affixLength); diff --git a/netx/net/sourceforge/jnlp/util/PropertiesFile.java b/netx/net/sourceforge/jnlp/util/PropertiesFile.java index 80a7ec2..6cdfd59 100644 --- a/netx/net/sourceforge/jnlp/util/PropertiesFile.java +++ b/netx/net/sourceforge/jnlp/util/PropertiesFile.java @@ -14,7 +14,6 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.util; import java.io.*; @@ -45,7 +44,6 @@ public class PropertiesFile extends Properties { /** lazy loaded on getProperty */ boolean loaded = false; - /** * Create a properties object backed by the specified file. * @@ -121,8 +119,7 @@ public class PropertiesFile extends Properties { InputStream s = new FileInputStream(file); load(s); - } - catch (IOException ex) { + } catch (IOException ex) { // eat } } @@ -137,8 +134,7 @@ public class PropertiesFile extends Properties { try { OutputStream s = new FileOutputStream(file); store(s, header); - } - catch (IOException ex) { + } catch (IOException ex) { // eat } } diff --git a/netx/net/sourceforge/jnlp/util/Reflect.java b/netx/net/sourceforge/jnlp/util/Reflect.java index 2b1301c..5f40629 100644 --- a/netx/net/sourceforge/jnlp/util/Reflect.java +++ b/netx/net/sourceforge/jnlp/util/Reflect.java @@ -19,7 +19,6 @@ package net.sourceforge.jnlp.util; import java.util.*; import java.lang.reflect.*; - /** * Provides simply, convenient methods to invoke methods by * name. This class is used to consolidate reflection needed to @@ -48,7 +47,6 @@ public class Reflect { private static Object zero[] = new Object[0]; - /** * Create a new Reflect instance. */ @@ -84,8 +82,7 @@ public class Reflect { m.setAccessible(accessible); return m.invoke(null, args); - } - catch (Exception ex) { // eat + } catch (Exception ex) { // eat return null; } } @@ -110,8 +107,7 @@ public class Reflect { m.setAccessible(accessible); return m.invoke(object, args); - } - catch (Exception ex) { // eat + } catch (Exception ex) { // eat ex.printStackTrace(); return null; } @@ -126,7 +122,7 @@ public class Reflect { for (Class c = type; c != null; c = c.getSuperclass()) { Method methods[] = c.getMethods(); - for (int i=0; i < methods.length; i++) { + for (int i = 0; i < methods.length; i++) { if (methods[i].getName().equals(method)) { Class parameters[] = methods[i].getParameterTypes(); @@ -135,8 +131,7 @@ public class Reflect { } } } - } - catch (Exception ex) { // eat + } catch (Exception ex) { // eat ex.printStackTrace(); } diff --git a/netx/net/sourceforge/jnlp/util/WeakList.java b/netx/net/sourceforge/jnlp/util/WeakList.java index 85204b1..66dab40 100644 --- a/netx/net/sourceforge/jnlp/util/WeakList.java +++ b/netx/net/sourceforge/jnlp/util/WeakList.java @@ -14,13 +14,11 @@ // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - package net.sourceforge.jnlp.util; import java.lang.ref.*; import java.util.*; - /** * This list stores objects automatically using weak references. * Objects are added and removed from the list as normal, but may @@ -37,7 +35,6 @@ public class WeakList<E> extends AbstractList<E> { /* list of weak references */ private ArrayList<WeakReference<E>> refs = new ArrayList<WeakReference<E>>(); - /** * Create a weak random-access list. */ @@ -103,7 +100,7 @@ public class WeakList<E> extends AbstractList<E> { public List<E> hardList() { List<E> result = new ArrayList<E>(); - for (int i=0; i < size(); i++) { + for (int i = 0; i < size(); i++) { E tmp = get(i); if (tmp != null) @@ -118,8 +115,8 @@ public class WeakList<E> extends AbstractList<E> { * objects. */ public void trimToSize() { - for (int i=size(); i-->0;) - if (get(i)==null) + for (int i = size(); i-- > 0;) + if (get(i) == null) remove(i); } diff --git a/netx/net/sourceforge/jnlp/util/XDesktopEntry.java b/netx/net/sourceforge/jnlp/util/XDesktopEntry.java index eae4146..06dff37 100644 --- a/netx/net/sourceforge/jnlp/util/XDesktopEntry.java +++ b/netx/net/sourceforge/jnlp/util/XDesktopEntry.java @@ -75,7 +75,7 @@ public class XDesktopEntry { String pathToJavaws = System.getProperty("java.home") + File.separator + "bin" + File.separator + "javaws"; String cacheDir = JNLPRuntime.getConfiguration() - .getProperty(DeploymentConfiguration.KEY_USER_CACHE_DIR); + .getProperty(DeploymentConfiguration.KEY_USER_CACHE_DIR); File cacheFile = CacheUtil.urlToPath(file.getSourceLocation(), cacheDir); String fileContents = "[Desktop Entry]\n"; diff --git a/netx/net/sourceforge/nanoxml/XMLElement.java b/netx/net/sourceforge/nanoxml/XMLElement.java index f8fd369..2284895 100644 --- a/netx/net/sourceforge/nanoxml/XMLElement.java +++ b/netx/net/sourceforge/nanoxml/XMLElement.java @@ -35,7 +35,6 @@ import java.util.*; import net.sourceforge.jnlp.runtime.JNLPRuntime; - /** * XMLElement is a representation of an XML object. The object is able to parse * XML code. @@ -94,8 +93,7 @@ import net.sourceforge.jnlp.runtime.JNLPRuntime; * <<A href="mailto:[email protected]">[email protected]</A>> * @version $Name: $, $Revision: 1.2 $ */ -public class XMLElement -{ +public class XMLElement { /** * The attributes given to the element. @@ -106,8 +104,7 @@ public class XMLElement * <li>The keys and the values are strings. * </ul></dd></dl> */ - private Hashtable<String,Object> attributes; - + private Hashtable<String, Object> attributes; /** * Child elements of the element. @@ -121,7 +118,6 @@ public class XMLElement */ private Vector<XMLElement> children; - /** * The name of the element. * @@ -135,7 +131,6 @@ public class XMLElement */ private String name; - /** * The #PCDATA content of the object. * @@ -147,7 +142,6 @@ public class XMLElement */ private String contents; - /** * Conversion table for &...; entities. The keys are the entity names * without the & and ; delimiters. @@ -162,8 +156,7 @@ public class XMLElement * <li>The values are char arrays * </ul></dd></dl> */ - private Hashtable<String,char[]> entities; - + private Hashtable<String, char[]> entities; /** * The line number where the element starts. @@ -174,21 +167,18 @@ public class XMLElement */ private int lineNr; - /** * <code>true</code> if the case of the element and attribute names * are case insensitive. */ private boolean ignoreCase; - /** * <code>true</code> if the leading and trailing whitespace of #PCDATA * sections have to be ignored. */ private boolean ignoreWhitespace; - /** * Character read too much. * This character provides push-back functionality to the input reader @@ -212,7 +202,6 @@ public class XMLElement */ private Reader reader; - /** * The current line number in the source content. * @@ -222,7 +211,6 @@ public class XMLElement */ private int parserLineNr; - /** * Creates and initializes a new XML element. * Calling the construction is equivalent to: @@ -240,12 +228,10 @@ public class XMLElement * </ul></dd></dl> * */ - public XMLElement() - { - this(new Hashtable<String,char[]>(), false, true, true); + public XMLElement() { + this(new Hashtable<String, char[]>(), false, true, true); } - /** * Creates and initializes a new XML element. * <P> @@ -284,16 +270,15 @@ public class XMLElement * </ul></dd></dl><dl> * */ - protected XMLElement(Hashtable<String,char[]> entities, - boolean skipLeadingWhitespace, - boolean fillBasicConversionTable, - boolean ignoreCase) - { + protected XMLElement(Hashtable<String, char[]> entities, + boolean skipLeadingWhitespace, + boolean fillBasicConversionTable, + boolean ignoreCase) { this.ignoreWhitespace = skipLeadingWhitespace; this.ignoreCase = ignoreCase; this.name = null; this.contents = ""; - this.attributes = new Hashtable<String,Object>(); + this.attributes = new Hashtable<String, Object>(); this.children = new Vector<XMLElement>(); this.entities = entities; this.lineNr = 0; @@ -314,7 +299,6 @@ public class XMLElement } } - /** * Adds a child element. * @@ -334,12 +318,10 @@ public class XMLElement * </ul></dd></dl><dl> * */ - public void addChild(XMLElement child) - { + public void addChild(XMLElement child) { this.children.addElement(child); } - /** * Adds or modifies an attribute. * @@ -362,15 +344,13 @@ public class XMLElement * */ public void setAttribute(String name, - Object value) - { + Object value) { if (this.ignoreCase) { name = name.toUpperCase(); } this.attributes.put(name, value.toString()); } - /** * Returns the number of child elements of the element. * @@ -379,12 +359,10 @@ public class XMLElement * </ul></dd></dl> * */ - public int countChildren() - { + public int countChildren() { return this.children.size(); } - /** * Enumerates the attribute names. * @@ -393,12 +371,10 @@ public class XMLElement * </ul></dd></dl> * */ - public Enumeration enumerateAttributeNames() - { + public Enumeration enumerateAttributeNames() { return this.attributes.keys(); } - /** * Enumerates the child elements. * @@ -407,23 +383,19 @@ public class XMLElement * </ul></dd></dl> * */ - public Enumeration enumerateChildren() - { + public Enumeration enumerateChildren() { return this.children.elements(); } - /** * Returns the PCDATA content of the object. If there is no such content, * <CODE>null</CODE> is returned. * */ - public String getContent() - { + public String getContent() { return this.contents; } - /** * Returns the line nr in the source data on which the element is found. * This method returns <code>0</code> there is no associated source data. @@ -432,12 +404,10 @@ public class XMLElement * <ul><li><code>result >= 0</code> * </ul></dd></dl> */ - public int getLineNr() - { + public int getLineNr() { return this.lineNr; } - /** * Returns an attribute of the element. * If the attribute doesn't exist, <code>null</code> is returned. @@ -450,8 +420,7 @@ public class XMLElement * </ul></dd></dl><dl> * */ - public Object getAttribute(String name) - { + public Object getAttribute(String name) { if (this.ignoreCase) { name = name.toUpperCase(); } @@ -459,17 +428,14 @@ public class XMLElement return value; } - /** * Returns the name of the element. * */ - public String getName() - { + public String getName() { return this.name; } - /** * Reads one XML element from a java.io.Reader and parses it. * @@ -494,12 +460,10 @@ public class XMLElement * If an error occured while parsing the read data. */ public void parseFromReader(Reader reader) - throws IOException, XMLParseException - { - this.parseFromReader(reader, /*startingLineNr*/ 1); + throws IOException, XMLParseException { + this.parseFromReader(reader, /*startingLineNr*/1); } - /** * Reads one XML element from a java.io.Reader and parses it. * @@ -526,9 +490,8 @@ public class XMLElement * If an error occured while parsing the read data. */ public void parseFromReader(Reader reader, - int startingLineNr) - throws IOException, XMLParseException - { + int startingLineNr) + throws IOException, XMLParseException { this.charReadTooMuch = '\0'; this.reader = reader; this.parserLineNr = startingLineNr; @@ -552,33 +515,28 @@ public class XMLElement } } - /** * Creates a new similar XML element. * <P> * You should override this method when subclassing XMLElement. */ - protected XMLElement createAnotherElement() - { + protected XMLElement createAnotherElement() { return new XMLElement(this.entities, this.ignoreWhitespace, false, this.ignoreCase); } - /** * Changes the content string. * * @param content * The new content string. */ - public void setContent(String content) - { + public void setContent(String content) { this.contents = content; } - /** * Changes the name of the element. * @@ -591,12 +549,10 @@ public class XMLElement * </ul></dd></dl> * */ - public void setName(String name) - { + public void setName(String name) { this.name = name; } - /** * Scans an identifier from the current reader. * The scanned identifier is appended to <code>result</code>. @@ -616,13 +572,12 @@ public class XMLElement * </ul></dd></dl><dl> */ protected void scanIdentifier(StringBuffer result) - throws IOException - { + throws IOException { for (;;) { char ch = this.readChar(); if (((ch < 'A') || (ch > 'Z')) && ((ch < 'a') || (ch > 'z')) - && ((ch < '0') || (ch > '9')) && (ch != '_') && (ch != '.') - && (ch != ':') && (ch != '-') && (ch <= '\u007E')) { + && ((ch < '0') || (ch > '9')) && (ch != '_') && (ch != '.') + && (ch != ':') && (ch != '-') && (ch <= '\u007E')) { this.unreadChar(ch); return; } @@ -630,15 +585,13 @@ public class XMLElement } } - /** * This method scans an identifier from the current reader. * * @return the next character following the whitespace. */ protected char scanWhitespace() - throws IOException - { + throws IOException { for (;;) { char ch = this.readChar(); switch (ch) { @@ -653,7 +606,6 @@ public class XMLElement } } - /** * This method scans an identifier from the current reader. * The scanned whitespace is appended to <code>result</code>. @@ -665,8 +617,7 @@ public class XMLElement * </ul></dd></dl> */ protected char scanWhitespace(StringBuffer result) - throws IOException - { + throws IOException { for (;;) { char ch = this.readChar(); switch (ch) { @@ -683,7 +634,6 @@ public class XMLElement } } - /** * This method scans a delimited string from the current reader. * The scanned string without delimiters is appended to @@ -695,8 +645,7 @@ public class XMLElement * </ul></dd></dl> */ protected void scanString(StringBuffer string) - throws IOException - { + throws IOException { char delimiter = this.readChar(); if ((delimiter != '\'') && (delimiter != '"')) { throw this.expectedInput("' or \""); @@ -713,7 +662,6 @@ public class XMLElement } } - /** * Scans a #PCDATA element. CDATA sections and entities are resolved. * The next < char is skipped. @@ -724,8 +672,7 @@ public class XMLElement * </ul></dd></dl> */ protected void scanPCData(StringBuffer data) - throws IOException - { + throws IOException { for (;;) { char ch = this.readChar(); if (ch == '<') { @@ -744,7 +691,6 @@ public class XMLElement } } - /** * Scans a special tag and if the tag is a CDATA section, append its * content to <code>buf</code>. @@ -755,14 +701,13 @@ public class XMLElement * </ul></dd></dl> */ protected boolean checkCDATA(StringBuffer buf) - throws IOException - { + throws IOException { char ch = this.readChar(); if (ch != '[') { this.unreadChar(ch); this.skipSpecialTag(0); return false; - } else if (! this.checkLiteral("CDATA[")) { + } else if (!this.checkLiteral("CDATA[")) { this.skipSpecialTag(1); // one [ has already been read return false; } else { @@ -802,7 +747,6 @@ public class XMLElement } } - /** * Skips a comment. * @@ -811,8 +755,7 @@ public class XMLElement * </ul></dd></dl> */ protected void skipComment() - throws IOException - { + throws IOException { int dashesToRead = 2; while (dashesToRead > 0) { char ch = this.readChar(); @@ -841,7 +784,6 @@ public class XMLElement */ } - /** * Skips a special tag or comment. * @@ -854,8 +796,7 @@ public class XMLElement * </ul></dd></dl> */ protected void skipSpecialTag(int bracketLevel) - throws IOException - { + throws IOException { int tagLevel = 1; // < char stringDelimiter = '\0'; if (bracketLevel == 0) { @@ -899,7 +840,6 @@ public class XMLElement } } - /** * Scans the data for literal text. * Scanning stops when a character does not match or after the complete @@ -912,8 +852,7 @@ public class XMLElement * </ul></dd></dl> */ protected boolean checkLiteral(String literal) - throws IOException - { + throws IOException { int length = literal.length(); for (int i = 0; i < length; i += 1) { if (this.readChar() != literal.charAt(i)) { @@ -923,13 +862,11 @@ public class XMLElement return true; } - /** * Reads a character from a reader. */ protected char readChar() - throws IOException - { + throws IOException { if (this.charReadTooMuch != '\0') { char ch = this.charReadTooMuch; this.charReadTooMuch = '\0'; @@ -947,7 +884,6 @@ public class XMLElement } } - /** * Scans an XML element. * @@ -959,8 +895,7 @@ public class XMLElement * </ul></dd></dl> */ protected void scanElement(XMLElement elt) - throws IOException - { + throws IOException { StringBuffer buf = new StringBuffer(); this.scanIdentifier(buf); String name = buf.toString(); @@ -1051,7 +986,7 @@ public class XMLElement throw this.expectedInput("/"); } this.unreadChar(this.scanWhitespace()); - if (! this.checkLiteral(name)) { + if (!this.checkLiteral(name)) { throw this.expectedInput(name); } if (this.scanWhitespace() != '>') { @@ -1059,7 +994,6 @@ public class XMLElement } } - /** * Resolves an entity. The name of the entity is read from the reader. * The value of the entity is appended to <code>buf</code>. @@ -1072,8 +1006,7 @@ public class XMLElement * </ul></dd></dl> */ protected void resolveEntity(StringBuffer buf) - throws IOException - { + throws IOException { char ch = '\0'; StringBuffer keyBuf = new StringBuffer(); for (;;) { @@ -1104,7 +1037,6 @@ public class XMLElement } } - /** * Pushes a character back to the read-back buffer. * @@ -1115,12 +1047,10 @@ public class XMLElement * <li><code>ch != '\0'</code> * </ul></dd></dl> */ - protected void unreadChar(char ch) - { + protected void unreadChar(char ch) { this.charReadTooMuch = ch; } - /** * Creates a parse exception for when an invalid valueset is given to * a method. @@ -1131,13 +1061,11 @@ public class XMLElement * <ul><li><code>name != null</code> * </ul></dd></dl> */ - protected XMLParseException invalidValueSet(String name) - { + protected XMLParseException invalidValueSet(String name) { String msg = "Invalid value set (entity name = \"" + name + "\")"; return new XMLParseException(this.getName(), this.parserLineNr, msg); } - /** * Creates a parse exception for when an invalid value is given to a * method. @@ -1151,25 +1079,21 @@ public class XMLElement * </ul></dd></dl> */ protected XMLParseException invalidValue(String name, - String value) - { + String value) { String msg = "Attribute \"" + name + "\" does not contain a valid " + "value (\"" + value + "\")"; return new XMLParseException(this.getName(), this.parserLineNr, msg); } - /** * Creates a parse exception for when the end of the data input has been * reached. */ - protected XMLParseException unexpectedEndOfData() - { + protected XMLParseException unexpectedEndOfData() { String msg = "Unexpected end of data reached"; return new XMLParseException(this.getName(), this.parserLineNr, msg); } - /** * Creates a parse exception for when a syntax error occured. * @@ -1180,13 +1104,11 @@ public class XMLElement * <li><code>context.length() > 0</code> * </ul></dd></dl> */ - protected XMLParseException syntaxError(String context) - { + protected XMLParseException syntaxError(String context) { String msg = "Syntax error while parsing " + context; return new XMLParseException(this.getName(), this.parserLineNr, msg); } - /** * Creates a parse exception for when the next character read is not * the character that was expected. @@ -1199,8 +1121,7 @@ public class XMLElement * <li><code>charSet.length() > 0</code> * </ul></dd></dl> */ - protected XMLParseException expectedInput(String charSet) - { + protected XMLParseException expectedInput(String charSet) { String msg = "Expected: " + charSet; return new XMLParseException(this.getName(), this.parserLineNr, msg); } @@ -1217,9 +1138,8 @@ public class XMLElement * <li><code>charSet.length() > 0</code> * </ul></dd></dl> */ - protected XMLParseException expectedInput(String charSet, char ch) - { - String msg = "Expected: '" + charSet +"'" + " but got: '" + ch + "'"; + protected XMLParseException expectedInput(String charSet, char ch) { + String msg = "Expected: '" + charSet + "'" + " but got: '" + ch + "'"; return new XMLParseException(this.getName(), this.parserLineNr, msg); } @@ -1233,8 +1153,7 @@ public class XMLElement * <li><code>name.length() > 0</code> * </ul></dd></dl> */ - protected XMLParseException unknownEntity(String name) - { + protected XMLParseException unknownEntity(String name) { String msg = "Unknown or invalid entity: &" + name + ";"; return new XMLParseException(this.getName(), this.parserLineNr, msg); } @@ -1257,7 +1176,7 @@ public class XMLElement int newline = 2; char prev = ' '; - while(true) { + while (true) { char ch; if (this.sanitizeCharReadTooMuch != '\0') { ch = this.sanitizeCharReadTooMuch; diff --git a/netx/net/sourceforge/nanoxml/XMLParseException.java b/netx/net/sourceforge/nanoxml/XMLParseException.java index dfbb637..329dea4 100644 --- a/netx/net/sourceforge/nanoxml/XMLParseException.java +++ b/netx/net/sourceforge/nanoxml/XMLParseException.java @@ -26,10 +26,8 @@ * 3. This notice may not be removed or altered from any source distribution. *****************************************************************************/ - package net.sourceforge.nanoxml; - /** * An XMLParseException is thrown when an error occures while parsing an XML * string. @@ -43,15 +41,13 @@ package net.sourceforge.nanoxml; * @version $Name: $, $Revision: 1.1 $ */ public class XMLParseException - extends RuntimeException -{ + extends RuntimeException { /** * Indicates that no line number has been associated with this exception. */ public static final int NO_LINE = -1; - /** * The line number in the source code where the error occurred, or * <code>NO_LINE</code> if the line number is unknown. @@ -62,7 +58,6 @@ public class XMLParseException */ private int lineNr; - /** * Creates an exception. * @@ -78,16 +73,14 @@ public class XMLParseException * </ul></dd></dl><dl> */ public XMLParseException(String name, - String message) - { + String message) { super("XML Parse Exception during parsing of " - + ((name == null) ? "the XML definition" + + ((name == null) ? "the XML definition" : ("a " + name + " element")) - + ": " + message); + + ": " + message); this.lineNr = XMLParseException.NO_LINE; } - /** * Creates an exception. * @@ -105,25 +98,22 @@ public class XMLParseException * </ul></dd></dl><dl> */ public XMLParseException(String name, - int lineNr, - String message) - { + int lineNr, + String message) { super("XML Parse Exception during parsing of " - + ((name == null) ? "the XML definition" + + ((name == null) ? "the XML definition" : ("a " + name + " element")) - + " at line " + lineNr + ": " + message); + + " at line " + lineNr + ": " + message); this.lineNr = lineNr; } - /** * Where the error occurred, or <code>NO_LINE</code> if the line number is * unknown. * * @see net.sourceforge.nanoxml.XMLParseException#NO_LINE */ - public int getLineNr() - { + public int getLineNr() { return this.lineNr; } |