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

Adapt new behavior of System.console() since JDK22 #69

Merged
merged 2 commits into from
May 30, 2024
Merged
Changes from all 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 @@ -29,9 +29,11 @@
import org.aesh.terminal.utils.OSUtils;
import org.aesh.readline.util.LoggerUtil;

import java.io.Console;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
Expand Down Expand Up @@ -143,8 +145,8 @@ else if (OSUtils.IS_WINDOWS) {

private Terminal createWindowsTerminal(String name) throws IOException {
try {
//if console != null its a native terminal, not redirects etc
if(System.console() != null)
Console console = System.console();
if (console != null && isTerminal(console)) // a native terminal, not redirects etc
return new WinSysTerminal(name, nativeSignals);
else {
return new WinExternalTerminal(name, type, (in == null) ? System.in : in,
Expand All @@ -156,4 +158,22 @@ private Terminal createWindowsTerminal(String name) throws IOException {
(out == null) ? System.out : out);
}
}

// Console.isTerminal() was introduced in Java 22
private static boolean isTerminal(Console console) {
if (console == null) {
return false;
}
try {
Method isTerminal = Console.class.getMethod("isTerminal");
stalep marked this conversation as resolved.
Show resolved Hide resolved
try {
return (boolean) isTerminal.invoke(console);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Failed to invoke System.console().isTerminal() via Reflection API", e);
return false;
}
} catch (NoSuchMethodException e) {
return true; // for Java <= 21
}
}
}