Ejemplo n.º 1
0
  /**
   * Load the Configuration file with the values from the command line and config files, and place
   * stuff in the DistrubutedCacheService as needed
   *
   * @param conf The Configuration to populate
   * @param args The command line arguments
   * @throws Exception
   */
  public static void initalizeConf(Configuration conf, String[] args) throws Exception {
    // Parse the arguments and make sure the required args are there
    final CommandLine commandLine;
    final Options options = constructGnuOptions();
    try {
      commandLine = new GnuParser().parse(options, args);
    } catch (MissingOptionException ex) {
      HelpFormatter help = new HelpFormatter();
      help.printHelp("hadoop jar <jarFile> " + FrameworkDriver.class.getCanonicalName(), options);
      return;
    } catch (Exception ex) {
      ex.printStackTrace();
      return;
    }

    final String userConfFilePath = commandLine.getOptionValue("amino_config_file_path", "");
    final String aminoDefaultConfigPath = commandLine.getOptionValue("amino_default_config_path");
    final String baseDir = commandLine.getOptionValue("base_dir");

    stopOnFirstPhase = commandLine.hasOption("stop");

    // Set the base dir config value if it was provided.
    if (StringUtils.isNotEmpty(baseDir)) {
      conf.set(AminoConfiguration.BASE_DIR, baseDir);
    }

    conf.set(AminoConfiguration.DEFAULT_CONFIGURATION_PATH_KEY, aminoDefaultConfigPath);

    // create a single DistributedCacheService so that multiple cache entries are deduped.
    // Cache files are added after each config is loaded in case the the property value changes.
    final DistributedCacheService distributedCacheService = new DistributedCacheService();

    // 1. load AminoDefaults
    AminoConfiguration.loadAndMergeWithDefault(conf, true);
    distributedCacheService.addFilesToDistributedCache(conf);

    // 2. load user config files, allowing them to overwrite
    if (!StringUtils.isEmpty(userConfFilePath)) {
      for (String path : getUserConfigFiles(userConfFilePath)) {
        Configuration userConf = new Configuration(false);
        logger.info("Grabbing configuration information from: " + path);
        userConf.addResource(new FileInputStream(path));
        HadoopConfigurationUtils.mergeConfs(conf, userConf);
      }
    }
    distributedCacheService.addFilesToDistributedCache(conf);

    // 3. load command line arguments as properties, allowing them to overwrite
    final Properties propertyOverrides = commandLine.getOptionProperties("property_override");
    for (Object key : propertyOverrides.keySet()) {
      conf.set((String) key, (String) propertyOverrides.get(key));
    }
    distributedCacheService.addFilesToDistributedCache(conf);
  }
Ejemplo n.º 2
0
  private void parseCmdLine(String[] args) {
    CommandLineParser parser = new PosixParser();

    Options options = new Options();
    options.addOption("v", "version", false, "Q2's version");
    options.addOption("d", "deploydir", true, "Deployment directory");
    options.addOption("r", "recursive", false, "Deploy subdirectories recursively");
    options.addOption("h", "help", false, "Usage information");
    options.addOption("C", "config", true, "Configuration bundle");
    options.addOption("e", "encrypt", true, "Encrypt configuration bundle");
    options.addOption("i", "cli", false, "Command Line Interface");
    options.addOption("c", "command", true, "Command to execute");

    try {
      CommandLine line = parser.parse(options, args);
      if (line.hasOption("v")) {
        displayVersion();
        System.exit(0);
      }
      if (line.hasOption("h")) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("Q2", options);
        System.exit(0);
      }
      if (line.hasOption("c")) {
        cli = new CLI(this, line.getOptionValue("c"), line.hasOption("i"));
      } else if (line.hasOption("i")) cli = new CLI(this, null, true);

      String dir = DEFAULT_DEPLOY_DIR;
      if (line.hasOption("d")) {
        dir = line.getOptionValue("d");
      }
      recursive = line.hasOption("r");
      this.deployDir = new File(dir);
      if (line.hasOption("C")) deployBundle(new File(line.getOptionValue("C")), false);
      if (line.hasOption("e")) deployBundle(new File(line.getOptionValue("e")), true);
    } catch (MissingArgumentException e) {
      System.out.println("ERROR: " + e.getMessage());
      System.exit(1);
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
Ejemplo n.º 3
0
  public static void main(String[] args) {

    String formatstr = "ws [--in][--out][--dd][--sw][-h]";
    Options opt = new Options();
    // opt.addOption(OptionBuilder.withArgName("in").hasArg().withDescription("search for buildfile
    // towards the root of the filesystem and use it").create("O"));
    opt.addOption(
        OptionBuilder.withLongOpt("in")
            .withDescription("file path of those files need to be processed")
            .withValueSeparator('=')
            .hasArg()
            .create());
    opt.addOption(
        OptionBuilder.withLongOpt("out")
            .withDescription("file path to store result")
            .withValueSeparator('=')
            .hasArg()
            .create());
    opt.addOption(
        OptionBuilder.withLongOpt("dd")
            .withDescription("file path of dictionary")
            .withValueSeparator('=')
            .hasArg()
            .create());
    opt.addOption(
        OptionBuilder.withLongOpt("sw")
            .withDescription("file path of stop words")
            .withValueSeparator('=')
            .hasArg()
            .create());
    opt.addOption("h", "help", false, "print help for the command.");

    if (args.length == 0) {
      HelpFormatter hf = new HelpFormatter();
      hf.printHelp(formatstr, "", opt, "");
      return;
    } else {
      parse_args(args, formatstr, opt);
    }
  }
Ejemplo n.º 4
0
  private static void parse_args(String[] args, String formatstr, Options opt) {
    HelpFormatter formatter = new HelpFormatter();
    CommandLineParser parser = new PosixParser();
    CommandLine cl = null;

    try {
      cl = parser.parse(opt, args);
    } catch (ParseException e) {
      formatter.printHelp(formatstr, opt); // 如果发生异常,则打印出帮助信息
    }

    if (cl.hasOption("in") && cl.hasOption("out") && cl.hasOption("dd") && cl.hasOption("sw")) {
      String stopWordsPath = cl.getOptionValue("sw");
      String inPath = cl.getOptionValue("in");
      String outPath = cl.getOptionValue("out");
      String dicPath = cl.getOptionValue("dd");
      processOperation(stopWordsPath, inPath, outPath, dicPath);
    } else {
      HelpFormatter hf = new HelpFormatter();
      hf.printHelp(formatstr, "", opt, "");
      return;
    }
  }
Ejemplo n.º 5
0
 public void printHelp() {
   HelpFormatter formatter = new HelpFormatter();
   formatter.printHelp(
       "liquibase-sdk [global options] [command] [command options]", globalOptions);
 }
Ejemplo n.º 6
0
 public static void displayHelp(final Options options) {
   final HelpFormatter formatter = new HelpFormatter();
   formatter.printHelp(80, "groovyc [options] <source-files>", "options:", options, "");
 }
Ejemplo n.º 7
0
  public static void main(String[] args) throws Exception {
    String inputFileName = "";
    String inputFileName2 = "";
    String outputFileName = "";
    String solrServerHost = "";
    String keepListFileName = "";
    String filterListFileName = "";
    String searchTerm = "";
    HashMap<String, String> keepGrayList = new HashMap<String, String>();
    HashMap<String, String> filterGrayList = new HashMap<String, String>();
    boolean useAlias = false;

    CommandLineParser parser = new GnuParser();
    Options options = createCLIOptions();
    try {
      CommandLine line = parser.parse(options, args);

      if (line.hasOption("f1")) {
        // get the input file
        inputFileName = line.getOptionValue("f1");
      }
      if (line.hasOption("f2")) {
        inputFileName2 = line.getOptionValue("f2");
      }
      if (line.hasOption("o")) {
        // get the output file
        outputFileName = line.getOptionValue("o");
      }
      if (line.hasOption("s")) {
        // get the server host name
        solrServerHost = line.getOptionValue("s");
      }
      if (line.hasOption("term")) {
        searchTerm = line.getOptionValue("term");
      }
      if (line.hasOption("a")) {
        useAlias = true;
      }
      if (line.hasOption("k")) {
        keepListFileName = line.getOptionValue("k");
      }
      if (line.hasOption("r")) {
        filterListFileName = line.getOptionValue("r");
      }
    } catch (ParseException exp) {
      log.warning("Command line parsing failed.  Reason:" + exp.getMessage());
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp("pubcrawl", options);
      System.exit(1);
    }

    if (isEmpty(outputFileName) || isEmpty(inputFileName) && isEmpty(searchTerm)) {
      // missing required elements, print usage and exit
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp("pubcrawl", options);
      System.exit(1);
    }

    if (!isEmpty(keepListFileName)) {
      // need to load the keepList hashmap
      FileReader inputReader = new FileReader(keepListFileName);
      BufferedReader bufReader = new BufferedReader(inputReader);
      String keepTerm = bufReader.readLine();
      while (keepTerm != null) {
        String[] keepInfoArr = keepTerm.trim().split("\t");
        keepGrayList.put(keepInfoArr[0].toLowerCase(), keepInfoArr[1]);
        keepTerm = bufReader.readLine();
      }
      bufReader.close();
    }

    log.info("loading filterlist filename");
    if (!isEmpty(filterListFileName)) {
      // need to load the filterlist hashmap
      FileReader inputReader = new FileReader(filterListFileName);
      BufferedReader bufReader = new BufferedReader(inputReader);
      String filterTerm = bufReader.readLine();
      while (filterTerm != null) {
        String[] filterInfoArr = filterTerm.trim().split("\t");
        filterGrayList.put(filterInfoArr[0].toLowerCase(), filterInfoArr[1]);
        filterTerm = bufReader.readLine();
      }
      bufReader.close();
    }

    SolrServer server = getSolrServer(solrServerHost);

    String logname = outputFileName + "_log.out";
    // create output files
    FileWriter logFileStream = new FileWriter(logname);
    BufferedWriter logFileOut = new BufferedWriter(logFileStream);
    FileWriter dataResultsStream = new FileWriter(outputFileName);
    BufferedWriter dataResultsOut = new BufferedWriter(dataResultsStream);

    final Map<String, Integer> singleCountMap = new HashMap<String, Integer>();
    final List<String> term2List = new ArrayList<String>();

    // now load the appropriate list of gene terms  - if the second file name wasn't entered
    if (isEmpty(inputFileName2)) {
      String sql = "Select term1,count from singletermcount";
      if (useAlias) {
        sql = "Select alias,count from singletermcount_alias";
      }

      JdbcTemplate jdbcTemplate = getJdbcTemplate();
      jdbcTemplate.query(
          sql,
          new ResultSetExtractor() {
            public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
              while (rs.next()) {
                String geneName = rs.getString(1).trim();
                int count = rs.getInt(2);
                singleCountMap.put(geneName.toLowerCase(), count);
                if (count > 0) {
                  term2List.add(geneName.toLowerCase());
                }
              }
              return null;
            }
          });
    } else { // have a second input file, so read the file in and put those as the terms in the
             // term2List, set the SingleCountMap to empty
      FileReader inputReader2 = new FileReader(inputFileName2);
      BufferedReader bufReader2 = new BufferedReader(inputReader2);
      String searchTerm2 = bufReader2.readLine();
      while (searchTerm2 != null) {
        term2List.add(searchTerm2.trim().toLowerCase());
        searchTerm2 = bufReader2.readLine();
      }
    }

    Long totalDocCount = getTotalDocCount(server);
    logFileOut.write("Total doc count: " + totalDocCount);
    Pubcrawl p = new Pubcrawl();
    if (isEmpty(inputFileName)) { // entered term option, just have one to calculate
      SearchTermAndList searchTermArray = getTermAndTermList(searchTerm.trim(), useAlias, false);
      Long searchTermCount =
          getTermCount(server, singleCountMap, searchTermArray, filterGrayList, keepGrayList);

      ExecutorService pool = Executors.newFixedThreadPool(32);
      Set<Future<NGDItem>> set = new HashSet<Future<NGDItem>>();
      Date firstTime = new Date();

      for (String secondTerm : term2List) {
        SearchTermAndList secondTermArray = getTermAndTermList(secondTerm, useAlias, false);
        long secondTermCount =
            getTermCount(server, singleCountMap, secondTermArray, filterGrayList, keepGrayList);
        Callable<NGDItem> callable =
            p
            .new SolrCallable(
                searchTermArray,
                secondTermArray,
                searchTermCount,
                secondTermCount,
                server,
                useAlias,
                filterGrayList,
                keepGrayList,
                totalDocCount);
        Future<NGDItem> future = pool.submit(callable);
        set.add(future);
      }

      for (Future<NGDItem> future : set) {
        dataResultsOut.write(future.get().printItem());
      }

      Date secondTime = new Date();
      logFileOut.write(
          "First set of queries took "
              + (secondTime.getTime() - firstTime.getTime()) / 1000
              + " seconds.\n");
      logFileOut.flush();
      logFileOut.close();
      dataResultsOut.flush();
      dataResultsOut.close();
      pool.shutdown();

    } else {

      FileReader inputReader = new FileReader(inputFileName);
      BufferedReader bufReader = new BufferedReader(inputReader);
      String fileSearchTerm = bufReader.readLine();
      SearchTermAndList searchTermArray = getTermAndTermList(fileSearchTerm, useAlias, false);
      Long searchTermCount =
          getTermCount(server, singleCountMap, searchTermArray, filterGrayList, keepGrayList);

      // do this once with a lower amount of threads, in case we are running on a server where new
      // caching is taking place
      ExecutorService pool = Executors.newFixedThreadPool(32);
      List<Future<NGDItem>> set = new ArrayList<Future<NGDItem>>();
      long firstTime = currentTimeMillis();
      int count = 0;

      for (String secondTerm : term2List) {
        count++;
        SearchTermAndList secondTermArray = getTermAndTermList(secondTerm, useAlias, false);
        long secondTermCount =
            getTermCount(server, singleCountMap, secondTermArray, filterGrayList, keepGrayList);
        Callable<NGDItem> callable =
            p
            .new SolrCallable(
                searchTermArray,
                secondTermArray,
                searchTermCount,
                secondTermCount,
                server,
                useAlias,
                filterGrayList,
                keepGrayList,
                totalDocCount);
        Future<NGDItem> future = pool.submit(callable);
        set.add(future);

        if (count > 5000) {
          for (Future<NGDItem> futureItem : set) {
            dataResultsOut.write(futureItem.get().printItem());
            futureItem = null;
          }
          count = 0;
          set.clear();
        }
      }

      for (Future<NGDItem> future : set) {
        dataResultsOut.write(future.get().printItem());
      }

      long secondTime = currentTimeMillis();
      logFileOut.write(
          "First set of queries took " + (secondTime - firstTime) / 1000 + " seconds.\n");
      logFileOut.flush();
      set.clear();

      pool = Executors.newFixedThreadPool(32);
      fileSearchTerm = bufReader.readLine();
      count = 0;
      while (fileSearchTerm != null) {
        searchTermArray = getTermAndTermList(fileSearchTerm, useAlias, false);
        searchTermCount =
            getTermCount(server, singleCountMap, searchTermArray, filterGrayList, keepGrayList);
        secondTime = currentTimeMillis();
        for (String secondTerm : term2List) {
          SearchTermAndList secondTermArray = getTermAndTermList(secondTerm, useAlias, false);
          long secondTermCount =
              getTermCount(server, singleCountMap, secondTermArray, filterGrayList, keepGrayList);
          Callable<NGDItem> callable =
              p
              .new SolrCallable(
                  searchTermArray,
                  secondTermArray,
                  searchTermCount,
                  secondTermCount,
                  server,
                  useAlias,
                  filterGrayList,
                  keepGrayList,
                  totalDocCount);
          Future<NGDItem> future = pool.submit(callable);
          set.add(future);
          count++;
          if (count > 5000) {
            for (Future<NGDItem> futureItem : set) {
              dataResultsOut.write(futureItem.get().printItem());
              futureItem = null;
            }
            count = 0;
            set.clear();
          }
        }

        for (Future<NGDItem> future : set) {
          dataResultsOut.write(future.get().printItem());
          future = null;
        }

        logFileOut.write("Query took " + (currentTimeMillis() - secondTime) / 1000 + " seconds.\n");
        logFileOut.flush();
        set.clear();
        fileSearchTerm = bufReader.readLine();
      }

      long fourthTime = currentTimeMillis();
      logFileOut.write("Final time: " + (fourthTime - firstTime) / 1000 + " seconds.\n");
      bufReader.close();
      logFileOut.flush();
      logFileOut.close();
      dataResultsOut.flush();
      dataResultsOut.close();
      pool.shutdown();
    }
    System.exit(0);
  }
Ejemplo n.º 8
0
 private static void usage(Options options) {
   HelpFormatter formatter = new HelpFormatter();
   formatter.printHelp(120, SNAAServer.class.getCanonicalName(), null, options, null);
   System.exit(1);
 }
  public static void main(String[] args) {
    String logConfig = System.getProperty("log-config");
    if (logConfig == null) {
      logConfig = "log-config.txt";
    }

    Options options = new Options();
    options.addOption("h", "help", false, "print this message");
    options.addOption("v", "version", false, "output version information and exit");
    options.addOption(OptionBuilder.withDescription("trace mode").withLongOpt("trace").create());
    options.addOption(OptionBuilder.withDescription("debug mode").withLongOpt("debug").create());
    options.addOption(OptionBuilder.withDescription("info mode").withLongOpt("info").create());
    options.addOption(
        OptionBuilder.withArgName("file")
            .hasArg()
            .withDescription(
                "file from which to read the labelled training set in tabular format (reference annotation)")
            .isRequired()
            .withLongOpt("labelled")
            .create("l"));
    options.addOption(
        OptionBuilder.withArgName("file")
            .hasArg()
            .withDescription(
                "file from which to read the translated unlabelled training set in tabular format (one sentence per line, including id)")
            .isRequired()
            .withLongOpt("unlabelled")
            .create("u"));
    options.addOption(
        OptionBuilder.withArgName("file")
            .hasArg()
            .withDescription(
                "file from which to read the translated roles (phrase table: source language \\t target language)")
            .isRequired()
            .withLongOpt("roles")
            .create("r"));
    options.addOption(
        OptionBuilder.withArgName("file")
            .hasArg()
            .withDescription(
                "file in which to write the translated labelled training set in tabular format (aligned with the reference annotation)")
            .isRequired()
            .withLongOpt("output")
            .create("o"));
    options.addOption(
        OptionBuilder.withArgName("int")
            .hasArg()
            .withDescription("example from which to start from")
            .withLongOpt("start")
            .create());

    CommandLineParser parser = new PosixParser();
    CommandLine commandLine = null;

    try {
      commandLine = parser.parse(options, args);

      Properties defaultProps = new Properties();
      try {
        defaultProps.load(new InputStreamReader(new FileInputStream(logConfig), "UTF-8"));
      } catch (Exception e) {
        defaultProps.setProperty("log4j.appender.stdout", "org.apache.log4j.ConsoleAppender");
        defaultProps.setProperty(
            "log4j.appender.stdout.layout.ConversionPattern", "[%t] %-5p (%F:%L) - %m %n");
        defaultProps.setProperty("log4j.appender.stdout.layout", "org.apache.log4j.PatternLayout");
        defaultProps.setProperty("log4j.appender.stdout.Encoding", "UTF-8");
      }

      if (commandLine.hasOption("trace")) {
        defaultProps.setProperty("log4j.rootLogger", "trace,stdout");
      } else if (commandLine.hasOption("debug")) {
        defaultProps.setProperty("log4j.rootLogger", "debug,stdout");
      } else if (commandLine.hasOption("info")) {
        defaultProps.setProperty("log4j.rootLogger", "info,stdout");
      } else {
        if (defaultProps.getProperty("log4j.rootLogger") == null) {
          defaultProps.setProperty("log4j.rootLogger", "info,stdout");
        }
      }
      PropertyConfigurator.configure(defaultProps);

      if (commandLine.hasOption("help") || commandLine.hasOption("version")) {
        throw new ParseException("");
      }

      File labelled = new File(commandLine.getOptionValue("labelled"));
      File unlabelled = new File(commandLine.getOptionValue("unlabelled"));
      File roles = new File(commandLine.getOptionValue("roles"));
      File output = new File(commandLine.getOptionValue("output"));
      try {
        if (commandLine.hasOption("start")) {
          int start = Integer.parseInt(commandLine.getOptionValue("start"));
          new AnnotationMigration(labelled, unlabelled, roles, output, start);
        } else {
          new AnnotationMigration(labelled, unlabelled, roles, output);
        }

      } catch (IOException e) {
        logger.error(e);
      }

    } catch (ParseException exp) {
      if (exp.getMessage().length() > 0) {
        System.err.println("Parsing failed: " + exp.getMessage() + "\n");
      }
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp(
          200,
          "java -Dfile.encoding=UTF-8 -cp dist/dirha.jar org.fbk.cit.hlt.dirha.AnnotationMigration",
          "\n",
          options,
          "\n",
          true);
      System.exit(1);
    }
  }
Ejemplo n.º 10
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");
      }
    }
  }