Example usage for java.lang System console

List of usage examples for java.lang System console

Introduction

In this page you can find the example usage for java.lang System console.

Prototype

public static Console console() 

Source Link

Document

Returns the unique java.io.Console Console object associated with the current Java virtual machine, if any.

Usage

From source file:examples.mail.IMAPUtils.java

/**
 * Parse the URI and use the details to connect to the IMAP(S) server and login.
 *
 * @param uri the URI to use, e.g. imaps://user:pass@imap.mail.yahoo.com/folder
 * or imaps://user:pass@imap.googlemail.com/folder
 * @param defaultTimeout initial timeout (in milliseconds)
 * @param listener for tracing protocol IO (may be null)
 * @return the IMAP client - connected and logged in
 * @throws IOException if any problems occur
 *///from  ww w  .  j a v  a2s . co m
static IMAPClient imapLogin(URI uri, int defaultTimeout, ProtocolCommandListener listener) throws IOException {
    final String userInfo = uri.getUserInfo();
    if (userInfo == null) {
        throw new IllegalArgumentException("Missing userInfo details");
    }

    String[] userpass = userInfo.split(":");
    if (userpass.length != 2) {
        throw new IllegalArgumentException("Invalid userInfo details: '" + userInfo + "'");
    }

    String username = userpass[0];
    String password = userpass[1];
    /*
     * If the initial password is:
     * '*' - replace it with a line read from the system console
     * '-' - replace it with next line from STDIN
     * 'ABCD' - if the input is all upper case, use the field as an environment variable name
     *
     * Note: there are no guarantees that the password cannot be snooped.
     *
     * Even using the console may be subject to memory snooping,
     * however it should be safer than the other methods.
     *
     * STDIN may require creating a temporary file which could be read by others
     * Environment variables may be visible by using PS
     */
    if ("-".equals(password)) { // stdin
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        password = in.readLine();
    } else if ("*".equals(password)) { // console
        Console con = System.console(); // Java 1.6
        if (con != null) {
            char[] pwd = con.readPassword("Password for " + username + ": ");
            password = new String(pwd);
        } else {
            throw new IOException("Cannot access Console");
        }
    } else if (password.equals(password.toUpperCase(Locale.ROOT))) { // environment variable name
        final String tmp = System.getenv(password);
        if (tmp != null) { // don't overwrite if variable does not exist (just in case password is all uppers)
            password = tmp;
        }
    }

    final IMAPClient imap;

    final String scheme = uri.getScheme();
    if ("imaps".equalsIgnoreCase(scheme)) {
        System.out.println("Using secure protocol");
        imap = new IMAPSClient(true); // implicit
    } else if ("imap".equalsIgnoreCase(scheme)) {
        imap = new IMAPClient();
    } else {
        throw new IllegalArgumentException("Invalid protocol: " + scheme);
    }
    final int port = uri.getPort();
    if (port != -1) {
        imap.setDefaultPort(port);
    }

    imap.setDefaultTimeout(defaultTimeout);

    if (listener != null) {
        imap.addProtocolCommandListener(listener);
    }

    final String server = uri.getHost();
    System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort());

    try {
        imap.connect(server);
        System.out.println("Successfully connected");
    } catch (IOException e) {
        throw new RuntimeException("Could not connect to server.", e);
    }

    if (!imap.login(username, password)) {
        imap.disconnect();
        throw new RuntimeException("Could not login to server. Check login details.");
    }

    return imap;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.standalone.StandaloneShutdownDialog.java

private void displayShutdownDialog() {
    String serverId = ServerDetector.getServerId();
    log.info("Running in: " + (serverId != null ? serverId : "unknown server"));
    log.info("Console: " + ((System.console() != null) ? "available" : "not available"));
    log.info("Headless: " + (GraphicsEnvironment.isHeadless() ? "yes" : "no"));

    // Show this only when run from the standalone JAR via a double-click
    if (System.console() == null && !GraphicsEnvironment.isHeadless() && ServerDetector.isWinstone()) {
        log.info("If you are running WebAnno in a server environment, please use '-Djava.awt.headless=true'");

        EventQueue.invokeLater(new Runnable() {
            @Override//ww w .  ja  v a  2s.c o  m
            public void run() {
                final JOptionPane optionPane = new JOptionPane(new JLabel(
                        "<HTML>WebAnno is running now and can be accessed via <a href=\"http://localhost:8080\">http://localhost:8080</a>.<br>"
                                + "WebAnno works best with the browsers Google Chrome or Safari.<br>"
                                + "Use this dialog to shut WebAnno down.</HTML>"),
                        JOptionPane.INFORMATION_MESSAGE, JOptionPane.OK_OPTION, null,
                        new String[] { "Shutdown" });

                final JDialog dialog = new JDialog((JFrame) null, "WebAnno", true);
                dialog.setContentPane(optionPane);
                dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                dialog.addWindowListener(new WindowAdapter() {
                    @Override
                    public void windowClosing(WindowEvent we) {
                        // Avoid closing window by other means than button
                    }
                });
                optionPane.addPropertyChangeListener(new PropertyChangeListener() {
                    @Override
                    public void propertyChange(PropertyChangeEvent aEvt) {
                        if (dialog.isVisible() && (aEvt.getSource() == optionPane)
                                && (aEvt.getPropertyName().equals(JOptionPane.VALUE_PROPERTY))) {
                            System.exit(0);
                        }
                    }
                });
                dialog.pack();
                dialog.setVisible(true);
            }
        });
    } else {
        log.info("Running in server environment or from command line: disabling interactive shutdown dialog.");
    }
}

From source file:com.linkedin.bowser.tool.REPLCommandLine.java

public void doRun() throws Exception {
    StringBuilder line = new StringBuilder();
    Console console = System.console();

    while (true) {
        String input;//w ww  .  ja  v a  2 s. c o m
        if (line.length() > 0) {
            input = console.readLine(_dots);
        } else {
            input = console.readLine(_prompt);
            if ("quit".equals(input) || "exit".equals(input))
                break;
        }

        if (input.endsWith("\\")) {
            line.append(input.substring(0, input.length() - 1));
            line.append("\n");
            continue;
        }

        if (line.length() > 0) {
            input = line.toString() + input;
            line = new StringBuilder();
        }

        try {
            _repl.execute(input, System.out);
        } catch (QueryRuntimeException e) {
            System.err.println(e.getMessage());
        } catch (QueryFormatException e) {
            System.err.println(e.getMessage());
        }
    }
}

From source file:net.alegen.datpass.cli.input.PasswordCommand.java

@Override
public void execute() {
    try {//from  w w w. j av a  2s  . co m
        CommandLineParser parser = new PosixParser();
        String[] arrayArgs = new String[this.args.size()];
        this.args.toArray(arrayArgs);
        CommandLine line = parser.parse(this.options, arrayArgs);
        String input = "";
        int length = -1;
        if (line.hasOption(OPTION_INPUT))
            input = line.getOptionValue(OPTION_INPUT);
        else {
            System.out.print("Input: ");
            input = String.valueOf(System.console().readPassword());
        }
        if (line.hasOption(OPTION_LENGTH))
            length = Integer.parseInt(line.getOptionValue(OPTION_LENGTH));
        else
            length = 100;
        String password = Generator.getInstance().password(input, length);
        if (Settings.echo())
            System.out.println(password);
        if (Settings.clipboard())
            ClipboardHandler.getInstance().set(password);
    } catch (Generator.GeneratorException e) {

    } catch (ParseException e) {

    }
}

From source file:io.stallion.users.UserAdder.java

public void execute(CommandOptionsBase options, String action) throws Exception {

    Log.info("Settings: siteName {0} email password {1}", Settings.instance().getSiteName(),
            Settings.instance().getEmail().getPassword());

    Scanner scanner = new Scanner(System.in);
    Console console = System.console();

    if (empty(action)) {
        //System.out.print("Create new user or edit existing? (new/edit): ");

        //String newEdit = scanner.next();

        System.out.print("Create new user or edit existing? (new/edit): ");
        //String newEdit = console.readLine("Create new user or edit existing? (new/edit): ");
        action = scanner.nextLine();/*from   w  ww .j ava2 s. c o  m*/
    }
    User user = null;
    if ("new".equals(action)) {
        user = new User();
        user.setPredefined(true);
    } else if ("edit".equals(action)) {
        System.out.print("Enter the email, username, or ID of the user you wish to edit:");
        String idMaybe = scanner.next();
        if (StringUtils.isNumeric(idMaybe)) {
            user = (User) UserController.instance().forId(Long.parseLong(idMaybe));
        }
        if (user == null) {
            user = (User) UserController.instance().forUniqueKey("email", idMaybe);
        }
        if (user == null) {
            user = (User) UserController.instance().forUniqueKey("username", idMaybe);
        }
        if (user == null) {
            System.out.print("Could not find user for key: " + idMaybe);
            System.exit(1);
        }
    } else {
        System.out.print("Invalid choice. Choose either 'new' or 'edit'");
        System.exit(1);
    }

    System.out.print("User's given name: ");
    String givenName = scanner.nextLine();
    if (!empty(givenName)) {
        user.setGivenName(givenName);
    }

    System.out.print("User's family name: ");
    String familyName = scanner.nextLine();
    if (!empty(familyName)) {
        user.setFamilyName(familyName);
        user.setDisplayName(user.getGivenName() + " " + user.getFamilyName());
    }

    System.out.print("User's email: ");
    String email = scanner.nextLine();
    if (!empty(email)) {
        user.setEmail(email);
        user.setUsername(user.getEmail());
    }

    System.out.print("Enter password: ");
    String password = "";
    if (console != null) {
        password = new String(console.readPassword());
    } else {
        password = new String(scanner.nextLine());
    }
    //System.out.printf("password: \"%s\"\n", password);
    if (empty(password) && empty(user.getBcryptedPassword())) {
        throw new UsageException("You must set a password!");
    } else if (!empty(password)) {
        String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
        user.setBcryptedPassword(hashed);
    }

    if (empty(user.getSecret())) {
        user.setSecret(RandomStringUtils.randomAlphanumeric(18));
    }
    if (empty(user.getEncryptionSecret())) {
        user.setEncryptionSecret(RandomStringUtils.randomAlphanumeric(36));
    }

    user.setPredefined(true);
    user.setRole(Role.ADMIN);
    user.setId(Context.dal().getTickets().nextId());
    user.setFilePath(GeneralUtils.slugify(user.getEmail() + "---" + user.getId().toString()) + ".json");
    UserController.instance().save(user);

    System.out.print("User saved with email " + user.getEmail() + " and id " + user.getId());

}

From source file:io.stallion.utils.Prompter.java

public String prompt() {
    System.out.print(message);/*w ww.  java 2 s  .  c o  m*/
    String line = "";
    if (isPassword && System.console() != null) {
        line = new String(System.console().readPassword());
    } else {
        line = this.scanner.nextLine();
    }
    line = line.trim();
    if (line.length() < minLength && line.length() == 0) {
        lastErrorMessage = "Sorry, your response must be at least " + minLength
                + " character(s) long. Please make a choice.";
        return failAndPromptAgain();
    }
    if (!empty(choices)) {
        if (!choices.contains(line)) {
            lastErrorMessage = "Sorry, that was not one of the allowed choices.\n" + "The allowed choices are: "
                    + StringUtils.join(choices, ", ");

            return failAndPromptAgain();
        }
    }
    if (validPattern != null) {
        if (!validPattern.matcher(line).matches()) {
            lastErrorMessage = "Sorry, that was not a valid entry.";
            return failAndPromptAgain();
        }
    }
    return line;
}

From source file:org.apache.safe.service.KeyStoreBasedKeyService.java

void initialize(InputStream ksfs, InputStream pwdfs) throws IOException {
    Properties passwords = null;/*from ww  w  . j ava  2 s  .co  m*/
    try {
        if (pwdfs != null) {
            passwords = new Properties();
            passwords.load(pwdfs);
        }
        char[] keyStorePassword = null;
        if (passwords != null) {
            String strPassword = passwords.getProperty("keystore.password");
            if (strPassword != null) {
                keyStorePassword = strPassword.toCharArray();
            } else {
                LOG.error("Canot obtain password for keystore");
                throw new IOException("Could not read secrets from keystore");
            }
        } else {
            System.out.println("Enter KeyStore Password: ");
            keyStorePassword = System.console().readPassword();
        }

        keystore = KeyStore.getInstance("JCEKS");
        keystore.load(ksfs, // InputStream to keystore
                keyStorePassword);
        keyStorePP = new PasswordProtection(keyStorePassword);
    } catch (FileNotFoundException e) {
        throw new IOException(e);
    } catch (IOException e) {
        throw new IOException(e);
    } catch (KeyStoreException e) {
        throw new IOException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    } catch (CertificateException e) {
        throw new IOException(e);
    }
}

From source file:org.apache.lens.client.LensClientSingletonWrapper.java

/**
 * Explain failed attempt./*from w  w w . ja va2s . co  m*/
 *
 * @param e the e
 */
public void explainFailedAttempt(LensClientServerConnectionException e) {
    LOG.error("failed login attempt", e);
    switch (e.getErrorCode()) {
    case 401:
        System.console().printf("username/password combination incorrect.\n");
        break;
    case 500:
        System.console().printf("server unresponsive, Returned error code 500\n");
        break;
    default:
        System.console().printf("Unknown error in authenticating with the server. Error code = %d\n",
                e.getErrorCode());
    }
}

From source file:io.stallion.boot.MainRunner.java

/**
 * Runs the main Stallion service in auto-reload mode, which means that if a configuration file,
 * or a server-side javascript file, or a plugin file is touched, the entire application context
 * will reload and all server-side javascript will be re-processed. Use this when developing
 * to avoid having to manually restart every time you change a file.
 *
 *
 * @param args/* w w  w  .j av a  2s .c o m*/
 * @param plugins
 * @throws Exception
 */
public static void runWithAutoReload(String[] args, StallionJavaPlugin[] plugins) throws Exception {
    isDebugRunner = true;

    Console console = System.console();
    while (true) {
        Log.info("(re)start in debug reloading mode.");
        try {
            reboot(args, plugins);
            if (doReload) {
                doReload = false;
                continue;
            }
            System.out.println("Interrupted. Type q to quit, any other key to reboot.");
            String input = console.readLine();
            if (input.startsWith("q")) {
                break;
            }
        } catch (Exception e) {
            ExceptionUtils.printRootCauseStackTrace(e);
            System.out.println("Other exception. Type q to quit, any other key to reboot.");
            String input = console.readLine();
            if (input.startsWith("q")) {
                break;
            }
        }
    }
    Log.info("Shutting down javascript and conf file watcher.");
    if (watcher != null) {
        watcher.setShouldRun(false);
    }
    watcherThread.interrupt();
    watcherThread.join();
    System.out.println("Exiting.");
    System.exit(0);
}

From source file:com.github.mavogel.ilias.utils.ConfigurationsUtils.java

/**
 * Creates the login configuration and uses defaults if necessary.
 *
 * @param propertyFilename the name of the property file
 * @return the {@link LoginConfiguration}
 *//*from  www. j  a  v  a  2 s . c o  m*/
public static LoginConfiguration createLoginConfiguration(final String propertyFilename) {
    Parameters params = new Parameters();
    FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>(
            PropertiesConfiguration.class).configure(params.properties().setFileName(propertyFilename));
    LoginConfiguration.LOGIN_MODE loginMode = null;
    String endpoint, client, username, password, loginModeRaw = "";
    int maxFolderDepth;
    Level logLevel;

    try {
        Configuration config = builder.getConfiguration();
        loginModeRaw = config.getString("login.mode");
        loginMode = LoginConfiguration.LOGIN_MODE.valueOf(loginModeRaw);
        endpoint = config.getString("endpoint");
        client = config.getString("login.client");
        username = config.getString("login.username");
        password = config.getString("login.password");
        maxFolderDepth = config.getString("maxFolderDepth", String.valueOf(Defaults.MAX_FOLDER_DEPTH)).isEmpty()
                ? Defaults.MAX_FOLDER_DEPTH
                : Integer
                        .valueOf(config.getString("maxFolderDepth", String.valueOf(Defaults.MAX_FOLDER_DEPTH)));
        logLevel = Level.toLevel(config.getString("log.level", Defaults.LOG_LEVEL.toString()),
                Defaults.LOG_LEVEL);
        if (password == null || password.isEmpty()) {
            Console console = System.console();
            if (console != null) {
                password = String.valueOf(console.readPassword("Enter your password: "));
            } else {
                throw new Exception("Console is not available!");
            }
        }
    } catch (IllegalArgumentException iae) {
        throw new RuntimeException(String.format("Login mode '%s' is unknown. Use one of %s", loginModeRaw,
                Arrays.stream(LoginConfiguration.LOGIN_MODE.values()).map(lm -> lm.name())
                        .collect(Collectors.joining(", "))));
    } catch (ConversionException ce) {
        throw new RuntimeException("maxFolderDepth property is not an integer");
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

    // == 1: set log level
    Logger.getRootLogger().setLevel(logLevel);

    // == 2: create login configuration
    switch (loginMode) {
    case STD:
        return LoginConfiguration.asStandardLogin(endpoint, client, username, password, maxFolderDepth);
    case LDAP:
        return LoginConfiguration.asLDAPLogin(endpoint, client, username, password, maxFolderDepth);
    case CAS:
        return LoginConfiguration.asCASLogin();
    default:
        // should not happen
        return null;
    }
}