Search in sources :

Example 6 with Console

use of java.io.Console in project voltdb by VoltDB.

the class CLIConfig method readPasswordIfNeeded.

public static String readPasswordIfNeeded(String user, String pwd, String prompt) throws IOException {
    // then read password from the console
    if ((null != user) && (user.trim().length() > 0)) {
        if ((pwd == null) || (pwd.trim().length() == 0)) {
            Console console = System.console();
            if (console == null) {
                throw new IOException("Unable to read password from console.");
            }
            char[] val = console.readPassword("%s", prompt);
            if (val != null) {
                return new String(val);
            } else {
                // logic handle password validation
                return "";
            }
        }
    }
    return pwd;
}
Also used : Console(java.io.Console) IOException(java.io.IOException)

Example 7 with Console

use of java.io.Console in project azure-sdk-for-java by Azure.

the class ManageWebAppWithAuthentication method runSample.

/**
     * Main function which runs the actual sample.
     * @param azure instance of the azure client
     * @return true if sample runs successfully
     */
public static boolean runSample(Azure azure) {
    // New resources
    final String suffix = ".azurewebsites.net";
    final String app1Name = SdkContext.randomResourceName("webapp1-", 20);
    final String app2Name = SdkContext.randomResourceName("webapp2-", 20);
    final String app3Name = SdkContext.randomResourceName("webapp3-", 20);
    final String app4Name = SdkContext.randomResourceName("webapp4-", 20);
    final String app1Url = app1Name + suffix;
    final String app2Url = app2Name + suffix;
    final String app3Url = app3Name + suffix;
    final String app4Url = app4Name + suffix;
    final String rgName = SdkContext.randomResourceName("rg1NEMV_", 24);
    try {
        //============================================================
        // Create a web app with a new app service plan
        System.out.println("Creating web app " + app1Name + " in resource group " + rgName + "...");
        WebApp app1 = azure.webApps().define(app1Name).withRegion(Region.US_WEST).withNewResourceGroup(rgName).withNewWindowsPlan(PricingTier.STANDARD_S1).withJavaVersion(JavaVersion.JAVA_8_NEWEST).withWebContainer(WebContainer.TOMCAT_8_0_NEWEST).create();
        System.out.println("Created web app " + app1.name());
        Utils.print(app1);
        //============================================================
        // Set up active directory authentication
        System.out.println("Please create an AD application with redirect URL " + app1Url);
        System.out.print("Application ID is:");
        Console console = System.console();
        String applicationId = console.readLine();
        System.out.print("Tenant ID is:");
        String tenantId = console.readLine();
        System.out.println("Updating web app " + app1Name + " to use active directory login...");
        app1.update().defineAuthentication().withDefaultAuthenticationProvider(BuiltInAuthenticationProvider.AZURE_ACTIVE_DIRECTORY).withActiveDirectory(applicationId, "https://sts.windows.net/" + tenantId).attach().apply();
        System.out.println("Added active directory login to " + app1.name());
        Utils.print(app1);
        //============================================================
        // Create a second web app
        System.out.println("Creating another web app " + app2Name + " in resource group " + rgName + "...");
        AppServicePlan plan = azure.appServices().appServicePlans().getById(app1.appServicePlanId());
        WebApp app2 = azure.webApps().define(app2Name).withExistingWindowsPlan(plan).withExistingResourceGroup(rgName).withJavaVersion(JavaVersion.JAVA_8_NEWEST).withWebContainer(WebContainer.TOMCAT_8_0_NEWEST).create();
        System.out.println("Created web app " + app2.name());
        Utils.print(app2);
        //============================================================
        // Set up Facebook authentication
        System.out.println("Please create a Facebook developer application with whitelisted URL " + app2Url);
        System.out.print("App ID is:");
        String fbAppId = console.readLine();
        System.out.print("App secret is:");
        String fbAppSecret = console.readLine();
        System.out.println("Updating web app " + app2Name + " to use Facebook login...");
        app2.update().defineAuthentication().withDefaultAuthenticationProvider(BuiltInAuthenticationProvider.FACEBOOK).withFacebook(fbAppId, fbAppSecret).attach().apply();
        System.out.println("Added Facebook login to " + app2.name());
        Utils.print(app2);
        //============================================================
        // Create a 3rd web app with a public GitHub repo in Azure-Samples
        System.out.println("Creating another web app " + app3Name + "...");
        WebApp app3 = azure.webApps().define(app3Name).withExistingWindowsPlan(plan).withNewResourceGroup(rgName).defineSourceControl().withPublicGitRepository("https://github.com/Azure-Samples/app-service-web-dotnet-get-started").withBranch("master").attach().create();
        System.out.println("Created web app " + app3.name());
        Utils.print(app3);
        //============================================================
        // Set up Google authentication
        System.out.println("Please create a Google developer application with redirect URL " + app3Url);
        System.out.print("Client ID is:");
        String gClientId = console.readLine();
        System.out.print("Client secret is:");
        String gClientSecret = console.readLine();
        System.out.println("Updating web app " + app3Name + " to use Google login...");
        app3.update().defineAuthentication().withDefaultAuthenticationProvider(BuiltInAuthenticationProvider.GOOGLE).withGoogle(gClientId, gClientSecret).attach().apply();
        System.out.println("Added Google login to " + app3.name());
        Utils.print(app3);
        //============================================================
        // Create a 4th web app
        System.out.println("Creating another web app " + app4Name + "...");
        WebApp app4 = azure.webApps().define(app4Name).withExistingWindowsPlan(plan).withExistingResourceGroup(rgName).create();
        System.out.println("Created web app " + app4.name());
        Utils.print(app4);
        //============================================================
        // Set up Google authentication
        System.out.println("Please create a Microsoft developer application with redirect URL " + app4Url);
        System.out.print("Client ID is:");
        String clientId = console.readLine();
        System.out.print("Client secret is:");
        String clientSecret = console.readLine();
        System.out.println("Updating web app " + app3Name + " to use Microsoft login...");
        app4.update().defineAuthentication().withDefaultAuthenticationProvider(BuiltInAuthenticationProvider.MICROSOFT_ACCOUNT).withMicrosoft(clientId, clientSecret).attach().apply();
        System.out.println("Added Microsoft login to " + app4.name());
        Utils.print(app4);
        return true;
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
    } finally {
        try {
            System.out.println("Deleting Resource Group: " + rgName);
            azure.resourceGroups().beginDeleteByName(rgName);
            System.out.println("Deleted Resource Group: " + rgName);
        } catch (NullPointerException npe) {
            System.out.println("Did not create any resources in Azure. No clean up is necessary");
        } catch (Exception g) {
            g.printStackTrace();
        }
    }
    return false;
}
Also used : Console(java.io.Console) IOException(java.io.IOException) WebApp(com.microsoft.azure.management.appservice.WebApp) AppServicePlan(com.microsoft.azure.management.appservice.AppServicePlan)

Example 8 with Console

use of java.io.Console in project zm-mailbox by Zimbra.

the class MailClient method authenticate.

protected void authenticate() throws LoginException, IOException {
    Console console = System.console();
    if (console != null) {
        if (config.getAuthenticationId() == null) {
            config.setAuthenticationId(console.readLine("Username: "));
        }
        if (password == null && isPasswordRequired()) {
            password = new String(console.readPassword("Password: "));
        }
    }
    connection.authenticate(password);
    String qop = connection.getNegotiatedQop();
    if (qop != null)
        System.out.printf("[Negotiated QOP is %s]\n", qop);
}
Also used : Console(java.io.Console)

Example 9 with Console

use of java.io.Console in project incubator-atlas by apache.

the class AuthenticationUtil method getBasicAuthenticationInput.

public static String[] getBasicAuthenticationInput() {
    String username = null;
    String password = null;
    try {
        Console console = System.console();
        username = console.readLine("Enter username for atlas :- ");
        char[] pwdChar = console.readPassword("Enter password for atlas :- ");
        if (pwdChar != null) {
            password = new String(pwdChar);
        }
    } catch (Exception e) {
        System.out.print("Error while reading ");
        System.exit(1);
    }
    return new String[] { username, password };
}
Also used : Console(java.io.Console) AtlasException(org.apache.atlas.AtlasException)

Example 10 with Console

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

the class Main method main.

public static void main(String[] args) throws Exception {
    ClientConfig config = new ClientConfig(args);
    SimpleLogger.setLevel(config.getLevel());
    if (config.getFile() != null) {
        StringBuilder sb = new StringBuilder();
        sb.setLength(0);
        try (Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(config.getFile())))) {
            for (int c = reader.read(); c >= 0; c = reader.read()) {
                sb.append((char) c);
            }
        }
        config.setCommand(sb.toString());
    } else if (config.isBatch()) {
        StringBuilder sb = new StringBuilder();
        sb.setLength(0);
        Reader reader = new BufferedReader(new InputStreamReader(System.in));
        for (int c = reader.read(); c >= 0; c = reader.read()) {
            sb.append((char) c);
        }
        config.setCommand(sb.toString());
    }
    try (SshClient client = ClientBuilder.builder().build()) {
        FilePasswordProvider passwordProvider = null;
        final Console console = System.console();
        if (console != null) {
            passwordProvider = resourceKey -> {
                char[] pwd = console.readPassword("Enter password for " + resourceKey + ": ");
                return new String(pwd);
            };
            client.setFilePasswordProvider(passwordProvider);
            client.setUserInteraction(new UserInteraction() {

                @Override
                public void welcome(ClientSession s, String banner, String lang) {
                    System.out.println(banner);
                }

                @Override
                public String[] interactive(ClientSession s, String name, String instruction, String lang, String[] prompt, boolean[] echo) {
                    String[] answers = new String[prompt.length];
                    try {
                        for (int i = 0; i < prompt.length; i++) {
                            if (echo[i]) {
                                answers[i] = console.readLine(prompt[i] + " ");
                            } else {
                                answers[i] = new String(console.readPassword(prompt[i] + " "));
                            }
                            if (answers[i] == null) {
                                return null;
                            }
                        }
                        return answers;
                    } catch (IOError e) {
                        return null;
                    }
                }

                @Override
                public boolean isInteractionAllowed(ClientSession session) {
                    return true;
                }

                @Override
                public void serverVersionInfo(ClientSession session, List<String> lines) {
                }

                @Override
                public String getUpdatedPassword(ClientSession session, String prompt, String lang) {
                    return null;
                }
            });
        }
        setupAgent(config.getUser(), config.getKeyFile(), client, passwordProvider);
        client.getProperties().put(FactoryManager.IDLE_TIMEOUT, String.valueOf(config.getIdleTimeout()));
        // TODO: remove the line below when SSHD-732 is fixed
        client.setKeyPairProvider(new FileKeyPairProvider());
        client.start();
        if (console != null) {
            console.printf("Logging in as %s\n", config.getUser());
        }
        ClientSession session = connectWithRetries(client, config);
        if (config.getPassword() != null) {
            session.addPasswordIdentity(config.getPassword());
        }
        session.auth().verify();
        int exitStatus = 0;
        try (Terminal terminal = TerminalBuilder.terminal()) {
            Attributes attributes = terminal.enterRawMode();
            try {
                ClientChannel channel;
                if (config.getCommand().length() > 0) {
                    ChannelExec exec = session.createExecChannel(config.getCommand() + "\n");
                    channel = exec;
                    channel.setIn(new ByteArrayInputStream(new byte[0]));
                    exec.setAgentForwarding(true);
                } else {
                    ChannelShell shell = session.createShellChannel();
                    channel = shell;
                    channel.setIn(new NoCloseInputStream(terminal.input()));
                    Map<PtyMode, Integer> modes = new HashMap<>();
                    // Control chars
                    modes.put(PtyMode.VINTR, attributes.getControlChar(ControlChar.VINTR));
                    modes.put(PtyMode.VQUIT, attributes.getControlChar(ControlChar.VQUIT));
                    modes.put(PtyMode.VERASE, attributes.getControlChar(ControlChar.VERASE));
                    modes.put(PtyMode.VKILL, attributes.getControlChar(ControlChar.VKILL));
                    modes.put(PtyMode.VEOF, attributes.getControlChar(ControlChar.VEOF));
                    modes.put(PtyMode.VEOL, attributes.getControlChar(ControlChar.VEOL));
                    modes.put(PtyMode.VEOL2, attributes.getControlChar(ControlChar.VEOL2));
                    modes.put(PtyMode.VSTART, attributes.getControlChar(ControlChar.VSTART));
                    modes.put(PtyMode.VSTOP, attributes.getControlChar(ControlChar.VSTOP));
                    modes.put(PtyMode.VSUSP, attributes.getControlChar(ControlChar.VSUSP));
                    modes.put(PtyMode.VDSUSP, attributes.getControlChar(ControlChar.VDSUSP));
                    modes.put(PtyMode.VREPRINT, attributes.getControlChar(ControlChar.VREPRINT));
                    modes.put(PtyMode.VWERASE, attributes.getControlChar(ControlChar.VWERASE));
                    modes.put(PtyMode.VLNEXT, attributes.getControlChar(ControlChar.VLNEXT));
                    modes.put(PtyMode.VSTATUS, attributes.getControlChar(ControlChar.VSTATUS));
                    modes.put(PtyMode.VDISCARD, attributes.getControlChar(ControlChar.VDISCARD));
                    // Input flags
                    modes.put(PtyMode.IGNPAR, getFlag(attributes, InputFlag.IGNPAR));
                    modes.put(PtyMode.PARMRK, getFlag(attributes, InputFlag.PARMRK));
                    modes.put(PtyMode.INPCK, getFlag(attributes, InputFlag.INPCK));
                    modes.put(PtyMode.ISTRIP, getFlag(attributes, InputFlag.ISTRIP));
                    modes.put(PtyMode.INLCR, getFlag(attributes, InputFlag.INLCR));
                    modes.put(PtyMode.IGNCR, getFlag(attributes, InputFlag.IGNCR));
                    modes.put(PtyMode.ICRNL, getFlag(attributes, InputFlag.ICRNL));
                    modes.put(PtyMode.IXON, getFlag(attributes, InputFlag.IXON));
                    modes.put(PtyMode.IXANY, getFlag(attributes, InputFlag.IXANY));
                    modes.put(PtyMode.IXOFF, getFlag(attributes, InputFlag.IXOFF));
                    // Local flags
                    modes.put(PtyMode.ISIG, getFlag(attributes, LocalFlag.ISIG));
                    modes.put(PtyMode.ICANON, getFlag(attributes, LocalFlag.ICANON));
                    modes.put(PtyMode.ECHO, getFlag(attributes, LocalFlag.ECHO));
                    modes.put(PtyMode.ECHOE, getFlag(attributes, LocalFlag.ECHOE));
                    modes.put(PtyMode.ECHOK, getFlag(attributes, LocalFlag.ECHOK));
                    modes.put(PtyMode.ECHONL, getFlag(attributes, LocalFlag.ECHONL));
                    modes.put(PtyMode.NOFLSH, getFlag(attributes, LocalFlag.NOFLSH));
                    modes.put(PtyMode.TOSTOP, getFlag(attributes, LocalFlag.TOSTOP));
                    modes.put(PtyMode.IEXTEN, getFlag(attributes, LocalFlag.IEXTEN));
                    // Output flags
                    modes.put(PtyMode.OPOST, getFlag(attributes, OutputFlag.OPOST));
                    modes.put(PtyMode.ONLCR, getFlag(attributes, OutputFlag.ONLCR));
                    modes.put(PtyMode.OCRNL, getFlag(attributes, OutputFlag.OCRNL));
                    modes.put(PtyMode.ONOCR, getFlag(attributes, OutputFlag.ONOCR));
                    modes.put(PtyMode.ONLRET, getFlag(attributes, OutputFlag.ONLRET));
                    shell.setPtyModes(modes);
                    shell.setPtyColumns(terminal.getWidth());
                    shell.setPtyLines(terminal.getHeight());
                    shell.setAgentForwarding(true);
                    String ctype = System.getenv("LC_CTYPE");
                    if (ctype == null) {
                        ctype = Locale.getDefault().toString() + "." + System.getProperty("input.encoding", Charset.defaultCharset().name());
                    }
                    shell.setEnv("LC_CTYPE", ctype);
                }
                channel.setOut(terminal.output());
                channel.setErr(terminal.output());
                channel.open().verify();
                if (channel instanceof PtyCapableChannelSession) {
                    registerSignalHandler(terminal, (PtyCapableChannelSession) channel);
                }
                channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0);
                if (channel.getExitStatus() != null) {
                    exitStatus = channel.getExitStatus();
                }
            } finally {
                terminal.setAttributes(attributes);
            }
        }
        System.exit(exitStatus);
    } catch (Throwable t) {
        if (config.getLevel() > SimpleLogger.WARN) {
            t.printStackTrace();
        } else {
            System.err.println(t.getMessage());
        }
        System.exit(1);
    }
}
Also used : SshClient(org.apache.sshd.client.SshClient) HashMap(java.util.HashMap) Attributes(org.jline.terminal.Attributes) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) ChannelShell(org.apache.sshd.client.channel.ChannelShell) ClientSession(org.apache.sshd.client.session.ClientSession) Console(java.io.Console) PtyCapableChannelSession(org.apache.sshd.client.channel.PtyCapableChannelSession) InputStreamReader(java.io.InputStreamReader) PtyMode(org.apache.sshd.common.channel.PtyMode) Terminal(org.jline.terminal.Terminal) FileInputStream(java.io.FileInputStream) ChannelExec(org.apache.sshd.client.channel.ChannelExec) ClientChannel(org.apache.sshd.client.channel.ClientChannel) FileKeyPairProvider(org.apache.sshd.common.keyprovider.FileKeyPairProvider) NoCloseInputStream(org.apache.sshd.common.util.io.NoCloseInputStream) IOError(java.io.IOError) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedReader(java.io.BufferedReader) UserInteraction(org.apache.sshd.client.auth.keyboard.UserInteraction) FilePasswordProvider(org.apache.sshd.common.config.keys.FilePasswordProvider)

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