tdlight-java/tdlight-java/src/main/java/it/tdlight/util/ScannerUtils.java

60 lines
1.6 KiB
Java
Raw Normal View History

2023-05-10 10:12:43 +02:00
package it.tdlight.util;
2020-04-19 16:32:49 +02:00
2021-10-24 00:12:01 +02:00
import java.io.Console;
2021-10-24 00:22:47 +02:00
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
2021-10-24 00:12:01 +02:00
2021-09-27 19:27:13 +02:00
public final class ScannerUtils {
2021-10-24 00:22:47 +02:00
private static final Object LOCK = new Object();
private static InputStreamReader scanner = null;
2021-10-24 00:12:01 +02:00
2020-04-19 16:32:49 +02:00
public static String askParameter(String displayName, String question) {
2021-10-24 00:22:47 +02:00
synchronized (LOCK) {
Console console = System.console();
if (console != null) {
return console.readLine("[%s] %s: ", displayName, question);
2021-10-24 00:22:47 +02:00
} else {
if (scanner == null) {
scanner = new InputStreamReader(System.in);
2021-10-24 00:12:01 +02:00
}
2021-10-24 00:22:47 +02:00
System.out.printf("[%s] %s: ", displayName, question);
try {
return interruptibleReadLine(scanner);
} catch (InterruptedException | IOException e) {
throw new RuntimeException(e);
}
}
}
}
/**
* https://stackoverflow.com/questions/3595926/how-to-interrupt-bufferedreaders-readline
*/
private static String interruptibleReadLine(Reader reader) throws InterruptedException, IOException {
Pattern line = Pattern.compile("^(.*)\\R");
Matcher matcher;
boolean interrupted;
StringBuilder result = new StringBuilder();
int chr = -1;
do {
if (reader.ready()) {
chr = reader.read();
}
if (chr > -1) {
result.append((char) chr);
2021-10-24 00:12:01 +02:00
}
2021-10-24 00:22:47 +02:00
matcher = line.matcher(result.toString());
interrupted = Thread.interrupted(); // resets flag, call only once
} while (!interrupted && !matcher.matches());
if (interrupted) {
throw new InterruptedException();
2021-10-24 00:12:01 +02:00
}
2021-10-24 00:22:47 +02:00
return (matcher.matches() ? matcher.group(1) : "");
2020-04-19 16:32:49 +02:00
}
}