Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Calculate java home from java command #716

Merged
merged 3 commits into from
Oct 16, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import org.mvndaemon.mvnd.common.Environment;
import org.mvndaemon.mvnd.common.InterpolationHelper;
import org.mvndaemon.mvnd.common.Os;
import org.mvndaemon.mvnd.common.OsUtils;
import org.mvndaemon.mvnd.common.SocketFamily;
import org.mvndaemon.mvnd.common.TimeUtils;
import org.slf4j.Logger;
Expand Down Expand Up @@ -137,6 +138,9 @@ public Path javaHome() {
.orLocalProperty(provider, globalPropertiesPath())
.orSystemProperty()
.orEnvironmentVariable()
.or(new ValueSource(
description -> description.append("java command"),
this::javaHomeFromPATH))
.orFail()
.asPath();
try {
Expand All @@ -146,6 +150,14 @@ public Path javaHome() {
}
}

private String javaHomeFromPATH() {
final String jHome = OsUtils.findJavaHomeFromPATH();
if (null != jHome) {
System.setProperty(Environment.JAVA_HOME.getProperty(), jHome);
}
return jHome;
}

public Path userDir() {
return value(Environment.USER_DIR)
.orSystemProperty()
Expand Down
12 changes: 12 additions & 0 deletions common/src/main/java/org/mvndaemon/mvnd/common/OsUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,18 @@ public static long findProcessRssInKb(long pid) {
}
}

public static String findJavaHomeFromPATH() {
final String[] cmd = { "java", "-XshowSettings:properties", "-version" };
final List<String> output = new ArrayList<String>(1);
exec(cmd, output);
final List<String> javaHomeLines = output.stream().filter(l -> l.contains(" java.home = "))
.collect(Collectors.toList());
if (javaHomeLines.size() == 1) {
return javaHomeLines.get(0).trim().replaceFirst("java.home = ", "");
}
return null;
}

private static void exec(String[] cmd, final List<String> output) {
final ProcessBuilder builder = new ProcessBuilder(cmd).redirectErrorStream(true);
try (CommandProcess ps = new CommandProcess(builder.start(), output::add)) {
Expand Down