Example #1
0
  public static void main(String[] args) throws IOException {

    boolean helyes = false;
    int i = 0;
    String aa = "al";
    do {
      System.out.println("-----Weclome!-----");
      System.out.println("a. - Soronkent szeretne keresni!");
      System.out.println("b. - Szavankent szeretne keresni!");
      System.out.println("c. - Ne legyen kis/nagy betuerzekeny!");
      System.out.println("x. - Kilep");
      System.out.println("------------------");
      String s = System.console().readLine();
      if (s.equals("x")) {
        helyes = true;
      } else {
        if (s.equals("a")) {
          System.out.println("irja':");
          String line = System.console().readLine();
          try {
            findTextLine(line, args[0]);
          } catch (FileNotFoundException e) {
            System.out.println("A kov fajl nem talalhato: " + args[0]);
          }
          helyes = true;
        }
        if (s.equals("b")) {
          System.out.println("irja':");
          String word = System.console().readLine();
          try {
            findTextWord(word, args[0]);
          } catch (FileNotFoundException e) {
            System.out.println("A kov fajl nem talalhato: " + args[0]);
          }
          helyes = true;
        }
        if (s.equals("c")) {
          System.out.println("irja':");
          String line = System.console().readLine();
          try {
            findTextWordNoCaps(line, args[0]);
          } catch (FileNotFoundException e) {
            System.out.println("A kov fajl nem talalhato: " + args[0]);
          }
          helyes = true;
        }
      }
    } while (helyes == false);
  }
Example #2
0
 /**
  * Returns a password from standard input.
  *
  * @return password
  */
 public static String password() {
   // use standard input if no console if defined (such as in Eclipse)
   if (NOCONSOLE) return input();
   // hide password
   final char[] pw = System.console().readPassword();
   return pw != null ? new String(pw) : "";
 }
Example #3
0
  public static void main(String[] args) throws MessagingException, IOException {
    Properties props = new Properties();
    try (InputStream in = Files.newInputStream(Paths.get("mail", "mail.properties"))) {
      props.load(in);
    }
    List<String> lines = Files.readAllLines(Paths.get(args[0]), Charset.forName("UTF-8"));

    String from = lines.get(0);
    String to = lines.get(1);
    String subject = lines.get(2);

    StringBuilder builder = new StringBuilder();
    for (int i = 3; i < lines.size(); i++) {
      builder.append(lines.get(i));
      builder.append("\n");
    }

    Console console = System.console();
    String password = new String(console.readPassword("Password: "));

    Session mailSession = Session.getDefaultInstance(props);
    // mailSession.setDebug(true);
    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(builder.toString());
    Transport tr = mailSession.getTransport();
    try {
      tr.connect(null, password);
      tr.sendMessage(message, message.getAllRecipients());
    } finally {
      tr.close();
    }
  }
Example #4
0
  public void Cloner(String f1, String f2) {
    File file1 = new File(f1);
    File file2 = new File(f2);
    if (file2.exists()) {
      System.out.println(
          "That file already exists are you sure you want to continue, hit n to return and any other key to contine");
      String str = System.console().readLine();
      if (str == "n") {
        return;
      }
    }

    BufferedReader in = null;
    PrintWriter out = null;
    try {
      in = new BufferedReader(new FileReader(file1));
      out = new PrintWriter(file2);
      String line;
      while ((line = in.readLine()) != null) {
        out.append(line + '\n');
      }
    } catch (FileNotFoundException ex) {
      System.out.println("the file does not exist");
      ex.printStackTrace();
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      System.out.println("okay thats been copied for you");
      closeReader(in);
      out.close();
    }
  }
Example #5
0
 public static void main(String[] args) throws Exception {
   BioServer s = new BioServer(9999);
   s.start();
   System.console().readLine("BioServer running on port 9999. Press enter to exit.");
   System.exit(0);
   s.stop();
 }
Example #6
0
  private void readDataConsole() {
    Console c = System.console();
    if (c == null) {
      System.err.println("No console.");
      System.exit(1);
    }

    String login = c.readLine("Enter your login: ");
  }
  public static void main(String argv[]) {

    Console console = System.console();
    String username = console.readLine("Username: "******"Password: "******"Entered password: " + new String(password));
    // clear the array as soon as the password has been used
    Arrays.fill(password, ' ');
  }
Example #8
0
 private static ShellConsole createConsole(Options options) throws IOException {
   ShellConsole console;
   if (!options.noJLine) {
     console = new JLineConsole(PROGRAM_NAME);
   } else if (System.console() != null) {
     console = new NativeConsole();
   } else {
     console = new LegacyConsole();
   }
   return console;
 }
Example #9
0
  public static void main(String[] args) {

    // Create a console object.
    Console objConsole = System.console();
    if (objConsole != null) {

      // readLine method call.
      String userName = objConsole.readLine("Enter  username  : "******"You have entered : " + userName);
    }
  }
Example #10
0
  @SuppressWarnings("serial")
  private static final class TruncatedThrowable extends Throwable {
    private static final boolean REMOVE_PACKAGE_NAME = System.console() != null;
    private static final String PACKAGE_NAME = "com.github.anba.es6draft.";
    private final Throwable throwable;

    TruncatedThrowable(Throwable throwable, int depth) {
      super();
      this.throwable = throwable;
      setStackTrace(truncate(throwable, depth));
      if (throwable.getCause() != null) {
        initCause(new TruncatedThrowable(throwable.getCause(), depth));
      }
      for (Throwable suppressed : throwable.getSuppressed()) {
        addSuppressed(new TruncatedThrowable(suppressed, depth));
      }
    }

    static StackTraceElement[] truncate(Throwable e, int depth) {
      StackTraceElement[] stackTrace = e.getStackTrace();
      if (stackTrace.length > depth) {
        int omitted = stackTrace.length - depth;
        stackTrace = Arrays.copyOf(stackTrace, depth + 1);
        stackTrace[depth] = new StackTraceElement("..", "", "Frames omitted", omitted);
      }
      if (REMOVE_PACKAGE_NAME) {
        for (int i = 0; i < stackTrace.length; ++i) {
          StackTraceElement element = stackTrace[i];
          String className = element.getClassName();
          if (className.startsWith(PACKAGE_NAME)) {
            stackTrace[i] =
                new StackTraceElement(
                    className.substring(PACKAGE_NAME.length()),
                    element.getMethodName(),
                    element.getFileName(),
                    element.getLineNumber());
          }
        }
      }
      return stackTrace;
    }

    @Override
    public String toString() {
      return throwable.toString();
    }

    @Override
    public Throwable fillInStackTrace() {
      // empty
      return this;
    }
  }
Example #11
0
  private static void parseOptions(Options options, String[] args) {
    ParserProperties properties = ParserProperties.defaults().withUsageWidth(128);
    CmdLineParser parser = new CmdLineParser(options, properties);
    try {
      parser.parseArgument(args);
    } catch (CmdLineException e) {
      System.err.println(e.getMessage());
      System.err.println(getUsageString(parser, false));
      System.exit(1);
    }
    if (options.showVersion) {
      System.out.println(getVersionString());
      System.exit(0);
    }
    if (options.showHelp) {
      System.out.println(getUsageString(parser, false));
      System.exit(0);
    }
    if (options.showExtendedHelp) {
      System.out.println(getUsageString(parser, true));
      System.exit(0);
    }
    if (options.debug || options.fullDebug || options.debugInfo) {
      // Disable interpreter when bytecode is requested
      options.noInterpreter = true;
    }
    if (options.fileName != null) {
      // Execute as last script
      if (options.fileName.toString().equals("-")) {
        // "-" is a short-hand to request reading from System.in
        if (System.console() == null) {
          // System.in is not interactive
          options.evalScripts.add(new EvalString(read(System.in)));
        } else {
          options.interactive = true;
        }
      } else {
        options.evalScripts.add(new EvalPath(options.fileName));
      }
    }
    if (options.evalScripts.isEmpty()) {
      // Default to interactive mode when no files or expressions were set
      options.interactive = true;

      // Warn if --module is used without input files.
      if (options.module) {
        System.err.println(formatMessage("module_no_files"));
      }
    }
    if (options.ecmascript7) {
      System.err.println(formatMessage("deprecated.es7"));
    }
  }
Example #12
0
 /**
  * This Sample PrivilegedAction performs the following operations:
  *
  * <ul>
  *   <li>Access the System property, <i>java.home</i>
  *   <li>Access the System property, <i>user.home</i>
  *   <li>Access the file, <i>foo.txt</i>
  * </ul>
  *
  * @return <code>null</code> in all cases.
  * @exception SecurityException if the caller does not have permission to perform the operations
  *     listed above.
  */
 public Object run() {
   Subject currentSubject = Subject.getSubject(AccessController.getContext());
   Iterator iter = currentSubject.getPrincipals().iterator();
   String dir = "";
   Principal p = null;
   while (iter.hasNext()) {
     p = (Principal) iter.next();
     dir = dir + p.getName() + " ";
   }
   if ((p.getName()).equals("Admin")) {
     String choice;
     while (!(choice = System.console().readLine("choice : ")).equals("exit")) {
       if (choice.equals("add")) {
         String directory = System.console().readLine("directory : ");
         String filename = System.console().readLine("name : ");
         String content = System.console().readLine("content : ");
         try {
           BufferedWriter bw =
               new BufferedWriter(
                   new FileWriter("sample/db/" + directory + "/" + filename + ".txt"));
           bw.write(content);
           bw.close();
           System.out.println(filename + ".txt generated.");
         } catch (Exception e) {
           System.out.println(e.toString());
           continue;
         }
       } else if (choice.equals("rm")) {
         try {
           String filename = System.console().readLine("name : ");
           File f = new File(searchMovie(dir, filename));
           if (f.exists()) {
             f.delete();
             System.out.println(filename + ".txt deleted.");
           }
         } catch (Exception e) {
           System.out.println(e.toString());
           continue;
         }
       } else if (choice.equals("read")) {
         String filename = System.console().readLine("Movie to watch : ");
         promptUser(dir, filename, p);
       } else {
         System.out.println("Invalid selection ( add, rm, read, exit )");
       }
     }
   } else {
     String filename;
     while (!(filename = System.console().readLine("Movie to watch : ")).equals("exit")) {
       promptUser(dir, filename, p);
     }
   }
   return null;
 }
Example #13
0
 public char[] askSecret(final String question) {
   if (withColor) {
     write(
         console,
         false,
         Ansi.ansi()
             .fgBright(Ansi.Color.CYAN)
             .bold()
             .a(question + " ")
             .boldOff()
             .reset()
             .toString());
   } else {
     write(console, false, question + " ");
   }
   return System.console().readPassword();
 }
Example #14
0
 public String ask(final String question) {
   if (withColor) {
     write(
         console,
         false,
         Ansi.ansi()
             .fgBright(Ansi.Color.WHITE)
             .bold()
             .a(question + " ")
             .boldOff()
             .reset()
             .toString());
   } else {
     write(console, false, question + " ");
   }
   return System.console().readLine();
 }
Example #15
0
public class JChatComm {

  JChatSession session;
  Com com;
  Console console = System.console();

  public JChatComm(String hostName, JChatSession csession) {
    if (hostName.equals("0")) com = new JServer();
    else com = new JClient(hostName);
    session = csession;
  }

  public void sendMessage() throws Exception {
    String userInput;
    userInput = console.readLine();
    JPacket packet = new JPacket(userInput);
    com.sendMessage(packet);
    if (userInput.equals("End Chat")) {
      endChat();
      System.out.println("Chat Over");
    } else logMessage(packet, "You");
  }

  private void logMessage(JPacket packet, String sender) {
    session.addMsg(packet, sender);
  }

  public void readMessage() {
    JPacket packet = com.receiveMessage();
    if (packet.jmsg.msg.equals("End Chat")) {
      endChat();
      System.out.println("Chat Over");
    } else {
      logMessage(packet, "OtherGuy");
      System.out.println("OtherGuy: " + packet.jmsg.msg);
    }
  }

  public void endChat() {
    com.closeConnection();
    System.out.println("\nLog");
    System.out.println("-----------------------------------------------");
    session.printLog();
    System.exit(1);
  }
}
Example #16
0
 public int[] menu() {
   int[] answers = {0, 0, 0};
   // helyértékek: 0 = isCaseSensitive,1 = isItYesOrNo,2 = helyes
   // 0 érték a hamis, 1 érték az igaz
   String s = System.console().readLine();
   if (s.equals("x")) {
     answers[2] = 1;
   } else {
     if (s.equals("i") || s.equals("I")) {
       answers[0] = 1;
       answers[1] = 1;
       answers[2] = 1;
     }
     if (s.equals("n") || s.equals("N")) {
       answers[0] = 0;
       answers[1] = 1;
       answers[2] = 1;
     }
   }
   return answers;
 }
Example #17
0
 public static void main(String[] args) {
   Set<Character> hole1 = new HashSet<Character>();
   Set<Character> hole2 = new HashSet<Character>();
   hole1.add('A');
   hole1.add('D');
   hole1.add('O');
   hole1.add('P');
   hole1.add('R');
   hole1.add('Q');
   hole2.add('B');
   Console c = System.console();
   int n = Integer.parseInt(c.readLine());
   for (int i = 0; i < n; i++) {
     int count = 0;
     String s = c.readLine();
     for (int j = 0; j < s.length(); j++) {
       if (hole1.contains(s.charAt(j))) count++;
       else if (hole2.contains(s.charAt(j))) count += 2;
     }
     System.out.println(count + "");
   }
 }
  private void initiateQuery() {
    Console console = System.console();
    String input = console.readLine("Please enter search term: ");
    while (input.isEmpty()) {
      input = console.readLine("Please enter a valid search term: ");
    }

    String precision = console.readLine("Please enter desired precision(between 0 and 1): ");
    while (precision.isEmpty() || !isPrecisionValid(precision)) {
      precision = console.readLine("Please enter a valid precision(between 0 and 1): ");
    }

    boolean complete = false;

    while (!complete) {
      try {
        String bingResults = searchBing(input);
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      SearchResult[] searchResults = parseTenSearchResults(bingResults);
      int numOfRelevant = 0;
      for (SearchResult result : searchResults) {
        boolean relevant = isResultRelevant(result);
        if (relevant) {
          numOfRelevant++;
        }
      }

      if (numOfRelevant < (Double.parseDouble(precision) * 10)) {
        String[] additionalTerms = extractNewTerms(searchResults);
      } else {
        complete = true;
      }
    }
  }
Example #19
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");
      }
    }
  }
Example #20
0
 public boolean canInteract() {
   return System.console() != null && !noPrompt;
 }
Example #21
0
  public static void main(String[] args) throws Exception {
    String host = null;
    int port = -1;
    for (int i = 0; i < args.length; i++) {
      System.out.println("args[" + i + "] = " + args[i]);
    }
    if (args.length < 2) {
      System.out.println("USAGE: java client host port");
      System.exit(-1);
    }
    try {
        /* get input parameters */
      host = args[0];
      port = Integer.parseInt(args[1]);
    } catch (IllegalArgumentException e) {
      System.out.println("USAGE: java client host port");
      System.exit(-1);
    }

    try {
        /* set up a key manager for client authentication */
      SSLSocketFactory factory = null;
      try {
        KeyStore ks = KeyStore.getInstance("JKS");
        KeyStore ts = KeyStore.getInstance("JKS");
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        SSLContext ctx = SSLContext.getInstance("TLS");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter keystore: ");
        String keystoreName = br.readLine();
        Console cons = System.console();

        if (cons != null) {
          password = cons.readPassword("%s", "Password: "******"Cannot find a console to read password from. Eclipse CANNOT fork a terminal child process.");
        }

        ks.load(new FileInputStream("keystores/" + keystoreName), password); // keystore
        // password
        // (storepass)
        char[] cliTrustPW = "password".toCharArray();
        ts.load(new FileInputStream("clienttruststore"), cliTrustPW); // truststore
        // password
        // (storepass);
        kmf.init(ks, password); // user password (keypass)
        tmf.init(ts); // keystore can be used as truststore here
        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        factory = ctx.getSocketFactory();
      } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
      }

      SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
      System.out.println("Handshake socket: " + socket + "\n");

      /*
       * send http request
       *
       * See SSLSocketClient.java for more information about why there is
       * a forced handshake here when using PrintWriters.
       */
      socket.startHandshake();

      SSLSession session = socket.getSession();
      X509Certificate cert = (X509Certificate) session.getPeerCertificateChain()[0];
      System.out.println("Server DN: " + cert.getSubjectDN().getName());
      System.out.println("Handshake socket: " + socket);
      System.out.println("Secure connection.");
      System.out.println("Issuer DN: " + cert.getIssuerDN().getName());
      System.out.println("Serial N: " + cert.getSerialNumber().toString());

      read = new BufferedReader(new InputStreamReader(System.in));
      serverMsg = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      out = new PrintWriter(socket.getOutputStream(), true);
      ois = new ObjectInputStream(socket.getInputStream());
      records = new ArrayList<Record>();

      boolean isLoggedIn = false;
      boolean isDone = false;

      isLoggedIn = waitForLoginData();

      if (!isLoggedIn) {
        System.out.println(
            "This certificate does not have a user. \n Press the RETURN key to exit.");
        System.console().readLine();

        out.close();
        read.close();
        socket.close();
        return;
      }

      boolean accessDenied = false;

      while (!isDone) {

        if (accessDenied) {
          System.out.println(
              "Access denied, or no such record exists! \n Type 'help' for commands.");
        }

        System.out.print(user.getUsername() + " commands>");
        msg = read.readLine();
        fetchRecords();
        splitMsg = msg.split("\\s+");

        try {
          if (msg.equalsIgnoreCase("quit")) {
            break;
          } else if (msg.equalsIgnoreCase("help")) {
            printHelp();
          } else if (splitMsg[0].equalsIgnoreCase("records")) {
            printRecords();
            accessDenied = false;
          } else if (splitMsg[0].equalsIgnoreCase("edit") && (accessDenied = hasPermissions(msg))) {
            editRecord(splitMsg[1]);
            fetchRecords();
            accessDenied = false;
          } else if (splitMsg[0].equalsIgnoreCase("read") && (accessDenied = hasPermissions(msg))) {
            printRecord(splitMsg[1]);
            accessDenied = false;
          } else if (splitMsg[0].equalsIgnoreCase("delete")
              && (accessDenied = hasPermissions(msg))) {
            for (Record r : records) {
              if (r.getId() == Long.parseLong(splitMsg[1])) {
                r.delete(user);
                accessDenied = false;
              }
            }
            fetchRecords();
          } else if (splitMsg[0].equalsIgnoreCase("create")
              && (accessDenied = hasPermissions(msg))) {
            createRecord();
            fetchRecords();
            accessDenied = false;
          } else {
            accessDenied = true;
          }
        } catch (Exception e) {
          accessDenied = true;
        }
      }

      ois.close();
      out.close();
      read.close();
      socket.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #22
0
/**
 * This class contains static methods, which are used throughout the project. The methods are used
 * for dumping error output, debugging information, getting the application path, etc.
 *
 * @author BaseX Team 2005-12, BSD License
 * @author Christian Gruen
 */
public final class Util {
  /** Flag for using default standard input. */
  private static final boolean NOCONSOLE = System.console() == null;

  /** Hidden constructor. */
  private Util() {}

  /**
   * Returns an information string for an unexpected exception.
   *
   * @param ex exception
   * @return dummy object
   */
  public static String bug(final Throwable ex) {
    final TokenBuilder tb = new TokenBuilder(BUGINFO);
    tb.add(NL).add("Contact: ").add(MAIL);
    tb.add(NL).add("Version: ").add(TITLE);
    tb.add(NL).add("Java: ").add(System.getProperty("java.vendor"));
    tb.add(", ").add(System.getProperty("java.version"));
    tb.add(NL).add("OS: ").add(System.getProperty("os.name"));
    tb.add(", ").add(System.getProperty("os.arch"));
    tb.add(NL).add("Stack Trace: ");
    for (final String e : toArray(ex)) tb.add(NL).add(e);
    return tb.toString();
  }

  /**
   * Throws a runtime exception for an unexpected exception.
   *
   * @param ext optional extension
   * @return runtime exception (indicates that an error is raised)
   */
  public static RuntimeException notexpected(final Object... ext) {
    final TokenBuilder tb = new TokenBuilder();
    tb.addExt("%", ext.length == 0 ? "Not Expected." : ext[0]);
    throw new RuntimeException(tb.toString());
  }

  /**
   * Throws a runtime exception for an unimplemented method.
   *
   * @param ext optional extension
   * @return runtime exception (indicates that an error is raised)
   */
  public static RuntimeException notimplemented(final Object... ext) {
    final TokenBuilder tb = new TokenBuilder("Not Implemented");
    if (ext.length != 0) tb.addExt(" (%)", ext);
    throw new UnsupportedOperationException(tb.add('.').toString());
  }

  /**
   * Returns the class name of the specified object.
   *
   * @param o object
   * @return class name
   */
  public static String name(final Object o) {
    return name(o.getClass());
  }

  /**
   * Returns the name of the specified class.
   *
   * @param o object
   * @return class name
   */
  public static String name(final Class<?> o) {
    return o.getSimpleName();
  }

  /**
   * Returns a single line from standard input.
   *
   * @return string
   */
  public static String input() {
    final Scanner sc = new Scanner(System.in);
    return sc.hasNextLine() ? sc.nextLine().trim() : "";
  }

  /**
   * Returns a password from standard input.
   *
   * @return password
   */
  public static String password() {
    // use standard input if no console if defined (such as in Eclipse)
    if (NOCONSOLE) return input();
    // hide password
    final char[] pw = System.console().readPassword();
    return pw != null ? new String(pw) : "";
  }

  /** Prints a newline to standard output. */
  public static void outln() {
    out(NL);
  }

  /**
   * Prints a string to standard output, followed by a newline.
   *
   * @param str output string
   * @param ext text optional extensions
   */
  public static void outln(final Object str, final Object... ext) {
    out((str instanceof byte[] ? Token.string((byte[]) str) : str) + NL, ext);
  }

  /**
   * Prints a string to standard output.
   *
   * @param str output string
   * @param ext text optional extensions
   */
  public static void out(final Object str, final Object... ext) {
    System.out.print(info(str, ext));
  }

  /**
   * Prints a string to standard error, followed by a newline.
   *
   * @param obj error string
   * @param ext text optional extensions
   */
  public static void errln(final Object obj, final Object... ext) {
    err((obj instanceof Throwable ? message((Throwable) obj) : obj) + NL, ext);
  }

  /**
   * Prints a string to standard error.
   *
   * @param string debug string
   * @param ext text optional extensions
   */
  public static void err(final String string, final Object... ext) {
    System.err.print(info(string, ext));
  }

  /**
   * Returns a more user-friendly error message for the specified exception.
   *
   * @param ex throwable reference
   * @return error message
   */
  public static String message(final Throwable ex) {
    debug(ex);
    if (ex instanceof BindException) return SRV_RUNNING;
    if (ex instanceof LoginException) return ACCESS_DENIED;
    if (ex instanceof ConnectException) return CONNECTION_ERROR;
    if (ex instanceof SocketTimeoutException) return TIMEOUT_EXCEEDED;
    if (ex instanceof SocketException) return CONNECTION_ERROR;
    String msg = ex.getMessage();
    if (msg == null || msg.isEmpty()) msg = ex.toString();
    if (ex instanceof FileNotFoundException) return info(RES_NOT_FOUND_X, msg);
    if (ex instanceof UnknownHostException) return info(UNKNOWN_HOST_X, msg);
    return msg;
  }

  /**
   * Prints the exception stack trace if the {@link Prop#debug} flag is set.
   *
   * @param ex exception
   */
  public static void debug(final Throwable ex) {
    if (Prop.debug && ex != null) stack(ex);
  }

  /**
   * Prints a string to standard error if the {@link Prop#debug} flag is set.
   *
   * @param str debug string
   * @param ext text optional extensions
   */
  public static void debug(final Object str, final Object... ext) {
    if (Prop.debug) errln(str, ext);
  }

  /**
   * Prints performance information if the {@link Prop#debug} flag is set.
   *
   * @param perf performance reference
   */
  public static void memory(final Performance perf) {
    if (!Prop.debug) return;
    errln(" " + perf + " (" + Performance.getMemory() + ')');
  }

  /**
   * Returns a string and replaces all % characters by the specified extensions (see {@link
   * TokenBuilder#addExt} for details).
   *
   * @param str string to be extended
   * @param ext text text extensions
   * @return extended string
   */
  public static String info(final Object str, final Object... ext) {
    return Token.string(inf(str, ext));
  }

  /**
   * Returns a token and replaces all % characters by the specified extensions (see {@link
   * TokenBuilder#addExt} for details).
   *
   * @param str string to be extended
   * @param ext text text extensions
   * @return token
   */
  public static byte[] inf(final Object str, final Object... ext) {
    return new TokenBuilder().addExt(str, ext).finish();
  }

  /**
   * Prints the current stack trace to System.err.
   *
   * @param i number of steps to print
   */
  public static void stack(final int i) {
    errln("You're here:");
    final String[] stack = toArray(new Throwable());
    final int l = Math.min(Math.max(2, i + 2), stack.length);
    for (int s = 2; s < l; ++s) errln(stack[s]);
  }

  /**
   * Prints the stack of the specified error to standard error.
   *
   * @param th error/exception instance
   */
  public static void stack(final Throwable th) {
    for (final String s : toArray(th)) errln(s);
  }

  /**
   * Returns an string array representation of the specified throwable.
   *
   * @param th throwable
   * @return string array
   */
  private static String[] toArray(final Throwable th) {
    final StackTraceElement[] st = th.getStackTrace();
    final String[] obj = new String[st.length + 1];
    obj[0] = th.toString();
    for (int i = 0; i < st.length; i++) obj[i + 1] = "  " + st[i];
    return obj;
  }

  /**
   * Starts the specified class in a separate process.
   *
   * @param clz class to start
   * @param args command-line arguments
   * @return reference to a {@link Process} instance representing the started process
   */
  public static Process start(final Class<?> clz, final String... args) {
    final String[] largs = {
      "java",
      "-Xmx" + Runtime.getRuntime().maxMemory(),
      "-cp",
      System.getProperty("java.class.path"),
      clz.getName(),
      "-D",
    };
    final StringList sl = new StringList().add(largs).add(args);

    try {
      return new ProcessBuilder(sl.toArray()).start();
    } catch (final IOException ex) {
      notexpected(ex);
      return null;
    }
  }

  /**
   * Checks if the specified string is "yes", "true" or "on".
   *
   * @param string string to be checked
   * @return result of check
   */
  public static boolean yes(final String string) {
    return Token.eqic(string, YES, TRUE, ON, INFOON);
  }

  /**
   * Checks if the specified string is "no", "false" or "off".
   *
   * @param string string to be checked
   * @return result of check
   */
  public static boolean no(final String string) {
    return Token.eqic(string, NO, FALSE, OFF, INFOOFF);
  }

  /**
   * Returns an info message for the specified flag.
   *
   * @param flag current flag status
   * @return ON/OFF message
   */
  public static String flag(final boolean flag) {
    return flag ? INFOON : INFOOFF;
  }
}
Example #23
0
 public String askWords() {
   System.out.println("Kerem a keresendo kifejezest:");
   String words = System.console().readLine();
   return words;
 }