Get JRE version from application - java

I need to get the java version from my application that the user has currently installed on their machine. However, the application that I have is installed with a self-contained JRE and when I do a System.getProperty("java.version"), it only returns the version of that self-contained JRE. Is there anyway that I can get the version that is installed on the machine?

The JRE installation are listed in the registry in the key only for Windows, Linux do not have central registry.
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
You can make a simple program to test :
public class ShowVersion {
public static void main(String args[]) {
System.out.println(System.getProperty("java.version"));
}
}
Or you can try command prompt
Type java -version
For more you can refer sister site of SO :
https://superuser.com/questions/1221096/how-do-i-check-what-version-of-java-i-have-installed

if you're bundling a JRE (did you check the distribution license for it? Make sure you are allowed to do so) and it's running under that, you get that version back.
If the user were to run it under another JRE, you'd get the version of that JRE. That's just how things work.
In fact if you're using a self-contained JRE the user doesn't even have to have another JRE installed on his system at all, that's the entire point of bundling one in the first place.
Apart from a full file system scan it's impossible to know what other JVMs might be installed, and if you do that you'd have to account for all the different names the Java runtime executables may have depending on the files system you're running on. And after finding all those executables you still have no real way of knowing what version of Java they belong to unless you either do a binary analysis of the executables or somehow detect the information from other files in the directories where those executables are installed, files that may or may not be present depending on the system in question, how it was set up, what JVM is in use, and whether the installation has been manually altered or not.
For example, in the root directory of a JDK installation there is a file called "release" which contains the JVM version, but AFAIK that file isn't required to be there for the JVM to work properly. And your application may not have the rights to the file system to read that file.

You can try looking in known paths e.g. C:\Program Files\Java but unless you scan the entire file system for java or java.exe you will never be sure.
This might not work as expected as in the user that runs your application shouldn't have access to system directories. You can force you application to be started with administrator level access but that would be a security risk.
You requirement seems a bit pointless if you are already bundling a JRE with your application.

You can run cmd command using java (java -version) and use that output to get version.
List<String> cmdArgs = new ArrayList<>();
cmdArgs.add("cmd.exe");
cmdArgs.add("/C");
cmdArgs.add("java -version");
ProcessBuilder processBuilderObj = new ProcessBuilder();
processBuilderObj.command(cmdArgs);
Process process = processBuilderObj.start();
//get inputStream
BufferedReader data = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line1;
while ((line = data.readLine()) != null){
System.out.println(line);
}

While System.getProperty("java.version") returns the version of the Java that your app is running on, calling "java -version" as a system command from your Java app will return the version of the default(installed) Java in your system.
Here are the generic steps to find it programmatically:
Using ProcessBuilder in Java, execute the system command "java -version". This is certainly platform-independent.
Read the output from executed process. The version is usually on the 1st line of the output (smth like java version "1.8.0_191"), so reading the 1st line is enough.
Check using regular expression, if the output matches a string containing a java version, you just parse the version and that will be what you are looking for.
Otherwise, it means the output is an error message (smth like -bash: java: command not found), and there is no Java installed in your system.

control panel
java
Java tab
view
you can see exact version of java used and it's location.

Related

Java code - Best way to list java processes in localhost JVM (for Linux & Windows]

I'm writing a console app that will run in Linux and Windows systems. This app will mainly run on JRE 1.8 environments.
In my code, it needs to get a list of Java processes that run on the host running my application. I have read the posts about jps, which come as a part of JDK, but not JRE, and also it's a separate executable.
My question is, is there any java library that I can use, to list (and ideally also kill some of) the running Java processes? Preferably, I would not want to hassle of calling jps executable with sth like Runtime.exec().
Thanks in advance, for any suggestions.
Oops: I just spotted that you need solutions for JRE1.8, this will only help for JRE9+.
A simple way to scan processes within JRE is to use ProcessHandle.allProcesses(). This will read all processes and you can add filter on simple name match with "java" or "java.exe":
Path java = Path.of("bin", "java.exe"); // use "java" if not on Windows
ProcessHandle.allProcesses()
.filter(ph -> ph.info().command().isPresent())
.filter(ph -> Path.of(ph.info().command().get()).endsWith(java))
.forEach(ph -> {
System.out.println("PID "+ph.pid()+" "+ph.info().command());
})
This approach won't spot Java VMs embedded in EXE - such as from jpackage - so is not as reliable as using JDK jps which does recognise jpackage EXEs and JDK tools like jshell.exe.
I finally found the 3rd party library named Oshi, which apparently does not need JDK and is compatible with Java 1.8: https://github.com/oshi/oshi
For future reference, here is a sample method:
public static List<OSProcess> getOSProcesses() {
SystemInfo si = new SystemInfo();
OperatingSystem os = si.getOperatingSystem();
return os.getProcesses();
}

check java is installed on windows system

How to check, java is installed on windows system and get fullpath from jvm.dll on client folder?
I used this code, but i dont know how to retrive the current version
TRegistry* reg = new TRegistry(KEY_READ);
reg->RootKey = HKEY_CURRENT_USER;
reg->Access = KEY_ALL_ACCESS;
bool openResult = reg->OpenKey("SOFTWARE\\JavaSoft\\Java Runtime Environment", true);
if(!openResult) // cannot create registry keys, use default values
return;
if(!reg->ValueExists("CurrentVersion")) //it's not exist CuurentVersion
return;
I don't think writing some code or anything like that is needed to see if java is installed.
To see if its installed on windows just go to C:\Program Files\Java if that directory exists then you have java, if its installed on a different directory look in windows programs and it should show if java is installed, if not then you most likely don't have java.
Use this link to see what version you have, but it is recommended to always get the latest version.
Hope this helps, Luke
Edit:
If you want to see if java is installed on another computer programmatically try using a .bat file to see, this link should help.
or use jsmooth to build the jar into an .exe, with this, if java is not installed it will prompt the user to install java.
You can execute a system "Java -version" command from your code. Here is an example for C++. To find the version you just need to parse the result you get, if you get. The String result would provide the information you required.
Meanwhile, to find the path i believe you can do it by iterating through environmental variables and look for JAVA_HOME.

Tomcat on Windows server woes

Synopsis: When calling an executable that links to shared libraries from Java code on Tomcat, I get errors on Windows 2003 whereas the executable works great on a command prompt.
I wanted to do this in Linux, but, alas, got outvoted and have to implement it using Windows Server 2003. Here it goes,
I have a simple Java code running on Tomcat which, when it receives a "start" signal from another server has to run an external executable (written in C++, using shared library DLLs from OpenCV and ffmpeg) like so
String cmd = "c:\\workspace\\process_video.exe -video " + filename;
// Execute the command
Process proc = null;
try {
proc = rt.exec(cmd);
} catch (Exception e) {
System.out.println("VA-> Exception thrown in running the command!");
errorOut.append(e.getStackTrace().toString());
}
Now, when I run the command in process_video from a DOS command prompt, it works (doesn't matter which directory it's issued from). However, when it is run through the Tomcat->my Java code->rt.exec() chain, cmd doesn't get executed, although the exception doesn't get thrown. When I examine Windows event logs, I see an APPCHRASH event for process_video with Fault Module Name cv110.dll, which is one of the OpenCV DLLs I link from cmd.
One solution would be to stuff all the DLLs used in process_video into the tomcat\lib directory, but this hurts my programmatic sensibilities, so I want to know if there is a better way to solve this issue. What user does Tomcat use when running executables on Windows? Maybe I can give more privileges to that user? Should I add the DLL paths to Tomcat's configuration file?
Any help will be much appreciated,
Thanks!
Cuneyt
Add an entry in the PATH evironment variable that points to where your DLLs are. If this doesn't work for your app, you can try adding the entry to Tomcat's PATH. You have to modify the PATH variable of the process that will be loading the executable. Since your Java code probably shares a JVM (and hence a process) with the Tomcat executable, that will dictate which environment the PATH variable will need to be updated.
This is a Windows problem, not a Tomcat problem.
By default, Windows looks in %Path% for DLLs, which may not include the directory of the EXE file.
You can fix this by creating an empty file called process_video.exe.local in the same direcotry as the EXE ( i.e. c:\workspace )
You can also create a .manifest file, but this is a bit more complicated.

Cannot execute Java app on Vista Business - "Cannot find the main class... Program will exit"

I have written a Java GUI app (using Netbeans 6.7) requiring Java 1.6. I successfully run it on my XP PC and also my Mac OSX (10.5.7).
My client is running Vista Business, and cannot run the application by double clicking the jar file. He can execute it from the command line: "javaw -jar ..." The error received is: "Cannot find the main class... Program will exit".
I've asked the client to do the following:
install the latest JRE
run JarFix
I've verified that:
JRE is installed in correct location
jar file association is correct
application works (as I have tested it on XP and Mac OSX, and the client can run it from the command line)
Any ideas on what else I can investigate? Note, Netbeans created the main jar file, and also a lib directory with a couple of other Jarfiles. I've unzipped the jarfile and examined the manifest file (which looks good). The correct main class is also within the app's jarfile.
Does the client need to be careful as to where the application is executed from in Vista?
Thanks very much.
Prembo
Does exactly the same JAR file work on other operating systems?
Is the manifest file (META-INF/MANIFEST.MF) in the JAR file correct? One catch to watch out for is that the manifest file MUST end with an empty line; if it doesn't, the last line in the manifest file will be ignored. So, for example, if the last line in your manifest file is something like this:
Main-Class: com.mypackage.MyProgram
and it is not followed by an empty line, then Java will ignore the line and it will not be able to find the main class of the program.
See Sun's Java Tutorial about deploying Java programs in JAR files for exact details about how to package your application in a JAR; it also contains the warning about the manifest file needing to end with an empty line.
Also, double-check if the right version of Java is used. Are you using the exact same version of Java as on Windows XP? Try:
java -version
to see which Java version is being used.
I'm running Vista Enterprise and have very little differences between it and other Windows versions (with regards to Java).
Here are some random ideas that may or may not work:
Have you tried: right clicking on the Jar -> Open with -> Java(TM) Platform SE Binary
Could it be permissions related? (probably not since it runs via the command line)
Have you tried it with UAC off? (UAC sandboxes java apps, and they can't write to certain locations like Program Files)
Did you make sure they have the same files as you in JAVA_HOME/lib/ext/
you could try setting environment variables:
JAVA_HOME=<your_java_home>
CLASSPATH=.
PATH=<your_java_home>\bin
Sometimes JDK needs to be installed separately,along with the net beans IDE. If you have jdk installed then you can try checking for classpath,path in the environmental variables.

An easy bulletproof technique to check if the system has jre (windows)

Sorry my newbie question :P If I promp "java -version" in the cmd on a windows system, am I guaranteed that the system will be able to run .jar files if I don't get any error?
From the command line you should be able to invoke "java --version" which will return an error if java is not installed or the currently installed version information.
I guess the only guaranteed way to check for a JRE is to try to run a small Java program.
Or maybe not even that - I suppose conceivably a system could have only part of the Java standard library installed, in which case a small test JAR might work fine but a full program might not. Although I can't imagine why anyone would go to the trouble of setting a system up that way.
Why not run a small class file, which write a value to a file which you then check? If it fails, it doesn't work.
A good value might be the value of the java.version system property.
On Windows, you can check the registry at HKLM\SOFTWARE\JavaSoft\Java Plug-in. From there, each subkey is an installed JRE.
edit Here is C# code that will return an array of strings with the installed JRE's
public string[] GetInstalledJavas() {
// hold the registry subkeys that list the installed JRE's
string[] jres = null;
try {
RegistryKey myKey = Registry.LocalMachine;
myKey = myKey.OpenSubKey(#"SOFTWARE\JavaSoft\Java Plug-in"); // read-only
jres = myKey.GetSubKeyNames();
} catch (Exception myException) {
Console.Writeline(myException.ToString());
}
return jres;
}
Well, obviously not. You can put an empty file called java.bat anywhare in PATH, like C:\Windows\System32. Invoking "java" will not yield any errors but it doesn't mean there's a JRE installed.
I'd actually suggest, if you're only concerned about checking on windows machines, checking the registry for a handler for JNLP... that should guarantee the presence of a relatively recent JRE.

Categories