java.io.Console Java Examples

The following examples show how to use java.io.Console. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: micro-integrator   Author: wso2   File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve value via the console
 *
 * @param msg        message to display in the inquiry
 * @param isPassword is the requested value a password or not
 * @return value provided by the user
 */
public static String getValueFromConsole(String msg, boolean isPassword) {
    Console console = System.console();
    if (console != null) {
        if (isPassword) {
            char[] password;
            if ((password = console.readPassword("[%s]", msg)) != null) {
                return String.valueOf(password);
            }
        } else {
            String value;
            if ((value = console.readLine("[%s]", msg)) != null) {
                return value;
            }
        }
    }
    throw new SecureVaultException("String cannot be null");
}
 
Example #2
Source Project: synopsys-detect   Author: blackducksoftware   File: InteractiveManager.java    License: Apache License 2.0 6 votes vote down vote up
public List<InteractiveOption> configureInInteractiveMode(final InteractiveMode interactiveMode) {
    // Using an UncloseablePrintStream so we don't accidentally close System.out
    try (final PrintStream interactivePrintStream = new UncloseablePrintStream(System.out)) {
        final InteractiveReader interactiveReader;
        final Console console = System.console();

        if (console != null) {
            interactiveReader = new ConsoleInteractiveReader(console);
        } else {
            logger.warn("It may be insecure to enter passwords because you are running in a virtual console.");
            interactiveReader = new ScannerInteractiveReader(System.in);
        }

        interactiveMode.init(interactivePrintStream, interactiveReader);

        interactiveMode.println("");
        interactiveMode.println("Interactive flag found.");
        interactiveMode.println("Starting default interactive mode.");
        interactiveMode.println("");

        interactiveMode.configure();
        return interactiveMode.getInteractiveOptions();
    }
}
 
Example #3
Source Project: aion   Author: aionnetwork   File: Cli.java    License: MIT License 6 votes vote down vote up
private String getCertPass(Console console) {
    int minPassLen = 7;
    String certPass =
            String.valueOf(
                    console.readPassword(
                            "Enter certificate password (at least "
                                    + minPassLen
                                    + " characters):\n"));
    if (certPass.isEmpty()) {
        System.out.println("Error: no certificate password entered.");
        System.exit(SystemExitCodes.INITIALIZATION_ERROR);
    } else if (certPass.length() < minPassLen) {
        System.out.println(
                "Error: certificate password must be at least "
                        + minPassLen
                        + " characters long.");
        System.exit(SystemExitCodes.INITIALIZATION_ERROR);
    }
    return certPass;
}
 
Example #4
Source Project: Learn-Java-12-Programming   Author: PacktPublishing   File: ConsoleDemo.java    License: MIT License 6 votes vote down vote up
private static void console2(){
    System.out.println("\nconsole2:");
    Console console = System.console();

    String line = console.readLine();
    System.out.println("Entered 1: " + line);
    line = console.readLine("Enter something 2: ");
    System.out.println("Entered 2: " + line);
    line = console.readLine("Enter some%s", "thing 3: ");
    System.out.println("Entered 3: " + line);

    char[] password = console.readPassword();
    System.out.println("Entered 4: " + new String(password));
    password = console.readPassword("Enter password 5: ");
    System.out.println("Entered 5: " + new String(password));
    password = console.readPassword("Enter pass%s", "word 6: ");
    System.out.println("Entered 6: " + new String(password));
}
 
Example #5
Source Project: PoseidonX   Author: ucarGroup   File: DefaultEncrypt.java    License: Apache License 2.0 6 votes vote down vote up
private static String encrypt() throws IOException, StreamingException
{
    Console console = System.console();
    if (console == null) {
        throw new IOException("Can not get System console. maybe it running in an IDE.");
    }

    char[] passwordArray = console.readPassword(DEFAULT_CLI_TIP);
    if(passwordArray == null || passwordArray.length == 0)
    {
        throw new IOException("User input can not be null.");
    }

    try
    {
        return new com.huawei.streaming.encrypt.NoneEncrypt().encrypt(new String(passwordArray));
    }
    finally
    {
        //密码使用结束之后清空密码数组
        Arrays.fill(passwordArray, ' ');
    }
}
 
Example #6
Source Project: tmc-cli   Author: testmycode   File: TerminalIo.java    License: MIT License 6 votes vote down vote up
@Override
public String readPassword(String prompt) {
    Console console = System.console();
    if (console != null) {
        try {
            return new String(console.readPassword(prompt));
        } catch (Exception e) {
            logger.warn("Password could not be read.", e);
        }
    } else {
        logger.warn("Failed to read password due to System.console()");
    }
    println("Unable to read password securely. Reading password in cleartext.");
    println("Press Ctrl+C to abort");
    return readLine(prompt);
}
 
Example #7
Source Project: hub-detect   Author: blackducksoftware   File: InteractiveManager.java    License: Apache License 2.0 6 votes vote down vote up
public void configureInInteractiveMode(InteractiveMode interactiveMode) {
    // TODO: Find a way to close the PrintStream without closing System.out
    // DO NOT CLOSE THIS STREAM, IT WILL CLOSE SYSOUT!
    final PrintStream interactivePrintStream = new PrintStream(System.out);
    final InteractiveReader interactiveReader;
    final Console console = System.console();

    if (console != null) {
        interactiveReader = new ConsoleInteractiveReader(console);
    } else {
        logger.warn("It may be insecure to enter passwords because you are running in a virtual console.");
        interactiveReader = new ScannerInteractiveReader(System.in);
    }

    interactiveMode.init(interactivePrintStream, interactiveReader);

    interactiveMode.println("");
    interactiveMode.println("Interactive flag found.");
    interactiveMode.println("Starting default interactive mode.");
    interactiveMode.println("");

    interactiveMode.configure();
    final List<InteractiveOption> interactiveOptions = interactiveMode.getInteractiveOptions();
    detectOptionManager.applyInteractiveOptions(interactiveOptions);

}
 
Example #8
Source Project: mumbler   Author: cesquivias   File: TruffleMumblerMain.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static void startREPL() throws IOException {
    Console console = System.console();
    while (true) {
        // READ
        String data = console.readLine(PROMPT);
        if (data == null) {
            // EOF sent
            break;
        }
        MumblerContext context = new MumblerContext();
        Source source = Source.newBuilder(ID, data, "<console>").build();
        ListSyntax sexp = Reader.read(source);
        Converter converter = new Converter(null, flags.tailCallOptimizationEnabled);
        MumblerNode[] nodes = converter.convertSexp(context, sexp);

        // EVAL
        Object result = execute(nodes, context.getGlobalFrame());

        // PRINT
        if (result != MumblerList.EMPTY) {
            System.out.println(result);
        }
    }
}
 
Example #9
Source Project: tomcat-vault   Author: web-servers   File: VaultInteractiveSession.java    License: Apache License 2.0 6 votes vote down vote up
public static char[] getSensitiveValue(String passwordPrompt) {
    while (true) {
        if (passwordPrompt == null)
            passwordPrompt = "Enter your password";

        Console console = System.console();

        char[] passwd = console.readPassword(passwordPrompt + ": ");
        char[] passwd1 = console.readPassword(passwordPrompt + " again: ");
        boolean noMatch = !Arrays.equals(passwd, passwd1);
        if (noMatch)
            System.out.println("Values entered don't match");
        else {
            System.out.println("Values match");
            return passwd;
        }
    }
}
 
Example #10
Source Project: rundeck-cli   Author: rundeck   File: Util.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Use console to prompt user for input
 *
 * @param prompt  prompt string
 * @param handler input handler, returns parsed value, or empty to prompt again
 * @param defval  default value to return if no input available or user cancels input
 * @param <T>     result type
 * @return result
 */
public static <T> T readPrompt(String prompt, Function<String, Optional<T>> handler, T defval) {
    Console console = System.console();
    if (null == console) {
        return defval;
    }
    while (true) {
        String load = console.readLine(prompt);
        if (null == load) {
            return defval;
        }
        Optional<T> o = handler.apply(load.trim());
        if (o.isPresent()) {
            return o.get();
        }
    }
}
 
Example #11
Source Project: rundeck-cli   Author: rundeck   File: Projects.java    License: Apache License 2.0 6 votes vote down vote up
@Command(description = "Delete a project")
public boolean delete(ProjectDelete options, CommandOutput output) throws IOException, InputError {
    String project = projectOrEnv(options);
    if (!options.isConfirm()) {
        //request confirmation
        Console console = System.console();
        String s = "n";
        if (null != console) {
            s = console.readLine("Really delete project %s? (y/N) ", project);
        } else {
            output.warning("No console input available, and --confirm/-y was not set.");
        }

        if (!"y".equals(s)) {
            output.warning(String.format("Not deleting project %s.", project));
            return false;
        }
    }
    apiCall(api -> api.deleteProject(project));
    output.info(String.format("Project was deleted: %s%n", project));
    return true;
}
 
Example #12
Source Project: knox   Author: apache   File: AbstractJavaConsoleCredentialCollector.java    License: Apache License 2.0 5 votes vote down vote up
protected String collectHiddenCredential(String prompt) {
  char[] response;
  Console c = System.console();
  if (c == null) {
    System.err.println("No console.");
    System.exit(1);
  }

  response = c.readPassword(prompt);
  value = new String(response);

  return value;
}
 
Example #13
Source Project: xipki   Author: xipki   File: IoUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static char[] readPasswordFromConsole(String prompt) {
  Console console = System.console();
  if (console == null) {
    throw new IllegalStateException("No console is available for input");
  }
  System.out.println(prompt == null ? "Enter the password" : prompt);
  return console.readPassword();
}
 
Example #14
Source Project: Xpatch   Author: WindySha   File: PasswordRetriever.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the character encoding used by the console or {@code null} if the encoding is not
 * known.
 */
private static Charset getConsoleEncoding() {
    // IMPLEMENTATION NOTE: There is no public API for obtaining the console's character
    // encoding. We thus cheat by using implementation details of the most popular JVMs.
    // Unfortunately, this doesn't work on Java 9 JVMs where access to Console.encoding is
    // restricted by default and leads to spewing to stdout at runtime.
    if (isJava9OrHigherErrOnTheSideOfCaution()) {
        return null;
    }
    String consoleCharsetName = null;
    try {
        Method encodingMethod = Console.class.getDeclaredMethod("encoding");
        encodingMethod.setAccessible(true);
        consoleCharsetName = (String) encodingMethod.invoke(null);
    } catch (ReflectiveOperationException ignored) {
        return null;
    }

    if (consoleCharsetName == null) {
        // Console encoding is the same as this JVM's default encoding
        return Charset.defaultCharset();
    }

    try {
        return getCharsetByName(consoleCharsetName);
    } catch (IllegalArgumentException e) {
        return null;
    }
}
 
Example #15
Source Project: aion   Author: aionnetwork   File: Aion.java    License: MIT License 5 votes vote down vote up
private static char[] getSslPassword(CfgAion cfg) {
    CfgSsl sslCfg = cfg.getApi().getRpc().getSsl();
    char[] sslPass = sslCfg.getPass();
    // interactively ask for a password for the ssl file if they did not set on in the config
    // file
    if (sslCfg.getEnabled() && sslPass == null) {
        Console console = System.console();
        // https://docs.oracle.com/javase/10/docs/api/java/io/Console.html
        // if the console does not exist, then either:
        // 1) jvm's underlying platform does not provide console
        // 2) process started in non-interactive mode (background scheduler, redirected output,
        // etc.)
        // don't wan't to compromise security in these scenarios
        if (console == null) {
            System.out.println(
                    "SSL-certificate-use requested with RPC server and no console found. "
                            + "Please set the ssl password in the config file (insecure) to run kernel non-interactively with this option.");
            System.exit(SystemExitCodes.INITIALIZATION_ERROR);
        } else {
            console.printf("---------------------------------------------\n");
            console.printf("----------- INTERACTION REQUIRED ------------\n");
            console.printf("---------------------------------------------\n");
            sslPass =
                    console.readPassword(
                            "Password for SSL keystore file [" + sslCfg.getCert() + "]\n");
        }
    }

    return sslPass;
}
 
Example #16
Source Project: aion   Author: aionnetwork   File: PasswordReader.java    License: MIT License 5 votes vote down vote up
/**
 * Returns a password after prompting the user to enter it. This method attempts first to read
 * user input from a console environment and if one is not available it instead attempts to read
 * from reader.
 *
 * @param prompt The read-password prompt to display to the user.
 * @return The user-entered password.
 * @throws NullPointerException if prompt is null or if console unavailable and reader is null.
 */
public String readPassword(String prompt, BufferedReader reader) {
    if (prompt == null) {
        throw new NullPointerException("readPassword given null prompt.");
    }

    Console console = System.console();
    if (console == null) {
        return readPasswordFromReader(prompt, reader);
    }
    return new String(console.readPassword(prompt));
}
 
Example #17
Source Project: aion   Author: aionnetwork   File: Cli.java    License: MIT License 5 votes vote down vote up
/** For security reasons we only want the ssl option to run in a console environment. */
private void checkConsoleExists(Console console) {
    if (console == null) {
        System.out.println(
                "No console found. This command can only be run interactively in a console environment.");
        System.exit(SystemExitCodes.INITIALIZATION_ERROR);
    }
}
 
Example #18
Source Project: ranger   Author: apache   File: ConsoleUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Ask a password from console, and return as a char array.
 * @param prompt the question which is prompted
 * @return the password.
 */

static char[] getPasswordFromConsole(String prompt) throws IOException {
    char pwd[]=null;
    Console c = System.console();
    if (c == null) {
        System.out.print(prompt + " ");
        InputStream in = System.in;
        int max = 50;
        byte[] b = new byte[max];
        int l = in.read(b);
        l--; // last character is \n
        pwd=new char[l];
        if (l > 0) {
            byte[] e = new byte[l];
            System.arraycopy(b, 0, e, 0, l);
            for (int i = 0; i < l; i++) {
                pwd[i] = (char) e[i];
            }
        }
    } else {
        pwd = c.readPassword(prompt + " ");
        if (pwd == null) {
            pwd = new char[0];
        }
    }
    return pwd;
}
 
Example #19
Source Project: jql   Author: benas   File: Shell.java    License: MIT License 5 votes vote down vote up
private static Console getConsole() {
    Console console = System.console();
    if (console == null) {
        System.err.print("No console available.");
        System.exit(1);
    }
    return console;
}
 
Example #20
Source Project: emissary   Author: NationalSecurityAgency   File: RubyConsole.java    License: Apache License 2.0 5 votes vote down vote up
public void shell() {
    // JDK 1.6 +
    Console jconsole = System.console();
    if (jconsole == null) {
        System.out.println("no tty");
        return;
    }

    // Put some nice words on screen for the user
    System.out.println("Emissary Ruby Console v" + new emissary.util.Version());
    String input;
    do {
        try {
            System.out.print(getPrompt());
            input = jconsole.readLine();
            if (input == null || input.equals("quit")) {
                break;
            }

            if (input.equals("reset")) {
                reset();
                continue;
            }

            evalConsoleInput(input, true);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    } while (true);
}
 
Example #21
Source Project: hugegraph   Author: hugegraph   File: StandardAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
private String inputPassword() {
    String prompt = "Please input the admin password:";
    Console console = System.console();
    if (console != null) {
        char[] chars = console.readPassword(prompt);
        return new String(chars);
    } else {
        System.out.print(prompt);
        @SuppressWarnings("resource")
        Scanner scanner = new Scanner(System.in);
        return scanner.nextLine();
    }
}
 
Example #22
Source Project: tessera   Author: jpmorganchase   File: PasswordReaderFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static PasswordReader create() {

        final Console console = System.console();

        if(console == null) {
            return new InputStreamPasswordReader(System.in);
        } else {
            return new ConsolePasswordReader(console);
        }

    }
 
Example #23
Source Project: google-ads-java   Author: googleads   File: AuthenticateInStandaloneApplication.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
  // Generates the client ID and client secret from the Google Cloud Console:
  // https://console.cloud.google.com
  String clientId;
  String clientSecret;

  Console console = System.console();
  if (console == null) {
    // The console will be null when running this example in some IDEs. In this case, please
    // set the clientId and clientSecret in the lines below.
    clientId = "INSERT_CLIENT_ID_HERE";
    clientSecret = "INSERT_CLIENT_SECRET_HERE";
    // Ensures that the client ID and client secret are not the "INSERT_..._HERE" values.
    Preconditions.checkArgument(
        !clientId.matches("INSERT_.*_HERE"),
        "Client ID is invalid. Please update the example and try again.");
    Preconditions.checkArgument(
        !clientSecret.matches("INSERT_.*_HERE"),
        "Client secret is invalid. Please update the example and try again.");
  } else {
    console.printf(
        "NOTE: When prompting for the client secret below, echoing will be disabled%n");
    console.printf("      since the client secret is sensitive information.%n");
    console.printf("Enter your client ID:%n");
    clientId = console.readLine();
    console.printf("Enter your client secret:%n");
    clientSecret = String.valueOf(console.readPassword());
  }

  new AuthenticateInStandaloneApplication().runExample(clientId, clientSecret);
}
 
Example #24
Source Project: knox   Author: apache   File: WebHDFSCommand.java    License: Apache License 2.0 5 votes vote down vote up
private String collectClearInput(String prompt) {
  Console c = System.console();
  if (c == null) {
    System.err.println("No console.");
    System.exit(1);
  }

  String value = c.readLine(prompt);

  return value;
}
 
Example #25
Source Project: sis   Author: apache   File: ParameterFormat.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Writes the given object to the console using a shared instance of {@code ParameterFormat}.
 */
@SuppressWarnings("UseOfSystemOutOrSystemErr")
static void print(final Object object) {
    final Console console = System.console();
    final Appendable out = (console != null) ? console.writer() : System.out;
    final ParameterFormat f = getSharedInstance(Colors.NAMING);
    try {
        f.format(object, out);
    } catch (IOException e) {
        throw new UncheckedIOException(e);      // Should never happen since we are writing to stdout.
    }
    INSTANCE.set(f);
}
 
Example #26
Source Project: gemfirexd-oss   Author: gemxd   File: GfxdServerLauncher.java    License: Apache License 2.0 5 votes vote down vote up
protected void readPassword(Map<String, String> envArgs) throws Exception {
  final Console cons = System.console();
  if (cons == null) {
    throw new IllegalStateException(
        "No console found for reading the password.");
  }
  final char[] pwd = cons.readPassword(LocalizedResource
      .getMessage("UTIL_password_Prompt"));
  if (pwd != null) {
    final String passwd = new String(pwd);
    // encrypt the password with predefined key that is salted with host IP
    final byte[] keyBytes = getBytesEnv();
    envArgs.put(ENV1, GemFireXDUtils.encrypt(passwd, null, keyBytes));
  }
}
 
Example #27
Source Project: keycloak   Author: keycloak   File: AddUser.java    License: Apache License 2.0 5 votes vote down vote up
private static String promptForInput() throws Exception {
    Console console = System.console();
    if (console == null) {
        throw new Exception("Couldn't get Console instance");
    }
    console.printf("Press ctrl-d (Unix) or ctrl-z (Windows) to exit\n");
    char passwordArray[] = console.readPassword("Password: ");

    if(passwordArray == null) System.exit(0);

    return new String(passwordArray);
}
 
Example #28
Source Project: sis   Author: apache   File: ShapeUtilitiesViewer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new panel where to paint the input and output values.
 */
@SuppressWarnings("UseOfSystemOutOrSystemErr")
private ShapeUtilitiesViewer() {
    setBackground(Color.BLACK);
    input  = new Path2D.Float();
    output = new Path2D.Float();
    random = new Random();
    final Console console = System.console();
    out = (console != null) ? console.writer() : new PrintWriter(System.out);
}
 
Example #29
Source Project: trygve   Author: jcoplien   File: InputStreamClass.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override public void keyTyped(KeyEvent e) {
    final int c = e.getKeyChar();
    try {
        queue.put(c);
    } catch (InterruptedException ex) {
        Logger.getLogger(Console.class.getName()).
                log(Level.SEVERE, null, ex);
    }
}
 
Example #30
Source Project: tutorials   Author: eugenp   File: ConsoleCallbackHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    Console console = System.console();
    for (Callback callback : callbacks) {
        if (callback instanceof NameCallback) {
            NameCallback nameCallback = (NameCallback) callback;
            nameCallback.setName(console.readLine(nameCallback.getPrompt()));
        } else if (callback instanceof PasswordCallback) {
            PasswordCallback passwordCallback = (PasswordCallback) callback;
            passwordCallback.setPassword(console.readPassword(passwordCallback.getPrompt()));
        } else {
            throw new UnsupportedCallbackException(callback);
        }
    }
}