Fixup #716 Calculate java home from java command (#721)

* Add a test
* Simplify the stream processing

Co-authored-by: Guillaume Nodet <gnodet@gmail.com>
This commit is contained in:
Peter Palaga
2022-12-14 00:35:10 +01:00
committed by GitHub
parent 2b8076d1ed
commit 031c263232
3 changed files with 31 additions and 12 deletions

View File

@@ -111,16 +111,23 @@ public class OsUtils {
}
}
public static String findJavaHomeFromPath() {
String[] cmd = {"java", "-XshowSettings:properties", "-version"};
final List<String> output = new ArrayList<String>(1);
/**
* Executes the given {@code javaExecutable} with {@code -XshowSettings:properties -version} parameters and extracts
* the value of {@code java.home} from the output.
*
* @param javaExecutable pass {@code "java"} to get {@code java} binary available in {@code PATH} environment
* variable or pass an absolute path to a {@code "java"} executable
* @return a {@code java.home} value or null
*/
public static String findJavaHomeFromJavaExecutable(String javaExecutable) {
String[] cmd = {javaExecutable, "-XshowSettings:properties", "-version"};
final List<String> output = new ArrayList<String>();
exec(cmd, output);
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;
return output.stream()
.filter(l -> l.contains(" java.home = "))
.map(l -> l.substring(l.indexOf('=') + 1).trim())
.findFirst()
.orElse(null);
}
private static void exec(String[] cmd, final List<String> output) {

View File

@@ -31,4 +31,11 @@ public class OsUtilsTest {
Assertions.assertEquals("1g", OsUtils.kbTohumanReadable(1024 * 1024));
Assertions.assertEquals("1t", OsUtils.kbTohumanReadable(1024 * 1024 * 1024));
}
@Test
void findJavaHomeFromPath() {
final String expectedJavaHome = System.getProperty("java.home");
Assertions.assertEquals(
expectedJavaHome, OsUtils.findJavaHomeFromJavaExecutable(expectedJavaHome + "/bin/java"));
}
}