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:Main.java

public static void main(String[] args) throws Exception {

    // creates a console object
    Console cnsl = System.console();

    // if console is not null
    if (cnsl != null) {

        // creates new print writer
        PrintWriter out = cnsl.writer();

        // prints
        out.println("Here is The Optimus Prime!!");
    }//  w  ww . j  ava  2  s . c  o m

}

From source file:Main.java

public static void main(String[] args) {
    Pattern pattern = null;/*from ww w  .ja  v  a2s  .  c o  m*/
    Matcher matcher = null;

    Console console = System.console();
    while (true) {
        try {
            pattern = Pattern.compile(console.readLine("%nEnter your regex: "));

            matcher = pattern.matcher(console.readLine("Enter input string to search: "));
        } catch (PatternSyntaxException pse) {
            console.format("There is a problem with the regular expression!%n");
            console.format("The pattern in question is: %s%n", pse.getPattern());
            console.format("The description is: %s%n", pse.getDescription());
            console.format("The message is: %s%n", pse.getMessage());
            console.format("The index is: %s%n", pse.getIndex());
            System.exit(0);
        }
        boolean found = false;
        while (matcher.find()) {
            console.format("I found the text \"%s\" starting at " + "index %d and ending at index %d.%n",
                    matcher.group(), matcher.start(), matcher.end());
            found = true;
        }
        if (!found) {
            console.format("No match found.%n");
        }
    }
}

From source file:goeurotest.GoEuroTest.java

/**
 * @param args the command line arguments
 *///from w w  w .  j  a  v  a2  s  .  com
public static void main(String[] args) {

    Console console = System.console();

    if (args.length != 1) {
        if (console != null)
            console.writer().println("Usage: java -jar GoEuroTest.jar <CITY_NAME>");
        return;
    }

    URL url;

    try {
        url = new URL("http://api.goeuro.com/api/v2/position/suggest/en/" + args[0]);
    } catch (MalformedURLException ex) {
        if (console != null)
            console.writer().println("Malformed URL. Make sure the first parameter is the name of the city.");
        return;
    }

    String json;

    try {
        json = IOUtils.toString(url);
    } catch (IOException ex) {
        if (console != null)
            console.writer().println("Unable to contact the GoEuro API");
        return;
    }

    JsonParser parser = new JsonParser();

    try {
        JsonArray cities = parser.parse(json).getAsJsonArray();

        if (cities.size() == 0) {
            if (console != null)
                console.writer().println("No results found");
            return;
        }

        for (int i = 0; i < cities.size(); i++) {
            JsonObject city = cities.get(i).getAsJsonObject();
            String id = city.get("_id").getAsString();
            String name = city.get("name").getAsString();
            String type = city.get("type").getAsString();
            JsonObject geo_position = city.get("geo_position").getAsJsonObject();
            String latitude = geo_position.get("latitude").getAsString();
            String longitude = geo_position.get("longitude").getAsString();
            String entry = id + "," + name + "," + type + "," + latitude + "," + longitude;
            System.out.println(entry);

        }
    } catch (Exception e) {
        if (console != null)
            console.writer().println("Malformed API response.");
    }
}

From source file:dualcontrol.CryptoClientDemo.java

public static void main(String[] args) throws Exception {
    if (args.length != 3) {
        System.err.println("CryptoClientDemo usage: hostAddress port text");
    } else {//from   w  ww .j  av  a 2s  . c  om
        new CryptoClientDemo().call(System.getProperties(), new MockableConsoleAdapter(System.console()),
                args[0], Integer.parseInt(args[1]), args[2].getBytes());
    }
}

From source file:com.bluexml.tools.miscellaneous.Translate.java

/**
 * @param args//from w  w w.  jav a 2s .c o  m
 */
public static void main(String[] args) {
    System.out.println("Translate.main() 1");
    Console console = System.console();

    System.out.println("give path to folder that contains properties files");
    Scanner scanIn = new Scanner(System.in);

    try {
        // TODO Auto-generated method stub
        String sWhatever;

        System.out.println("Translate.main() 2");
        sWhatever = scanIn.nextLine();
        System.out.println("Translate.main() 3");

        System.out.println(sWhatever);

        File inDir = new File(sWhatever);

        FilenameFilter filter = new FilenameFilter() {

            public boolean accept(File arg0, String arg1) {
                return arg1.endsWith("properties");
            }
        };
        File[] listFiles = inDir.listFiles(filter);
        for (File file : listFiles) {

            prapareFileToTranslate(file, inDir);

        }

        System.out.println("please translate text files and press enter");
        String readLine = scanIn.nextLine();
        System.out.println("Translate.main() 4");
        for (File file : listFiles) {

            File values = new File(file.getParentFile(), file.getName() + ".txt");
            writeBackValues(values, file);
            values.delete();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        scanIn.close();
    }

}

From source file:org.fracturedatlas.athena.admin.AthenaAdmin.java

public static void main(String[] args) {

    Console c = System.console();
    if (c == null) {
        System.exit(1);//from   w ww  . j  a v a 2 s  .c om
    }

    Properties props = new Properties();
    ClassPathResource cpr = new ClassPathResource("admin.properties");
    try {
        InputStream in = cpr.getInputStream();
        props.load(in);
        in.close();
    } catch (Exception e) {
        c.format("Could not read properties file admin.properties\n");
        System.exit(1);
    }

    ApplicationContext context = new ClassPathXmlApplicationContext("security.xml");
    JdbcUserDetailsManager userDao = (JdbcUserDetailsManager) context.getBean("userDao");
    Md5PasswordEncoder encoder = (Md5PasswordEncoder) context.getBean("passwordEncoder");

    //TODO: Props file
    String realmName = props.getProperty("athena.admin.realm");

    if (args.length == 0) {
        System.out.println("USAGE: admin [command]");
        System.out.println("Where [command] is one of: create-user");
        System.exit(1);
    }

    Boolean usernameGood = false;
    String login = null;
    while (!usernameGood) {
        login = c.readLine("Enter new username: ");
        if (StringUtils.isBlank(login)) {
            c.format("username cannot be blank, please try again\n");
        } else {
            usernameGood = true;
        }
    }
    Boolean match = false;
    char[] password = null;
    char[] confirmedPassword = null;
    while (!match) {
        password = c.readPassword("Enter password: ");
        confirmedPassword = c.readPassword("Enter password again: ");
        match = Arrays.equals(password, confirmedPassword);
        if (!match) {
            c.format("Passwords do not match please try again\n");
        }
    }

    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new GrantedAuthorityImpl("ROLE_CLIENT_APPLICATION"));
    String clearPassword = new String(password);
    String saltedClearPassword = login + ":" + realmName + ":" + clearPassword;
    String encryptedPassword = encoder.encodePassword(saltedClearPassword, null);
    User user = new User(login, encryptedPassword, true, true, true, true, authorities);
    try {
        userDao.createUser(user);
    } catch (org.springframework.dao.DuplicateKeyException dke) {
        System.out.println("Username [" + user.getUsername() + "] already exists.");
        System.exit(1);
    }

    System.out.println("Successfully created [" + user.getUsername() + "]");
}

From source file:Password.java

public static void main(String args[]) throws IOException {

    Console c = System.console();
    if (c == null) {
        System.err.println("No console.");
        System.exit(1);/*from w ww.j av  a2 s . c o m*/
    }

    String login = c.readLine("Enter your login: ");
    char[] oldPassword = c.readPassword("Enter your old password: ");

    if (verify(login, oldPassword)) {
        boolean noMatch;
        do {
            char[] newPassword1 = c.readPassword("Enter your new password: ");
            char[] newPassword2 = c.readPassword("Enter new password again: ");
            noMatch = !Arrays.equals(newPassword1, newPassword2);
            if (noMatch) {
                c.format("Passwords don't match. Try again.%n");
            } else {
                change(login, newPassword1);
                c.format("Password for %s changed.%n", login);
            }
            Arrays.fill(newPassword1, ' ');
            Arrays.fill(newPassword2, ' ');
        } while (noMatch);
    }

    Arrays.fill(oldPassword, ' ');

}

From source file:webreader.WebReader.java

public static void main(String[] args) {
    WebReader app = new WebReader();
    Scanner scanner = new Scanner(System.in);
    Console console = System.console();
    //---Takes in user input for login
    System.out.print("Username: ");
    username = scanner.nextLine();//from  w  w w. j  a  v a  2s. c  o  m
    char[] charPassword = console.readPassword("Enter password: ");
    password = new String(charPassword);
    System.out.print("Non-UofM Gmail: ");
    email = scanner.nextLine();
    char[] charEmailPassword = console.readPassword("Gmail password: ");
    emailPassword = new String(charEmailPassword);
    System.out.println("How often(in minutes) do you want your grades checked? ");
    refreshRate = Integer.parseInt(scanner.nextLine()) * 60000;
    //---Starts program
    app.go();
}

From source file:com.floragunn.searchguard.tools.Hasher.java

public static void main(final String[] args) {

    final Options options = new Options();
    final HelpFormatter formatter = new HelpFormatter();
    options.addOption(//from   ww w .j ava  2  s. c  o  m
            Option.builder("p").argName("password").hasArg().desc("Cleartext password to hash").build());
    options.addOption(Option.builder("env").argName("name environment variable").hasArg()
            .desc("name environment variable to read password from").build());

    final CommandLineParser parser = new DefaultParser();
    try {
        final CommandLine line = parser.parse(options, args);

        if (line.hasOption("p")) {
            System.out.println(hash(line.getOptionValue("p").getBytes("UTF-8")));
        } else if (line.hasOption("env")) {
            final String pwd = System.getenv(line.getOptionValue("env"));
            if (pwd == null || pwd.isEmpty()) {
                throw new Exception("No environment variable '" + line.getOptionValue("env") + "' set");
            }
            System.out.println(hash(pwd.getBytes("UTF-8")));
        } else {
            final Console console = System.console();
            if (console == null) {
                throw new Exception("Cannot allocate a console");
            }
            final char[] passwd = console.readPassword("[%s]", "Password:");
            System.out.println(hash(new String(passwd).getBytes("UTF-8")));
        }
    } catch (final Exception exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        formatter.printHelp("hasher.sh", options, true);
        System.exit(-1);
    }
}

From source file:CertificateSigner.java

public static void main(String[] args) {
    String ksname = null; // the keystore name
    String alias = null; // the private key alias
    String inname = null; // the input file name
    String outname = null; // the output file name
    for (int i = 0; i < args.length; i += 2) {
        if (args[i].equals("-keystore"))
            ksname = args[i + 1];/*from  www.j av  a2s .  co  m*/
        else if (args[i].equals("-alias"))
            alias = args[i + 1];
        else if (args[i].equals("-infile"))
            inname = args[i + 1];
        else if (args[i].equals("-outfile"))
            outname = args[i + 1];
        else
            usage();
    }

    if (ksname == null || alias == null || inname == null || outname == null)
        usage();

    try {
        Console console = System.console();
        if (console == null)
            error("No console");
        char[] password = console.readPassword("Keystore password: ");
        KeyStore store = KeyStore.getInstance("JKS", "SUN");
        InputStream in = new FileInputStream(ksname);
        store.load(in, password);
        Arrays.fill(password, ' ');
        in.close();

        char[] keyPassword = console.readPassword("Key password for %s: ", alias);
        PrivateKey issuerPrivateKey = (PrivateKey) store.getKey(alias, keyPassword);
        Arrays.fill(keyPassword, ' ');

        if (issuerPrivateKey == null)
            error("No such private key");

        in = new FileInputStream(inname);

        CertificateFactory factory = CertificateFactory.getInstance("X.509");

        X509Certificate inCert = (X509Certificate) factory.generateCertificate(in);
        in.close();
        byte[] inCertBytes = inCert.getTBSCertificate();

        X509Certificate issuerCert = (X509Certificate) store.getCertificate(alias);
        Principal issuer = issuerCert.getSubjectDN();
        String issuerSigAlg = issuerCert.getSigAlgName();

        FileOutputStream out = new FileOutputStream(outname);

        X509CertInfo info = new X509CertInfo(inCertBytes);
        info.set(X509CertInfo.ISSUER, new CertificateIssuerName((X500Name) issuer));

        X509CertImpl outCert = new X509CertImpl(info);
        outCert.sign(issuerPrivateKey, issuerSigAlg);
        outCert.derEncode(out);

        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}