Search in sources :

Example 16 with Console

use of java.io.Console in project ceylon-compiler by ceylon.

the class CeylonVersionTool method confirm.

/**
     * Issues a confirmation
     * @param prompt
     * @return null means quit, empty string means no, anything else is the version string to use.
     * @throws IOException 
     */
private String confirm(String msgKey, Object... args) throws IOException {
    if (confirm == Confirm.none) {
        return this.newVersion;
    }
    String version = this.newVersion;
    Console console = System.console();
    while (true) {
        prompt: while (true) {
            // XXX Ugly: Need to replace the new version within the args array 
            args[args.length - 1] = version;
            console.printf("%s", CeylonVersionMessages.msg(msgKey, args));
            String ch = console.readLine();
            if (ch.equals(CeylonVersionMessages.msg("mnemonic.yes"))) {
                return version;
            } else if (ch.equals(CeylonVersionMessages.msg("mnemonic.help"))) {
                out.append(CeylonVersionMessages.msg("help")).append(System.lineSeparator());
                continue prompt;
            } else if (ch.equals(CeylonVersionMessages.msg("mnemonic.quit"))) {
                return null;
            } else if (ch.equals(CeylonVersionMessages.msg("mnemonic.all"))) {
                this.confirm = Confirm.none;
                return version;
            } else if (ch.equals(CeylonVersionMessages.msg("mnemonic.no"))) {
                return "";
            } else if (ch.equals(CeylonVersionMessages.msg("mnemonic.edit"))) {
                break prompt;
            } else {
                continue prompt;
            }
        }
        console.printf(CeylonVersionMessages.msg("prompt.version"));
        version = console.readLine();
    }
}
Also used : Console(java.io.Console)

Example 17 with Console

use of java.io.Console in project ceylon-compiler by ceylon.

the class PathValidator method getValue.

@Override
public String getValue(String projectName, Environment env) {
    String value;
    while (true) {
        String readLine = null;
        String dv = getDefault(env);
        String prompt = getPrompt(projectName, env, dv);
        if (System.console() != null) {
            Console console = System.console();
            if (console == null) {
                throw new RuntimeException(Messages.msg("no.console"));
            }
            readLine = console.readLine(prompt);
        } else {
            System.out.print(prompt);
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            try {
                readLine = reader.readLine();
            } catch (IOException e) {
            // Ignore
            }
        }
        if (readLine == null) {
            throw new RuntimeException(Messages.msg("exit"));
        } else if (readLine.isEmpty() && dv != null) {
            readLine = dv;
        }
        value = parseValue(readLine);
        if (value != null) {
            break;
        }
    }
    return value;
}
Also used : InputStreamReader(java.io.InputStreamReader) Console(java.io.Console) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException)

Example 18 with Console

use of java.io.Console in project camel by apache.

the class CamelCatalogRestMain method run.

public void run() {
    LOGGER.info("Starting ...");
    catalog = new CamelCatalogRest();
    connectorCatalog = new CamelConnectorCatalogRest();
    // setup Apache CXF REST server
    JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
    sf.setResourceClasses(CamelCatalogRest.class, CamelConnectorCatalogRest.class);
    sf.setResourceProvider(CamelCatalogRest.class, new SingletonResourceProvider(catalog));
    sf.setResourceProvider(CamelConnectorCatalogRest.class, new SingletonResourceProvider(connectorCatalog));
    Swagger2Feature swagger = new Swagger2Feature();
    swagger.setBasePath("/");
    swagger.setScanAllResources(false);
    swagger.setPrettyPrint(true);
    swagger.setSupportSwaggerUi(true);
    swagger.setTitle("Camel Catalog and Connector Catalog REST Api");
    swagger.setDescription("REST Api for the Camel Catalog and Connector Catalog");
    swagger.setVersion(catalog.getCatalogVersion());
    swagger.setContact("Apache Camel");
    sf.getFeatures().add(swagger);
    // to use jackson for json
    sf.setProvider(JacksonJsonProvider.class);
    sf.setAddress("http://localhost:" + port);
    // create and start the CXF server (non blocking)
    server = sf.create();
    server.start();
    LOGGER.info("CamelCatalog REST Api started");
    LOGGER.info("");
    LOGGER.info("\tRest API base path: http://localhost:{}/camel-catalog", port);
    LOGGER.info("\tRest API version: http://localhost:{}/camel-catalog/catalogVersion", port);
    LOGGER.info("");
    LOGGER.info("CamelConnectorCatalog REST Api started");
    LOGGER.info("");
    LOGGER.info("\tRest API base path: http://localhost:{}/camel-connector-catalog", port);
    LOGGER.info("");
    LOGGER.info("\tSwagger Doc: http://localhost:{}/swagger.json", port);
    LOGGER.info("\tSwagger UI: http://localhost:{}/api-docs?url=/swagger.json", port);
    LOGGER.info("");
    LOGGER.info("Press Enter to stop");
    Console console = System.console();
    console.readLine();
    LOGGER.info("Stopping ...");
    server.stop();
    server.destroy();
    LOGGER.info("CamelCatalog REST Api stopped");
    System.exit(0);
}
Also used : JAXRSServerFactoryBean(org.apache.cxf.jaxrs.JAXRSServerFactoryBean) Console(java.io.Console) Swagger2Feature(org.apache.cxf.jaxrs.swagger.Swagger2Feature) SingletonResourceProvider(org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider)

Example 19 with Console

use of java.io.Console in project AndResGuard by shwenzhang.

the class PasswordRetriever method getPasswords.

/**
     * Returns the passwords described by the provided spec. The reason there may be more than one
     * password is compatibility with {@code keytool} and {@code jarsigner} which in certain cases
     * use the form of passwords encoded using the console's character encoding.
     *
     * <p>Supported specs:
     * <ul>
     * <li><em>stdin</em> -- read password as a line from console, if available, or standard
     *     input if console is not available</li>
     * <li><em>pass:password</em> -- password specified inside the spec, starting after
     *     {@code pass:}</li>
     * <li><em>file:path</em> -- read password as a line from the specified file</li>
     * <li><em>env:name</em> -- password is in the specified environment variable</li>
     * </ul>
     *
     * <p>When the same file (including standard input) is used for providing multiple passwords,
     * the passwords are read from the file one line at a time.
     */
public List<char[]> getPasswords(String spec, String description) throws IOException {
    // IMPLEMENTATION NOTE: Java KeyStore and PBEKeySpec APIs take passwords as arrays of
    // Unicode characters (char[]). Unfortunately, it appears that Sun/Oracle keytool and
    // jarsigner in some cases use passwords which are the encoded form obtained using the
    // console's character encoding. For example, if the encoding is UTF-8, keytool and
    // jarsigner will use the password which is obtained by upcasting each byte of the UTF-8
    // encoded form to char. This occurs only when the password is read from stdin/console, and
    // does not occur when the password is read from a command-line parameter.
    // There are other tools which use the Java KeyStore API correctly.
    // Thus, for each password spec, there may be up to three passwords:
    // * Unicode characters,
    // * characters (upcast bytes) obtained from encoding the password using the console's
    //   character encoding,
    // * characters (upcast bytes) obtained from encoding the password using the JVM's default
    //   character encoding.
    //
    // For a sample password "ab¡äю1":
    // On Windows 10 with English US as the UI language, IBM437 is used as console encoding and
    // windows-1252 is used as the JVM default encoding:
    // * keytool -genkey -v -keystore native.jks -keyalg RSA -keysize 2048 -validity 10000
    //     -alias test
    //   generates a keystore and key which decrypt only with
    //   "ab­„?1"
    // * keytool -genkey -v -keystore native.jks -keyalg RSA -keysize 2048 -validity 10000
    //     -alias test -storepass <pass here>
    //   generates a keystore and key which decrypt only with
    //   "ab¡ä?1"
    // On modern OSX/Linux UTF-8 is used as the console and JVM default encoding:
    // * keytool -genkey -v -keystore native.jks -keyalg RSA -keysize 2048 -validity 10000
    //     -alias test
    //   generates a keystore and key which decrypt only with
    //   "ab¡äю1"
    // * keytool -genkey -v -keystore native.jks -keyalg RSA -keysize 2048 -validity 10000
    //     -alias test
    //   generates a keystore and key which decrypt only with
    //   "ab¡äю1"
    assertNotClosed();
    if (spec.startsWith("pass:")) {
        char[] pwd = spec.substring("pass:".length()).toCharArray();
        return getPasswords(pwd);
    } else if (SPEC_STDIN.equals(spec)) {
        Console console = System.console();
        if (console != null) {
            // Reading from console
            char[] pwd = console.readPassword(description + ": ");
            if (pwd == null) {
                throw new IOException("Failed to read " + description + ": console closed");
            }
            return getPasswords(pwd);
        } else {
            // Console not available -- reading from redirected input
            System.out.println(description + ": ");
            byte[] encodedPwd = readEncodedPassword(System.in);
            if (encodedPwd.length == 0) {
                throw new IOException("Failed to read " + description + ": standard input closed");
            }
            // encoding just in case.
            return getPasswords(encodedPwd, Charset.defaultCharset(), CONSOLE_CHARSET);
        }
    } else if (spec.startsWith("file:")) {
        String name = spec.substring("file:".length());
        File file = new File(name).getCanonicalFile();
        InputStream in = mFileInputStreams.get(file);
        if (in == null) {
            in = new FileInputStream(file);
            mFileInputStreams.put(file, in);
        }
        byte[] encodedPwd = readEncodedPassword(in);
        if (encodedPwd.length == 0) {
            throw new IOException("Failed to read " + description + " : end of file reached in " + file);
        }
        // default character encoding.
        return getPasswords(encodedPwd, Charset.defaultCharset());
    } else if (spec.startsWith("env:")) {
        String name = spec.substring("env:".length());
        String value = System.getenv(name);
        if (value == null) {
            throw new IOException("Failed to read " + description + ": environment variable " + value + " not specified");
        }
        return getPasswords(value.toCharArray());
    } else {
        throw new IOException("Unsupported password spec for " + description + ": " + spec);
    }
}
Also used : PushbackInputStream(java.io.PushbackInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Console(java.io.Console) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 20 with Console

use of java.io.Console in project nhin-d by DirectProject.

the class PKCS11SecretKeyManager method tokenLogin.

public static MutableKeyStoreProtectionManager tokenLogin() throws CryptoException {
    try {
        //System.console();
        final Console cons = null;
        char[] passwd = null;
        if (cons != null) {
            passwd = cons.readPassword("[%s]", "Enter hardware token password: ");
            java.util.Arrays.fill(passwd, ' ');
        } else {
            System.out.print("Enter hardware token password: ");
            final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            passwd = reader.readLine().toCharArray();
        }
        final BootstrappedPKCS11Credential cred = new BootstrappedPKCS11Credential(new String(passwd));
        final StaticPKCS11TokenKeyStoreProtectionManager loginMgr = new StaticPKCS11TokenKeyStoreProtectionManager();
        loginMgr.setCredential(cred);
        loginMgr.setKeyStoreProviderName(providerName);
        if (!StringUtils.isEmpty(keyStoreType))
            loginMgr.setKeyStoreType(keyStoreType);
        if (!StringUtils.isEmpty(keyStoreSource)) {
            InputStream str = new ByteArrayInputStream(keyStoreSource.getBytes());
            loginMgr.setKeyStoreSource(str);
        }
        if (!StringUtils.isEmpty(pkcs11ProviderCfg))
            loginMgr.setPcks11ConfigFile(pkcs11ProviderCfg);
        loginMgr.initTokenStore();
        return loginMgr;
    } catch (Exception e) {
        throw new RuntimeException("Error getting password.", e);
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) StaticPKCS11TokenKeyStoreProtectionManager(org.nhindirect.common.crypto.impl.StaticPKCS11TokenKeyStoreProtectionManager) Console(java.io.Console) BufferedReader(java.io.BufferedReader) BootstrappedPKCS11Credential(org.nhindirect.common.crypto.impl.BootstrappedPKCS11Credential) IOException(java.io.IOException) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException)

Aggregations

Console (java.io.Console)23 IOException (java.io.IOException)6 BufferedReader (java.io.BufferedReader)5 ByteArrayInputStream (java.io.ByteArrayInputStream)5 InputStreamReader (java.io.InputStreamReader)5 IOError (java.io.IOError)4 SshClient (org.apache.sshd.client.SshClient)4 UserInteraction (org.apache.sshd.client.auth.keyboard.UserInteraction)4 ClientChannel (org.apache.sshd.client.channel.ClientChannel)4 ClientSession (org.apache.sshd.client.session.ClientSession)4 File (java.io.File)3 FileInputStream (java.io.FileInputStream)3 Scanner (java.util.Scanner)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 InputStream (java.io.InputStream)2 Reader (java.io.Reader)2 HashMap (java.util.HashMap)2 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)2 ChannelShell (org.apache.sshd.client.channel.ChannelShell)2 PtyCapableChannelSession (org.apache.sshd.client.channel.PtyCapableChannelSession)2