Exemple #1
0
 public static void main(String[] args) {
   Console console = System.console();
   if (console != null) {
     String user = new String(console.readLine("Enter username:"******"Enter password"));
     console.printf("User name is " + user + "\n");
     console.printf("Password is " + pwd + "\n");
   } else {
     System.out.println("Console is unavaliable");
   }
 }
Exemple #2
0
  /**
   * Main driver - run this to start interactive password manager.
   *
   * @param args Prog args
   * @throws Throwable If something went very wrong.
   */
  public static void main(String[] args) throws Throwable {
    Console c = System.console();
    if (c == null) FError.errAndExit("You need to be running in CLI mode");

    c.printf(
        "Welcome to FLogin!%nThis utility will encrypt & store your usernames/passwords%n(c) 2016 Fastily%n%n");

    // let user enter user & pw combos
    HashMap<String, String> ul = new HashMap<>();
    while (true) {
      String u = c.readLine("Enter a username: "******"!!! Characters hidden for security !!! %n");
      char[] p1 = c.readPassword("Enter password for %s: ", u);
      char[] p2 = c.readPassword("Confirm/Re-enter password for %s: ", u);

      if (Arrays.equals(p1, p2)) ul.put(u, new String(p1));
      else c.printf("Entered passwords do not match!%n");

      if (!c.readLine("Continue? (y/N): ").trim().toLowerCase().matches("(?i)(y|yes)")) break;

      c.printf("%n");
    }

    if (ul.isEmpty()) FError.errAndExit("You didn't enter any user/pass.  Program will exit.");

    // Generating our JSONObject
    JSONObject jo = new JSONObject();
    for (Map.Entry<String, String> e : ul.entrySet()) {
      JSONObject internal = new JSONObject();
      internal.put("pass", e.getValue());
      jo.put(e.getKey(), internal);
    }

    // Encrypt and dump to file
    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(128);
    SecretKey sk = kg.generateKey();
    writeFiles(pf, sk.getEncoded());

    Cipher cx = Cipher.getInstance("AES");
    cx.init(Cipher.ENCRYPT_MODE, sk);
    writeFiles(px, cx.doFinal(jo.toString().getBytes("UTF-8")));

    c.printf(
        "Successfully written out to '%s', '%s', '%s%s' and '%s%s'%n",
        pf, px, homefmt, pf, homefmt, px);
  }
 public void printTeams() {
   @SuppressWarnings("unchecked")
   List<String> teams = (List<String>) cache.get(teamsKey);
   if (teams != null) {
     for (String teamName : teams) {
       con.printf(cache.get(encode(teamName)).toString());
     }
   }
 }
Exemple #4
0
  public static void main(String args[]) {

    Console consola = System.console();

    // si consola es null significa que no tenemos consola
    if (consola == null) {
      System.out.printf("No existe una consola");
      System.exit(0); // Termina la aplicación
    }

    consola.printf("user: "******"pass: "******"\nEl usuario introducido es: " + usuario + ", y el password es: " + pass + "\n");
  }
 public void removePlayer() {
   String playerName = con.readLine("Enter player's name: ");
   String teamName = con.readLine("Enter player's team: ");
   Team t = (Team) cache.get(encode(teamName));
   if (t != null) {
     t.removePlayer(playerName);
     cache.put(encode(teamName), t);
   } else {
     con.printf(msgTeamMissing, teamName);
   }
 }
 public void addPlayers() {
   String teamName = con.readLine(msgEnterTeamName);
   String playerName = null;
   Team t = (Team) cache.get(encode(teamName));
   if (t != null) {
     while (!(playerName = con.readLine("Enter player's name (to stop adding, type \"q\"): "))
         .equals("q")) {
       t.addPlayer(playerName);
     }
     cache.put(encode(teamName), t);
   } else {
     con.printf(msgTeamMissing, teamName);
   }
 }
 public void removeTeam() {
   String teamName = con.readLine(msgEnterTeamName);
   Team t = (Team) cache.get(encode(teamName));
   if (t != null) {
     cache.remove(encode(teamName));
     @SuppressWarnings("unchecked")
     List<String> teams = (List<String>) cache.get(teamsKey);
     if (teams != null) {
       teams.remove(teamName);
     }
     cache.put(teamsKey, teams);
   } else {
     con.printf(msgTeamMissing, teamName);
   }
 }
Exemple #8
0
  public boolean promptForGuess() {
    Console console = System.console();

    while (true) {

      String guessAsString = console.readLine("Enter a letter: ");

      try {
        char guess = guessAsString.charAt(0);
        return mGame.applyGuess(guess);
      } catch (IllegalArgumentException e) {
        console.printf(e.getMessage() + "\n");
      }
    }
  }
  public static void main(String[] args) {
    Console console = System.console();

    // "In the book War of the __nouns__, the main character is an anonymous __job__ who records the
    // arrival of __animals__ in __place__.
    // Needless to say, havoc reigns as the __animals__ continue to __verb__ everything in sight,
    // until they are killed by the common __noun__.\n"

    // String sAge = console.readLine("How old are you?  ");
    // int age = Integer.parseInt(sAge);
    // if(age < 13) {
    // 	console.printf("Sorry, you must be at least 13 to use this program.\n");
    // 	System.exit(0);
    // }

    String noun;
    boolean invalid;
    do {
      noun = console.readLine("Enter a noun. ");
      invalid = noun.equalsIgnoreCase("dork");
      if (invalid) {
        console.printf("bad word, try again. ");
      }
    } while (invalid);
    String job = console.readLine("Enter a job. ");
    String animals = console.readLine("Enter an animal(plural). ");
    String place = console.readLine("Enter a place. ");
    String verb = console.readLine("Enter a verb. ");

    console.printf(
        "In the book War of the %s, the main character is an anonymous %s who records the arrival of %s in %s.\n",
        animals, job, animals, place);
    console.printf(
        "Needless to say, havoc reigns as the %s continue to %s everything in sight, until they are killed by the common %s.\n",
        animals, verb, noun);
  }
  /** Get password for the input principal from console */
  private static String getPassword(String principal) {
    Console console = System.console();
    if (console == null) {
      System.out.println(
          "Couldn't get Console instance, "
              + "maybe you're running this from within an IDE. "
              + "Use scanner to read password.");
      System.out.println("Password for " + principal + ":");
      try (Scanner scanner = new Scanner(System.in, "UTF-8")) {
        return scanner.nextLine().trim();
      }
    }
    console.printf("Password for " + principal + ":");
    char[] passwordChars = console.readPassword();
    String password = new String(passwordChars).trim();
    Arrays.fill(passwordChars, ' ');

    return password;
  }
Exemple #11
0
  /**
   * @param args
   * @throws ParseException
   */
  public static void main(String[] args) throws ParseException {
    Console console = System.console();
    console.printf("Mula Preview on Java, (version 0.1)\n\n");
    while (true) {
      try {
        console.printf("mula-preview >>> ");
        String text = System.console().readLine();
        MulaParser parser = new MulaParser(new StringReader(text));
        MulaSubstance[] substances = parser.article();
        if (!(substances.length == 1
            && substances[0] instanceof MulaList
            && ((MulaList) substances[0]).get(0).equals(MulaAtom.get("match"))
            && ((MulaList) substances[0]).get(1) instanceof MulaList
            && ((MulaList) substances[0]).get(2) instanceof MulaList)) {
          throw new Exception(
              "Unexpected list, using \"(match [scheme] [source])\" to test MulaScheme.");
        }

        MulaList scheme = (MulaList) ((MulaList) substances[0]).get(1);
        MulaList source = (MulaList) ((MulaList) substances[0]).get(2);

        MulaScheme mulaScheme = new MulaScheme(scheme);
        Map<MulaAtom, List<MulaSubstance>> variables = mulaScheme.match(source);

        if (variables == null) {
          throw new Exception("Source doesn't match scheme.");
        }

        console.printf("Variables: \n");
        for (MulaAtom name : variables.keySet()) {
          for (MulaSubstance substance : variables.get(name)) {
            console.printf(name.toString() + " -> " + substance.toString());
          }
        }
        console.printf("\n");
      } catch (Exception e) {
        console.printf(e.getMessage());
        e.printStackTrace();
        console.printf("\n");
      }
    }
  }
  public static void main(String[] args) {
    Console con = System.console();
    FootballManager manager = new FootballManager(System.console());
    con.printf(initialPrompt);

    while (true) {
      String action = con.readLine(">");
      if ("at".equals(action)) {
        manager.addTeam();
      } else if ("ap".equals(action)) {
        manager.addPlayers();
      } else if ("rt".equals(action)) {
        manager.removeTeam();
      } else if ("rp".equals(action)) {
        manager.removePlayer();
      } else if ("p".equals(action)) {
        manager.printTeams();
      } else if ("q".equals(action)) {
        System.exit(0);
      }
    }
  }
Exemple #13
0
 public void create(Node node, Interrupter interrupter) throws Exception {
   AgentChannelManager agentChannelManager = node.agentChannelManager();
   System.out.println(
       "\n*** ConsoleApp " + agentChannelManager.agentChannelManagerAddress() + " ***\n");
   Console cons = System.console();
   boolean authenticated = false;
   while (!authenticated) {
     operatorName = cons.readLine("name: ");
     authenticated =
         node.passwordAuthenticator()
             .authenticate(operatorName, new String(cons.readPassword("password: "******"invalid\n\n");
   }
   interpreter = new Interpreter();
   interpreter.initialize(node.mailboxFactory().createAsyncMailbox());
   interpreter.configure(operatorName, node, this, System.out);
   if (interrupter != null) {
     node.mailboxFactory().addClosable(interrupter);
     interrupter.activate(interpreter);
   }
   this.node = node;
   agentChannelManager.interpreters.add(interpreter);
   inbr = new BufferedReader(new InputStreamReader(System.in));
   JAFuture future = new JAFuture();
   boolean first = true;
   while (true) {
     String commandLine = null;
     while (commandLine == null) {
       if (!first) System.out.println();
       else first = false;
       interpreter.prompt();
       commandLine = input();
     }
     (new Interpret(commandLine)).send(future, interpreter);
   }
 }
Exemple #14
0
  public static void main(String[] args) throws Exception {
    boolean isInteractive = false;
    classUrl = MynaInstaller.class.getResource("MynaInstaller.class").toString();
    isJar = (classUrl.indexOf("jar") == 0);
    if (!isJar) {
      System.err.println("Installer can only be run from inside a Myna distribution war file");
      System.exit(1);
    }

    Thread.sleep(1000);

    Console console = System.console();
    String response = null;
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();
    options.addOption(
        "c", "context", true, "Webapp context. Must Start with \"/\" Default: " + webctx);
    options.addOption("h", "help", false, "Displays help.");
    options.addOption(
        "w",
        "webroot",
        true,
        "Webroot to use. Will be created if webroot/WEB-INF does not exist. Default: " + webroot);
    options.addOption(
        "l",
        "logfile",
        true,
        "Log file to use. Will be created if it does not exist. Default: ./<context>.log");
    options.addOption(
        "s",
        "servername",
        true,
        "Name of this instance. Will also be the name of the init script. Defaults to either \"myna\" or the value of <context> if defined");
    // options.addOption( "P", "purpose", true, "Purpose of the Server, such as DEV,PROD,TRAIN, etc.
    // Defaults to DEV" );

    options.addOption("p", "port", true, "HTTP port. Set to 0 to disable HTTP. Default: " + port);
    options.addOption(
        "sp", "ssl-port", true, "SSL (HTTPS) port. Set to 0 to disable SSL, Default: 0");

    options.addOption(
        "ks", "keystore", true, "keystore path. Default: <webroot>/WEB-INF/myna/myna_keystore");
    options.addOption("ksp", "ks-pass", true, "keystore password. Default: " + ksPass);
    options.addOption("ksa", "ks-alias", true, "certificate alias. Default: " + ksAlias);

    modeOptions.add("upgrade");
    modeOptions.add("install");
    options.addOption(
        "m",
        "mode",
        true,
        "Mode: one of "
            + modeOptions.toString()
            + ". \n"
            + "\"upgrade\": Upgrades myna installation in webroot and exits. "
            + "\"install\": Unpacks to webroot, and installs startup files");
    options.addOption(
        "u",
        "user",
        true,
        "User to own and run the Myna installation. Only applies to unix installs. Default: nobody");

    HelpFormatter formatter = new HelpFormatter();

    String cmdSyntax = "java -jar myna-X.war -m <mode> [options]";
    try {
      CommandLine line = parser.parse(options, args);
      Option option;
      if (args.length == 0) {
        formatter.printHelp(cmdSyntax, options);
        response = console.readLine("\nContinue with Interactive Install? (y/N)");
        if (response.toLowerCase().equals("y")) {
          isInteractive = true;

        } else System.exit(1);
      }
      // Help
      if (line.hasOption("help")) {
        formatter.printHelp(cmdSyntax, options);
        System.exit(1);
      }
      // mode
      if (line.hasOption("mode")) {
        mode = line.getOptionValue("mode");
        if (!modeOptions.contains(mode)) {
          System.err.println(
              "Invalid Arguments.  Reason: Mode must be in " + modeOptions.toString());
          formatter.printHelp(cmdSyntax, options);
          System.exit(1);
        }
      } else if (isInteractive) {
        option = options.getOption("mode");
        console.printf("\n" + option.getDescription());

        do {
          response = console.readLine("\nEnter " + option.getLongOpt() + "(" + mode + "): ");
          if (!response.isEmpty()) mode = response;
        } while (!modeOptions.contains(mode));
      }
      // webroot
      if (line.hasOption("webroot")) {
        webroot = line.getOptionValue("webroot");
      } else if (isInteractive) {
        option = options.getOption("webroot");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + webroot + "): ");
        if (!response.isEmpty()) webroot = response;
      }
      // port
      if (line.hasOption("port")) {
        port = Integer.parseInt(line.getOptionValue("port"));
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("port");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + port + "): ");
        if (!response.isEmpty()) port = Integer.parseInt(response);
      }
      // context
      if (line.hasOption("context")) {
        webctx = line.getOptionValue("context");

      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("context");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + webctx + "): ");
        if (!response.isEmpty()) webctx = response;
      }
      if (!webctx.startsWith("/")) {
        webctx = "/" + webctx;
      }
      // servername (depends on context)
      if (!webctx.equals("/")) {
        serverName = webctx.substring(1);
      }
      if (line.hasOption("servername")) {
        serverName = line.getOptionValue("servername");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("servername");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + serverName + "): ");
        if (!response.isEmpty()) serverName = response;
      }
      // user
      if (line.hasOption("user")) {
        user = line.getOptionValue("user");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("user");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + user + "): ");
        if (!response.isEmpty()) user = response;
      }
      // logfile
      logFile = "myna.log";
      if (!webctx.equals("/")) {
        logFile = webctx.substring(1) + ".log";
      }
      if (line.hasOption("logfile")) {
        logFile = line.getOptionValue("logfile");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("logfile");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "path(" + logFile + "): ");
        if (!response.isEmpty()) logFile = response;
      }

      // ssl-port
      if (line.hasOption("ssl-port")) {
        sslPort = Integer.parseInt(line.getOptionValue("ssl-port"));
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("ssl-port");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + sslPort + "): ");
        if (!response.isEmpty()) sslPort = Integer.parseInt(response);
      }
      // ks-pass
      if (line.hasOption("ks-pass")) {
        ksPass = line.getOptionValue("ks-pass");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("ks-pass");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + ksPass + "): ");
        if (!response.isEmpty()) ksPass = response;
      }
      // ks-alias
      if (line.hasOption("ks-alias")) {
        ksAlias = line.getOptionValue("ks-alias");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("ks-alias");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + ksAlias + "): ");
        if (!response.isEmpty()) ksAlias = response;
      }
      // keystore
      String appBase = new File(webroot).getCanonicalPath();
      if (keystore == null) {
        keystore = appBase + "/WEB-INF/myna/myna_keystore";
      }
      if (line.hasOption("keystore")) {
        keystore = line.getOptionValue("keystore");
      } else if (isInteractive && mode.equals("install")) {
        option = options.getOption("keystore");
        console.printf("\n" + option.getDescription());
        response = console.readLine("\nEnter " + option.getLongOpt() + "(" + keystore + "): ");
        if (!response.isEmpty()) keystore = response;
      }

      javaOpts = line.getArgList();
    } catch (ParseException exp) {
      System.err.println("Invalid Arguments.	Reason: " + exp.getMessage());

      formatter.printHelp(cmdSyntax, options);
      System.exit(1);
    }

    if (isInteractive) {
      System.out.println("\nProceeed with the following settings?:\n");
      System.out.println("mode        = " + mode);
      System.out.println("webroot     = " + webroot);
      if (mode.equals("install")) {
        System.out.println("port        = " + port);
        System.out.println("context     = " + webctx);
        System.out.println("servername  = " + serverName);
        System.out.println("user        = "******"logfile     = " + logFile);
        System.out.println("ssl-port    = " + sslPort);
        System.out.println("ks-pass     = "******"ks-alias    = " + ksAlias);
        System.out.println("keystore    = " + keystore);
      }
      response = console.readLine("Continue? (Y/n)");
      if (response.toLowerCase().equals("n")) System.exit(1);
    }
    File wrFile = new File(webroot);
    webroot = wrFile.toString();
    if (mode.equals("install")) {
      adminPassword = console.readLine("\nCreate an Admin password for this installation: ");
    }
    // unpack myna if necessary
    if (!wrFile.exists() || mode.equals("upgrade") || mode.equals("install")) {
      upgrade(wrFile);
    }

    if (mode.equals("install")) {
      File propertiesFile = new File(wrFile.toURI().resolve("WEB-INF/classes/general.properties"));
      FileInputStream propertiesFileIS = new FileInputStream(propertiesFile);
      Properties generalProperties = new Properties();
      generalProperties.load(propertiesFileIS);
      propertiesFileIS.close();
      if (!adminPassword.isEmpty()) {
        org.jasypt.util.password.StrongPasswordEncryptor cryptTool =
            new org.jasypt.util.password.StrongPasswordEncryptor();
        generalProperties.setProperty("admin_password", cryptTool.encryptPassword(adminPassword));
      }
      generalProperties.setProperty("instance_id", serverName);

      generalProperties.store(
          new java.io.FileOutputStream(propertiesFile), "Myna General Properties");

      String javaHome = System.getProperty("java.home");
      webroot = new File(webroot).getCanonicalPath();
      if (serverName.length() == 0) serverName = "myna";
      if (java.lang.System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) {
        if (!new File(logFile).isAbsolute()) {
          logFile = new File(wrFile.toURI().resolve("WEB-INF/" + logFile)).toString();
        }
        File templateFile =
            new File(
                wrFile.toURI().resolve("WEB-INF/myna/install/windows/update_myna_service.cmd"));

        String initScript =
            FileUtils.readFileToString(templateFile)
                .replaceAll("\\{webctx\\}", webctx)
                .replaceAll("\\{server\\}", Matcher.quoteReplacement(serverName))
                .replaceAll("\\{webroot\\}", Matcher.quoteReplacement(webroot))
                .replaceAll("\\{logfile\\}", Matcher.quoteReplacement(logFile))
                .replaceAll("\\{javahome\\}", Matcher.quoteReplacement(javaHome))
                .replaceAll("\\{port\\}", new Integer(port).toString())
                .replaceAll("\\{sslPort\\}", new Integer(sslPort).toString())
                .replaceAll("\\{keystore\\}", Matcher.quoteReplacement(keystore))
                .replaceAll("\\{ksPass\\}", Matcher.quoteReplacement(ksPass))
                .replaceAll("\\{ksAlias\\}", Matcher.quoteReplacement(ksAlias));

        File scriptFile =
            new File(wrFile.toURI().resolve("WEB-INF/myna/install/update_myna_service.cmd"));

        FileUtils.writeStringToFile(scriptFile, initScript);

        // Runtime.getRuntime().exec("cmd /c start " + scriptFile.toString()).waitFor();

        System.out.println(
            "\nInstalled Service 'Myna App Server " + serverName + "' the following settings:\n");
        System.out.println(
            "\nInit script '" + scriptFile + "' created with the following settings:\n");
        System.out.println("memory=256MB");
        System.out.println("serverName=" + serverName);
        System.out.println("javaHome=" + javaHome);
        System.out.println("context=" + webctx);
        System.out.println("port=" + port);
        System.out.println("myna_home=" + webroot);
        System.out.println("logfile=" + logFile);

        System.out.println("sslPort=" + sslPort);
        System.out.println("keyStore=" + keystore);
        System.out.println("ksPass="******"ksAlias=" + ksAlias);

        System.out.println(
            "\nEdit and and run the command file in " + scriptFile + " to update this service");

      } else {
        String curUser = java.lang.System.getProperty("user.name");
        if (!curUser.equals("root")) {
          System.out.println("Install mode must be run as root.");
          System.exit(1);
        }

        if (!new File(logFile).isAbsolute()) {
          logFile = new File(wrFile.toURI().resolve("WEB-INF/" + logFile)).toString();
        }
        File templateFile =
            new File(wrFile.toURI().resolve("WEB-INF/myna/install/linux/init_script"));
        String initScript =
            FileUtils.readFileToString(templateFile)
                .replaceAll("\\{webctx\\}", webctx)
                .replaceAll("\\{server\\}", serverName)
                .replaceAll("\\{user\\}", user)
                .replaceAll("\\{webroot\\}", webroot)
                .replaceAll("\\{javahome\\}", javaHome)
                .replaceAll("\\{logfile\\}", logFile)
                .replaceAll("\\{port\\}", new Integer(port).toString())
                .replaceAll("\\{sslPort\\}", new Integer(sslPort).toString())
                .replaceAll("\\{keystore\\}", keystore)
                .replaceAll("\\{ksPass\\}", ksPass)
                .replaceAll("\\{ksAlias\\}", ksAlias);

        File scriptFile = new File(wrFile.toURI().resolve("WEB-INF/myna/install/" + serverName));

        FileUtils.writeStringToFile(scriptFile, initScript);

        if (new File("/etc/init.d").exists()) {

          exec("chown  -R " + user + " " + webroot);
          exec("chown root " + scriptFile.toString());
          exec("chmod 700 " + scriptFile.toString());
          exec("cp " + scriptFile.toString() + " /etc/init.d/");

          System.out.println(
              "\nInit script '/etc/init.d/"
                  + serverName
                  + "' created with the following settings:\n");
        } else {
          System.out.println(
              "\nInit script '" + scriptFile + "' created with the following settings:\n");
        }

        System.out.println("user="******"memory=256MB");
        System.out.println("server=" + serverName);
        System.out.println("context=" + webctx);
        System.out.println("port=" + port);
        System.out.println("myna_home=" + webroot);
        System.out.println("logfile=" + logFile);

        System.out.println("sslPort=" + sslPort);
        System.out.println("keyStore=" + keystore);
        System.out.println("ksPass="******"ksAlias=" + ksAlias);

        System.out.println("\nEdit this file to customize startup behavior");
      }
    }
  }
Exemple #15
0
 public void print(String text) {
   console.printf("%s\n", text);
 }