Search code examples
javajava-web-start

What is the best way to detect whether an application is launched by Webstart


As it was made clear in my recent question, Swing applications need to explicitly call System.exit() when they are ran using the Sun Webstart launcher (at least as of Java SE 6).

I want to restrict this hack as much as possible and I am looking for a reliable way to detect whether the application is running under Webstart. Right now I am checking that the value of the system property "webstart.version" is not null, but I couldn't find any guarantees in the documentation that this property should be set by future versions/alternative implementations.

Are there any better ways (preferably ones that do not ceate a dependency on the the webstart API?)


Solution

  • When your code is launched via javaws, javaws.jar is loaded and the JNLP API classes that you don't want to depend on are available. Instead of testing for a system property that is not guaranteed to exist, you could instead see if a JNLP API class exists:

    private boolean isRunningJavaWebStart() {
        boolean hasJNLP = false;
        try {
          Class.forName("javax.jnlp.ServiceManager");
          hasJNLP = true;
        } catch (ClassNotFoundException ex) {
          hasJNLP = false;
        }
        return hasJNLP;
    }
    

    This also avoids needing to include javaws.jar on your class path when compiling.

    Alternatively you could switch to compiling with javaws.jar and catching NoClassDefFoundError instead:

    private boolean isRunningJavaWebStart() {
        try {
            ServiceManager.getServiceNames();
            return ds != null;
        } catch (NoClassDefFoundError e) {
            return false;
        }
    }
    

    Using ServiceManager.lookup(String) and UnavailableServiceException is trouble because both are part of the JNLP API. The ServiceManager.getServiceNames() is not documented to throw. We are specifically calling this code to check for a NoClassDefFoundError.