Prevent jar from running on network drive

Bakri Bitar :

An executable jar is distributed to users per network drive. I want to prevent users from running it directly on the network because it causes performance and other problems.

One solution can be to check the execution path and compare it with the network drive path, but what if the network drive path is not known in advance? Is there any other possibility?

Stephen C :

I don't think you can do this in pure Java. I'm pretty sure you will need to either run an external command or make a call into native code to detect the whether the JAR file is on a network share.

The first part you need to do is to obtain the absolute path for the JAR file:

Class mainClass = MyMainClass.class;
File jarFile = new File(mainClass.getProtectionDomain()
                                 .getCodeSource()
                                 .getLocation()
                                 .toURI());

I found a "gist" on github written by Aaron Digulla that does the second rest of the task:

Aaron's code takes a Windows absolute path, extracts the drive letter and then runs the Windows net use <drive-letter>: command to test whether the drive is a share drive.


An alternative would be to implement the logic a batch file does the following:

  • Extract the drive name for the JAR file
  • Use net use ... to test for a share drive
  • Use the same technique to check that the Java installation is not on a share drive either1.
  • Use the java command to start the application

Finally, is probably a bad idea to refuse to run on a share drive. The user may have reasons to do this that you are not aware of. I would suggest prompting the user and giving the user the option of continuing anyway. Or something like that.

Alternatively, document in the application's installation instructions that it is inadvisable to install the JRE / JDK and the application on a share drive (or equivalent).


1 - A Java install on a share drive will give as bad if not worse performance than an application JAR on a share drive.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=157045&siteId=1