Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if my program is running as an Applet, or as an Java Application

I've written a clunky little breakout clone & I'm writing to disk for save games and high scores.

Is there an easy way for me to check if my program is running as an applet, or as an application?

eg...

if(!anApplet){
//Include disk i/o features
}

I've tried setting a boolean variable in the 'main' class, setting it to false with init(), and true in the main method but no luck so far. Will keep trying regardless, but thanks in advance for any advice!

like image 716
Brett Avatar asked Oct 24 '22 09:10

Brett


1 Answers

Use the AccessController. You could wrap all calls in an AccessController.doPrivileged block.

AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            // privileged code goes here, for example, read and writing files.
            ...
            return null; // nothing to return
        }
});

You could also, if necessary, establish the permissions that you application has, on startup, and use them later:

Boolean flag = AccessController.doPrivileged(new PrivilegedAction() {
        public Boolean run() {
            boolean flag = false;
            // privileged code goes here, for example, read and writing files. If it succeeds, set flag to true.
            ...
            return flag; // return true, if the privileged action succeeded
        }
});

I would recommend using the first approach. If you do use the second, then make the flag variable final in nature; you'll therefore need to perform any "privilege testing" in the constructor of the class that stores this flag.

Addendum

The snippets of code will continue to throw AccessControlExceptions, if they are encountered. If you want to continue processing, without hindering the user, then you'll have to catch them, while setting the flag to false. The AccessController.doPrivilege block exists to check if the permission exists for the current stack frame.

Addendum #2

Using AccessController.checkPermission is not recommended, unless you can guarantee the presence of a Security Manager, and an appropriate policy file. In the absence of a Security Manager, this method will always throw an exception for a permission check, which would be undesirable when the application is not running as an applet.

like image 128
Vineet Reynolds Avatar answered Nov 15 '22 01:11

Vineet Reynolds