private static Options createCommandLineOptions() {

    Options options = new Options();

    options.addOption("p", "port", true, "Serial port to which the device is attached");
    options.getOption("p").setRequired(true);

    options.addOption("t", "type", true, "Type of the device");
    options.getOption("t").setRequired(true);

    options.addOption(
        "x", "use64BitMode", false, "Set if you want to write the MAC in 64 bit mode");
    options.getOption("x").setRequired(false);

    options.addOption(
        "r",
        "referencetomacmap",
        true,
        "Optional: a properties file containing device references to MAC address mappings");
    options.addOption(
        "c",
        "configuration",
        true,
        "Optional: file name of a configuration file containing key value pairs to configure the device");
    options.addOption(
        "v", "verbose", false, "Optional: verbose logging output (equal to -l DEBUG)");
    options.addOption(
        "l",
        "logging",
        true,
        "Optional: set logging level (one of [" + Joiner.on(", ").join(LOG_LEVELS) + "])");
    options.addOption("h", "help", false, "Optional: print help");

    return options;
  }
Esempio n. 2
0
 /**
  * @param args
  * @throws Exception
  */
 public static void main(String[] args) throws Exception {
   Options options = initOptions();
   if (args.length == 0) {
     printHelp(options);
   } else {
     CommandLineParser oparser = new GnuParser();
     try {
       CommandLine line = oparser.parse(options, args);
       if (line.hasOption("cvDir")) {
         importDirectory(line);
       } else if (line.hasOption("docPred")) {
         docPredImport(
             options.getOption("docPred").getValue(), options.getOption("label").getValue());
       } else if (line.hasOption("pred")) {
         importPred(line);
       }
     } catch (ParseException e) {
       printHelp(options);
       throw e;
     }
   }
 }
Esempio n. 3
0
 /**
  * Checks that the given option values as returned from e.g. {@link
  * CommandLine#getOptionValues(String)} does exist and contains enough parameters. Prints an error
  * message if not.
  *
  * @param optionValues the values to check
  * @param required the number of required parameters
  * @param options the available command line options
  * @param currentOption the short name of the current option being parsed
  */
 private static final void checkArguments(
     String[] optionValues, int required, Options options, String currentOption) {
   if (optionValues == null || optionValues.length < required) {
     printException(
         "Parsing failed",
         new ParseException(
             "missing parameter for option "
                 + currentOption
                 + " (required: <"
                 + options.getOption(currentOption).getArgName()
                 + ">)"),
         false);
   }
 }
Esempio n. 4
0
 /**
  * Checks that the given option value as returned from e.g. {@link
  * CommandLine#getOptionValue(String)} does exist and prints an error message if not.
  *
  * @param optionValue the value to check
  * @param options the available command line options
  * @param currentOption the short name of the current option being parsed
  */
 static final void checkArguments(
     final String optionValue, final Options options, final String currentOption) {
   if (optionValue == null) {
     printException(
         "Parsing failed",
         new ParseException(
             "missing parameter for option "
                 + currentOption
                 + " (required: <"
                 + options.getOption(currentOption).getArgName()
                 + ">)"),
         false);
   }
 }
Esempio n. 5
0
  /**
   * Queries the command line options for an action to perform.
   *
   * <pre>
   * <code>
   * > java -jar scalaris.jar -help
   * usage: scalaris [Options]
   *  -b,--minibench                   run mini benchmark
   *  -d,--delete <key> <[timeout]>    delete an item (default timeout: 2000ms)
   *                                   WARNING: This function can lead to
   *                                   inconsistent data (e.g. deleted items
   *                                   can re-appear). Also when re-creating an
   *                                   item the version before the delete can
   *                                   re-appear.
   *  -g,--getsubscribers <topic>      get subscribers of a topic
   *  -h,--help                        print this message
   *  -lh,--localhost                  gets the local host's name as known to
   *                                   Java (for debugging purposes)
   *  -p,--publish <topic> <message>   publish a new message for the given
   *                                   topic
   *  -r,--read <key>                  read an item
   *  -s,--subscribe <topic> <url>     subscribe to a topic
   *  -u,--unsubscribe <topic> <url>   unsubscribe from a topic
   *  -v,--verbose                     print verbose information, e.g. the
   *                                   properties read
   *  -w,--write <key> <value>         write an item
   * </code>
   * </pre>
   *
   * @param args command line arguments
   */
  public static void main(String[] args) {
    boolean verbose = false;
    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    Options options = getOptions();
    try {
      line = parser.parse(options, args);
    } catch (ParseException e) {
      printException("Parsing failed", e, false);
    }

    if (line.hasOption("verbose")) {
      verbose = true;
      ConnectionFactory.getInstance().printProperties();
    }

    if (line.hasOption("minibench")) {
      Benchmark.minibench();
    } else if (line.hasOption("r")) { // read
      String key = line.getOptionValue("read");
      checkArguments(key, options, "r");
      try {
        Scalaris sc = new Scalaris();
        String value = sc.read(key);
        System.out.println("read(" + key + ") == " + value);
      } catch (ConnectionException e) {
        printException("read failed with connection error", e, verbose);
      } catch (TimeoutException e) {
        printException("read failed with timeout", e, verbose);
      } catch (NotFoundException e) {
        printException("read failed with not found", e, verbose);
      } catch (UnknownException e) {
        printException("read failed with unknown", e, verbose);
      }
    } else if (line.hasOption("w")) { // write
      String[] optionValues = line.getOptionValues("write");
      checkArguments(optionValues, 2, options, "w");
      String key = optionValues[0];
      String value = optionValues[1];
      try {
        Scalaris sc = new Scalaris();
        sc.write(key, value);
        System.out.println("write(" + key + ", " + value + ")");
      } catch (ConnectionException e) {
        printException("write failed with connection error", e, verbose);
      } catch (TimeoutException e) {
        printException("write failed with timeout", e, verbose);
      } catch (UnknownException e) {
        printException("write failed with unknown", e, verbose);
      }
    } else if (line.hasOption("p")) { // publish
      String[] optionValues = line.getOptionValues("publish");
      checkArguments(optionValues, 2, options, "p");
      String topic = optionValues[0];
      String content = optionValues[1];
      if (content == null) {
        // parsing methods of commons.cli only checks the first argument :(
        printException(
            "Parsing failed", new ParseException("missing content for option p"), verbose);
      }
      try {
        Scalaris sc = new Scalaris();
        sc.publish(topic, content);
        System.out.println("publish(" + topic + ", " + content + ")");
      } catch (ConnectionException e) {
        printException("publish failed with connection error", e, verbose);
      }
    } else if (line.hasOption("s")) { // subscribe
      String[] optionValues = line.getOptionValues("subscribe");
      checkArguments(optionValues, 2, options, "s");
      String topic = optionValues[0];
      String url = optionValues[1];
      try {
        Scalaris sc = new Scalaris();
        sc.subscribe(topic, url);
        System.out.println("subscribe(" + topic + ", " + url + ")");
      } catch (ConnectionException e) {
        printException("subscribe failed with connection error", e, verbose);
      } catch (TimeoutException e) {
        printException("subscribe failed with timeout", e, verbose);
      } catch (UnknownException e) {
        printException("subscribe failed with unknown", e, verbose);
      }
    } else if (line.hasOption("u")) { // unsubscribe
      String[] optionValues = line.getOptionValues("unsubscribe");
      checkArguments(optionValues, 2, options, "u");
      String topic = optionValues[0];
      String url = optionValues[1];
      try {
        Scalaris sc = new Scalaris();
        sc.unsubscribe(topic, url);
        System.out.println("unsubscribe(" + topic + ", " + url + ")");
      } catch (ConnectionException e) {
        printException("unsubscribe failed with connection error", e, verbose);
      } catch (TimeoutException e) {
        printException("unsubscribe failed with timeout", e, verbose);
      } catch (NotFoundException e) {
        printException("unsubscribe failed with not found", e, verbose);
      } catch (UnknownException e) {
        printException("unsubscribe failed with unknown", e, verbose);
      }
    } else if (line.hasOption("g")) { // getsubscribers
      String topic = line.getOptionValue("getsubscribers");
      checkArguments(topic, options, "g");
      try {
        Scalaris sc = new Scalaris();
        ArrayList<String> subscribers = sc.getSubscribers(topic);
        System.out.println("getSubscribers(" + topic + ") == " + subscribers);
      } catch (ConnectionException e) {
        printException("getSubscribers failed with connection error", e, verbose);
      } catch (UnknownException e) {
        printException("getSubscribers failed with unknown error", e, verbose);
      }
    } else if (line.hasOption("d")) { // delete
      String[] optionValues = line.getOptionValues("delete");
      checkArguments(optionValues, 1, options, "d");
      String key = optionValues[0];
      int timeout = 2000;
      if (optionValues.length >= 2) {
        try {
          timeout = Integer.parseInt(optionValues[1]);
        } catch (Exception e) {
          printException(
              "Parsing failed",
              new ParseException(
                  "wrong type for timeout parameter of option d"
                      + " (parameters: <"
                      + options.getOption("d").getArgName()
                      + ">)"),
              verbose);
        }
      }
      try {
        Scalaris sc = new Scalaris();
        sc.delete(key, timeout);
        DeleteResult deleteResult = sc.getLastDeleteResult();
        System.out.println(
            "delete("
                + key
                + ", "
                + timeout
                + "): "
                + deleteResult.ok
                + " ok, "
                + deleteResult.locks_set
                + " locks_set, "
                + deleteResult.undef
                + " undef");
      } catch (ConnectionException e) {
        printException("delete failed with connection error", e, verbose);
      } catch (TimeoutException e) {
        printException("delete failed with timeout", e, verbose);
      } catch (NodeNotFoundException e) {
        printException("delete failed with node not found", e, verbose);
      } catch (UnknownException e) {
        printException("delete failed with unknown error", e, verbose);
      }
    } else if (line.hasOption("lh")) { // get local host name
      System.out.println(ConnectionFactory.getLocalhostName());
    } else {
      // print help if no other option was given
      //		if (line.hasOption("help")) {
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp("scalaris [Options]", getOptions());
    }
  }
Esempio n. 6
0
  /**
   * Queries the command line options for an action to perform.
   *
   * <pre>
   * <code>
   * > java -jar scalaris.jar --help
   * usage: scalaris [Options]
   *  -h,--help                                   print this message
   *  -v,--verbose                                print verbose information,
   *                                              e.g. the properties read
   *  -lh,--localhost                             gets the local host's name as
   *                                              known to Java (for debugging
   *                                              purposes)
   *  -b,--minibench <[ops]> <[tpn]> <[benchs]>   run selected mini
   *                                              benchmark(s) [1|...|18|all]
   *                                              (default: all benchmarks, 500
   *                                              operations, 10 threads per
   *                                              Scalaris node)
   *  -m,--monitor <node>                         print monitoring information
   *  -r,--read <key>                             read an item
   *  -w,--write <key> <value>                    write an item
   *     --test-and-set <key> <old> <new>         atomic test and set, i.e.
   *                                              write <key> to <new> if the
   *                                              current value is <old>
   *  -d,--delete <key> <[timeout]>               delete an item (default
   *                                              timeout: 2000ms)
   *                                              WARNING: This function can
   *                                              lead to inconsistent data
   *                                              (e.g. deleted items can
   *                                              re-appear). Also when
   *                                              re-creating an item the
   *                                              version before the delete can
   *                                              re-appear.
   *  -jmx,--jmxservice <node>                    starts a service exposing
   *                                              Scalaris monitoring values
   *                                              via JMX
   * </code>
   * </pre>
   *
   * In order to override node and cookie to use for a connection, specify the
   * <tt>scalaris.node</tt> or <tt>scalaris.cookie</tt> system properties. Their values will be used
   * instead of the values defined in the config file!
   *
   * @param args command line arguments
   */
  public static void main(final String[] args) {
    boolean verbose = false;
    final CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    final Options options = getOptions();
    try {
      line = parser.parse(options, args);
    } catch (final ParseException e) {
      printException("Parsing failed", e, false);
      return; // will not be reached since printException exits
    }

    if (line.hasOption("verbose")) {
      verbose = true;
      ConnectionFactory.getInstance().printProperties();
    }

    if (line.hasOption("minibench")) {
      final String[] optionValues = line.getOptionValues("minibench");
      int nrOperations = 500;
      int threadsPerNode = 10;
      final HashSet<Integer> benchmarks = new HashSet<Integer>(10);
      boolean all = false;
      if (optionValues != null) {
        checkArguments(optionValues, 0, options, "b");
        if (optionValues.length >= 1) {
          nrOperations = Integer.parseInt(optionValues[0]);
        }
        if (optionValues.length >= 2) {
          threadsPerNode = Integer.parseInt(optionValues[1]);
        }
        if (optionValues.length >= 3) {
          for (int i = 2; i < Math.min(20, optionValues.length); ++i) {
            final String benchmarks_str = optionValues[i];
            if (benchmarks_str.equals("all")) {
              all = true;
            } else {
              benchmarks.add(Integer.parseInt(benchmarks_str));
            }
          }
        }
      } else {
        all = true;
      }
      if (all) {
        for (int i = 1; i <= 18; ++i) {
          benchmarks.add(i);
        }
      }
      Benchmark.minibench(nrOperations, threadsPerNode, benchmarks);
    } else if (line.hasOption("r")) { // read
      final String key = line.getOptionValue("read");
      checkArguments(key, options, "r");
      try {
        final TransactionSingleOp sc = new TransactionSingleOp();
        final String value = sc.read(key).value().toString();
        System.out.println("read(" + key + ") == " + value);
      } catch (final ConnectionException e) {
        printException("read failed with connection error", e, verbose);
      } catch (final NotFoundException e) {
        printException("read failed with not found", e, verbose);
      } catch (final UnknownException e) {
        printException("read failed with unknown", e, verbose);
      }
    } else if (line.hasOption("w")) { // write
      final String[] optionValues = line.getOptionValues("write");
      checkArguments(optionValues, 2, options, "w");
      final String key = optionValues[0];
      final String value = optionValues[1];
      try {
        final TransactionSingleOp sc = new TransactionSingleOp();
        sc.write(key, value);
        System.out.println("write(" + key + ", " + value + "): ok");
      } catch (final ConnectionException e) {
        printException("write failed with connection error", e, verbose);
      } catch (final AbortException e) {
        printException("write failed with abort", e, verbose);
      } catch (final UnknownException e) {
        printException("write failed with unknown", e, verbose);
      }
    } else if (line.hasOption("test-and-set")) { // test_and_set
      final String[] optionValues = line.getOptionValues("test-and-set");
      checkArguments(optionValues, 3, options, "test-and-set");
      final String key = optionValues[0];
      final String oldValue = optionValues[1];
      final String newValue = optionValues[2];
      try {
        final TransactionSingleOp sc = new TransactionSingleOp();
        sc.testAndSet(key, oldValue, newValue);
        System.out.println("testAndSet(" + key + ", " + oldValue + ", " + newValue + "): ok");
      } catch (final ConnectionException e) {
        printException("testAndSet failed with connection error", e, verbose);
      } catch (final AbortException e) {
        printException("testAndSet failed with abort", e, verbose);
      } catch (final UnknownException e) {
        printException("testAndSet failed with unknown", e, verbose);
      } catch (final NotFoundException e) {
        printException("testAndSet failed with not found", e, verbose);
      } catch (final KeyChangedException e) {
        printException(
            "testAndSet failed with key changed (current value: "
                + e.getOldValue().toString()
                + ")",
            e,
            verbose);
      }
    } else if (line.hasOption("d")) { // delete
      final String[] optionValues = line.getOptionValues("delete");
      checkArguments(optionValues, 1, options, "d");
      final String key = optionValues[0];
      int timeout = 2000;
      if (optionValues.length >= 2) {
        try {
          timeout = Integer.parseInt(optionValues[1]);
        } catch (final Exception e) {
          printException(
              "Parsing failed",
              new ParseException(
                  "wrong type for timeout parameter of option d"
                      + " (parameters: <"
                      + options.getOption("d").getArgName()
                      + ">)"),
              verbose);
        }
      }
      try {
        final ReplicatedDHT sc = new ReplicatedDHT();
        final DeleteResult deleteResult = sc.delete(key, timeout);
        System.out.println(
            "delete("
                + key
                + ", "
                + timeout
                + "): "
                + deleteResult.ok
                + " ok, "
                + deleteResult.locks_set
                + " locks_set, "
                + deleteResult.undef
                + " undef");
      } catch (final ConnectionException e) {
        printException("delete failed with connection error", e, verbose);
      } catch (final TimeoutException e) {
        printException("delete failed with timeout", e, verbose);
      } catch (final UnknownException e) {
        printException("delete failed with unknown error", e, verbose);
      }
    } else if (line.hasOption("lh")) { // get local host name
      System.out.println(ConnectionFactory.getLocalhostName());
    } else if (line.hasOption("monitor")) { // print monitoring data
      final String node = line.getOptionValue("monitor");
      checkArguments(node, options, "monitor");
      try {
        final Monitor monitor = new Monitor(node);
        final GetNodeInfoResult nodeInfo = monitor.getNodeInfo();
        final GetNodePerformanceResult nodePerf = monitor.getNodePerformance();
        final GetServiceInfoResult srvInfo = monitor.getServiceInfo();
        final GetServicePerformanceResult srvPerf = monitor.getServicePerformance();

        final Double nodePerfCurLatAvg = Monitor.getCurrentPerfValue(nodePerf.latencyAvg);
        final Double nodePerfCurLatStddev = Monitor.getCurrentPerfValue(nodePerf.latencyStddev);
        final Double srvPerfCurLatAvg = Monitor.getCurrentPerfValue(srvPerf.latencyAvg);
        final Double srcPerfCurLatStddev = Monitor.getCurrentPerfValue(srvPerf.latencyStddev);

        final DecimalFormat df = new DecimalFormat("0.##");
        System.out.println("== Node Info ==");
        System.out.println("Scalaris version: " + nodeInfo.scalarisVersion);
        System.out.println("Erlang   version: " + nodeInfo.erlangVersion);
        System.out.println("# of DHT nodes  : " + nodeInfo.dhtNodes);
        System.out.println("== Service Info (from mgmt_server) ==");
        System.out.println("Total # of nodes: " + srvInfo.nodes);
        System.out.println("Total load      : " + srvInfo.totalLoad);
        System.out.println("== Node Performance ==");
        System.out.println(
            "Current latency : "
                + (nodePerfCurLatAvg == null ? "n/a" : df.format(nodePerfCurLatAvg)));
        System.out.println(
            "Current stddev  : "
                + (nodePerfCurLatStddev == null ? "n/a" : df.format(nodePerfCurLatStddev)));
        System.out.println("== Service Performance ==");
        System.out.println(
            "Current latency : "
                + (srvPerfCurLatAvg == null ? "n/a" : df.format(srvPerfCurLatAvg)));
        System.out.println(
            "Current stddev  : "
                + (srcPerfCurLatStddev == null ? "n/a" : df.format(srcPerfCurLatStddev)));
      } catch (final ConnectionException e) {
        printException("monitor failed with connection error", e, verbose);
      } catch (final UnknownException e) {
        printException("monitor failed with unknown error", e, verbose);
      }
    } else if (line.hasOption("jmx")) { // start JMX monitoring service
      final String node = line.getOptionValue("jmx");
      checkArguments(node, options, "jmx");
      startJmxService(node, verbose);
    } else {
      // print help if no other option was given
      //        if (line.hasOption("help")) {
      final HelpFormatter formatter = new HelpFormatter();
      formatter.setOptionComparator(
          new Comparator<Option>() {
            private int optionToInt(final Option option) {
              if (option.getLongOpt().equals("help")) {
                return 1;
              } else if (option.getLongOpt().equals("verbose")) {
                return 2;
              } else if (option.getLongOpt().equals("localhost")) {
                return 3;
              } else if (option.getLongOpt().equals("minibench")) {
                return 4;
              } else if (option.getLongOpt().equals("monitor")) {
                return 5;
              } else if (option.getLongOpt().equals("read")) {
                return 6;
              } else if (option.getLongOpt().equals("write")) {
                return 7;
              } else if (option.getLongOpt().equals("test-and-set")) {
                return 8;
              } else if (option.getLongOpt().equals("add-del-on-list")) {
                return 9;
              } else if (option.getLongOpt().equals("add-on-nr")) {
                return 10;
              } else if (option.getLongOpt().equals("delete")) {
                return 11;
              } else if (option.getLongOpt().equals("jmxservice")) {
                return 12;
              } else {
                return 13;
              }
            }

            public int compare(final Option arg0, final Option arg1) {
              final int arg0_i = optionToInt(arg0);
              final int arg1_i = optionToInt(arg1);
              if (arg0_i < arg1_i) {
                return -1;
              } else if (arg0_i == arg1_i) {
                return 0;
              } else {
                return 1;
              }
            }
          });
      formatter.printHelp("scalaris [Options]", getOptions());
      if (!line.hasOption("help")) {
        System.exit(1);
      }
    }
  }
Esempio n. 7
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");
      }
    }
  }
 private CommandLineOption getOption(String optionName) {
   final CommandLineOption option = (CommandLineOption) options.getOption(optionName);
   assert option != null : String.format("Option [%s] does not exist", optionName);
   return option;
 }