public static Options parseArgs(String cmdArgs[]) {
      CommandLineParser parser = new GnuParser();
      CmdLineOptions options = getCmdLineOptions();
      try {
        CommandLine cmd = parser.parse(options, cmdArgs, false);

        if (cmd.hasOption(HELP_OPTION)) {
          printUsage(options);
          System.exit(0);
        }

        String[] args = cmd.getArgs();
        if (args.length >= 4 || args.length < 2) {
          String msg = args.length < 2 ? "Missing arguments" : "Too many arguments";
          errorMsg(msg, options);
          System.exit(1);
        }

        String keyspace = args[0];
        String cf = args[1];
        String snapshot = null;
        if (args.length == 3) snapshot = args[2];

        Options opts = new Options(keyspace, cf, snapshot);

        opts.debug = cmd.hasOption(DEBUG_OPTION);
        opts.keepSource = cmd.hasOption(KEEP_SOURCE);

        return opts;
      } catch (ParseException e) {
        errorMsg(e.getMessage(), options);
        return null;
      }
    }
Example #2
0
  private void cli(CliRequest cliRequest) throws Exception {
    //
    // Parsing errors can happen during the processing of the arguments and we prefer not having to
    // check if
    // the logger is null and construct this so we can use an SLF4J logger everywhere.
    //
    slf4jLogger = new Slf4jStdoutLogger();

    CLIManager cliManager = new CLIManager();

    try {
      cliRequest.commandLine = cliManager.parse(cliRequest.args);
    } catch (ParseException e) {
      System.err.println("Unable to parse command line options: " + e.getMessage());
      cliManager.displayHelp(System.out);
      throw e;
    }

    if (cliRequest.commandLine.hasOption(CLIManager.HELP)) {
      cliManager.displayHelp(System.out);
      throw new ExitException(0);
    }

    if (cliRequest.commandLine.hasOption(CLIManager.VERSION)) {
      System.out.println(CLIReportingUtils.showVersion());
      throw new ExitException(0);
    }
  }
  @SuppressWarnings("static-access")
  public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(
        OptionBuilder.withArgName("path")
            .hasArg()
            .withDescription("data file with tweet ids")
            .create(DATA_OPTION));
    options.addOption(
        OptionBuilder.withArgName("path")
            .hasArg()
            .withDescription("output file (*.gz)")
            .create(OUTPUT_OPTION));
    options.addOption(NOFOLLOW_OPTION, NOFOLLOW_OPTION, false, "don't follow 301 redirects");

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
      cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
      System.err.println("Error parsing command line: " + exp.getMessage());
      System.exit(-1);
    }

    if (!cmdline.hasOption(DATA_OPTION) || !cmdline.hasOption(OUTPUT_OPTION)) {
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp(ReadStatuses.class.getName(), options);
      System.exit(-1);
    }

    String data = cmdline.getOptionValue(DATA_OPTION);
    String output = cmdline.getOptionValue(OUTPUT_OPTION);
    boolean noFollow = cmdline.hasOption(NOFOLLOW_OPTION);
    new AsyncEmbeddedJsonStatusBlockCrawler(new File(data), output, noFollow).fetch();
  }
Example #4
0
  // package-level visibility for testing purposes (just usage/errors at this stage)
  // TODO: should we have an 'err' printstream too for ParseException?
  static void processArgs(String[] args, final PrintStream out) {
    Options options = buildOptions();

    try {
      CommandLine cmd = parseCommandLine(options, args);

      if (cmd.hasOption('h')) {
        printHelp(out, options);
      } else if (cmd.hasOption('v')) {
        String version = GroovySystem.getVersion();
        out.println(
            "Groovy Version: "
                + version
                + " JVM: "
                + System.getProperty("java.version")
                + " Vendor: "
                + System.getProperty("java.vm.vendor")
                + " OS: "
                + System.getProperty("os.name"));
      } else {
        // If we fail, then exit with an error so scripting frameworks can catch it
        // TODO: pass printstream(s) down through process
        if (!process(cmd)) {
          System.exit(1);
        }
      }
    } catch (ParseException pe) {
      out.println("error: " + pe.getMessage());
      printHelp(out, options);
    }
  }
  /**
   * Processing the input command line arguments
   *
   * @param args a list of pride db accessions
   */
  private void processCmdArgs(String[] args) {
    try {
      // parse command line input
      CommandLine cmd = cmdParser.parse(cmdOptions, args);

      // get accessions
      java.util.List<Comparable> accs = null;
      if (cmd.hasOption(ACCESSION_CMD)) {
        String accStr = cmd.getOptionValue(ACCESSION_CMD);
        accs = new ArrayList<Comparable>(AccessionUtils.expand(accStr));
      }

      // get user name
      String username = null;
      if (cmd.hasOption(USER_NAME_CMD)) {
        username = cmd.getOptionValue(USER_NAME_CMD);
      }

      // get password
      String password = null;
      if (cmd.hasOption(PASSWORD_CMD)) {
        password = cmd.getOptionValue(PASSWORD_CMD);
      }

      if (accs != null || username != null) {
        OpenValidPrideExperimentTask task =
            new OpenValidPrideExperimentTask(accs, username, password);
        task.setGUIBlocker(new DefaultGUIBlocker(task, GUIBlocker.Scope.NONE, null));
        getDesktopContext().addTask(task);
      }
    } catch (ParseException e) {
      System.err.println("Parsing command line option failed. Reason: " + e.getMessage());
    }
  }
  public static void main(String args[]) {
    File f = new File("resources/archive_hub_dump.nt");
    String name = f.getName();

    CommandLineParser parser = new BasicParser();
    CommandLine cmd;
    try {
      cmd = parser.parse(getCLIOptions(), args);
      if (cmd.hasOption("file")) {
        f = new File(cmd.getOptionValue("file"));
        if (!f.exists()) {
          System.err.println("File/Directory to compress not found.");
          System.exit(0);
        }
      }
      if (cmd.hasOption("name")) {
        name = cmd.getOptionValue("name");
      }
    } catch (ParseException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    HDTEvaluation hdtEval = new HDTEvaluation(name, f);

    try {
      hdtEval.run();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ParserException e) {
      e.printStackTrace();
    }
  }
Example #7
0
  /**
   * Parse the command line.
   *
   * @param args command-line arguments
   * @return line parsed command line
   * @exception ParametersException on error in parameters
   */
  public CommandLine parse(final String args[]) throws ParametersException {
    log.fine("Command line parsing started");

    final CommandLineParser parser = new DefaultParser();
    CommandLine line;
    try {
      line = parser.parse(options, args);
    } catch (final ParseException exception) {
      throw new ParametersException(
          "Failed to parse the command line, exception: " + exception.getMessage());
    }

    fileNames = line.getArgs();

    outputFileNameFlag = line.hasOption("o");
    if (outputFileNameFlag) {
      outputFileName = line.getOptionValue("o");
    }

    crcFileNameFlag = line.hasOption("c");
    if (crcFileNameFlag) {
      crcFileName = line.getOptionValue("c");
    }

    if (line.hasOption("s")) {
      literalStrings = line.getOptionValues("s");
    }

    listCrcFlag = line.hasOption("l");

    hexMode = line.hasOption("x");

    log.fine("Command line parsing completed");
    return line;
  }
Example #8
0
  public static final void main(String[] args) {
    String accessKey = null;
    String secretKey = null;

    Options options = createCommandLineOption();

    CommandLineParser parser = new GnuParser();
    try {
      // parse the command line arguments
      CommandLine line = parser.parse(options, args);

      if (!line.hasOption("ak")) {
        throw new ParseException("AWS Accress Key is missing.");
      }

      if (!line.hasOption("sk")) {
        throw new ParseException("AWS Secret Key is missing.");
      }

      accessKey = line.getOptionValue("ak");
      secretKey = line.getOptionValue("sk");

    } catch (ParseException exp) {
      System.err.println("Parsing failed.  Reason: " + exp.getMessage());
      System.exit(1);
    }

    TargetURLGenerator generator = new TargetURLGenerator();

    generator.setAccessKey(accessKey);
    generator.setSecretKey(secretKey);

    generator.run();
  }
Example #9
0
  @Override
  public int run(String[] args) throws Exception {

    Options options = new Options();
    options.addOption("c", "concurrent", false, "run concurrently with generation");

    GnuParser parser = new GnuParser();
    CommandLine cmd = null;
    try {
      cmd = parser.parse(options, args);
      if (cmd.getArgs().length != 4) {
        throw new ParseException(
            "Did not see expected # of arguments, saw " + cmd.getArgs().length);
      }
    } catch (ParseException e) {
      System.err.println("Failed to parse command line " + e.getMessage());
      System.err.println();
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp(getClass().getSimpleName() + " <output dir> <num reducers>", options);
      System.exit(-1);
    }

    String outputDir = cmd.getArgs()[0];
    int numReducers = Integer.parseInt(cmd.getArgs()[1]);
    String accessKey = cmd.getArgs()[2];
    String secretKey = cmd.getArgs()[3];

    return run(outputDir, numReducers, cmd.hasOption("c"), accessKey, secretKey);
  }
Example #10
0
  /**
   * The main CLI processor
   *
   * @param args command line argument
   */
  public static void main(String[] args) {

    checkJavaVersion();
    String logConfig = System.getProperty("log4j.configuration");
    if (logConfig != null && logConfig.length() > 0) {
      File lc = new File(logConfig);
      if (lc.exists()) {
        PropertyConfigurator.configure(logConfig);
        Properties defaults = loadDefaults();
        try {
          Options o = getOptions();
          CommandLineParser parser = new GnuParser();
          CommandLine cmdline = parser.parse(o, args);
          GdcNotification gdi = new GdcNotification(cmdline, defaults);
          if (!gdi.finishedSucessfuly) {
            System.exit(1);
          }
        } catch (org.apache.commons.cli.ParseException e) {
          l.error("Error parsing command line parameters: " + e.getMessage());
          l.debug("Error parsing command line parameters", e);
        }
      } else {
        l.error(
            "Can't find the logging config. Please configure the logging via the log4j.configuration.");
      }
    } else {
      l.error(
          "Can't find the logging config. Please configure the logging via the log4j.configuration.");
    }
  }
Example #11
0
  @SuppressWarnings("static-access")
  private CommandLine parseArgs(String[] args) throws Exception {
    options = new Options();
    options.addOption(
        OptionBuilder.withDescription("path to output of pwsim algorithm")
            .withArgName("path")
            .hasArg()
            .isRequired()
            .create(PWSIM_OPTION));
    options.addOption(
        OptionBuilder.withDescription("path to output")
            .withArgName("path")
            .hasArg()
            .isRequired()
            .create(OUTPUT_PATH_OPTION));
    options.addOption(
        OptionBuilder.withDescription("source-side raw collection path")
            .withArgName("path")
            .hasArg()
            .isRequired()
            .create(FCOLLECTION_OPTION));
    options.addOption(
        OptionBuilder.withDescription("target-side raw collection path")
            .withArgName("path")
            .hasArg()
            .isRequired()
            .create(ECOLLECTION_OPTION));
    options.addOption(
        OptionBuilder.withDescription("two-letter code for f-language")
            .withArgName("en|de|tr|cs|zh|ar|es")
            .hasArg()
            .isRequired()
            .create(FLANG_OPTION));
    options.addOption(
        OptionBuilder.withDescription("two-letter code for e-language")
            .withArgName("en|de|tr|cs|zh|ar|es")
            .hasArg()
            .isRequired()
            .create(ELANG_OPTION));
    options.addOption(
        OptionBuilder.withDescription("only keep pairs that match these docnos")
            .withArgName("path to sample docnos file")
            .hasArg()
            .create(SAMPLEDOCNOS_OPTION));
    options.addOption(
        OptionBuilder.withDescription("Hadoop option to load external jars")
            .withArgName("jar packages")
            .hasArg()
            .create(LIBJARS_OPTION));

    CommandLine cmdline;
    CommandLineParser parser = new GnuParser();
    try {
      cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
      System.err.println("Error parsing command line: " + exp.getMessage());
      return null;
    }
    return cmdline;
  }
Example #12
0
  public static void main(String[] rawArgs)
      throws FileNotFoundException, UnsupportedEncodingException {

    CommandLineParser parser = new BasicParser();

    Options options = new Options();
    options.addOption("p", "parser", true, "Which parser to use. (stanford | malt)");

    CommandLine line = null;

    try {
      line = parser.parse(options, rawArgs);
    } catch (ParseException exp) {
      System.err.println(exp.getMessage());
      System.exit(1);
    }

    String[] args = line.getArgs();
    String parserName = line.getOptionValue("parser", "stanford");

    System.out.println("Using " + parserName + " parser");

    File evaluationFile = new File(args[0]);
    File outputFile = new File(args[1]);

    BenchmarkBinary evaluation = new BenchmarkBinary(evaluationFile, outputFile, parserName);

    // read evaluation file with sentences annotated with golden statements
    // and run Exemplar over them.
    evaluation.runAndTime();
  }
Example #13
0
  public void runParseTest(
      String fieldTerminator,
      String lineTerminator,
      String encloser,
      String escape,
      boolean encloseRequired)
      throws IOException {

    ClassLoader prevClassLoader = null;

    String[] argv =
        getArgv(true, fieldTerminator, lineTerminator, encloser, escape, encloseRequired);
    runImport(argv);
    try {
      String tableClassName = getTableName();

      argv = getArgv(false, fieldTerminator, lineTerminator, encloser, escape, encloseRequired);
      SqoopOptions opts = new ImportTool().parseArguments(argv, null, null, true);

      CompilationManager compileMgr = new CompilationManager(opts);
      String jarFileName = compileMgr.getJarFilename();

      // Make sure the user's class is loaded into our address space.
      prevClassLoader = ClassLoaderStack.addJarFile(jarFileName, tableClassName);

      JobConf job = new JobConf();
      job.setJar(jarFileName);

      // Tell the job what class we're testing.
      job.set(ReparseMapper.USER_TYPE_NAME_KEY, tableClassName);

      // use local mode in the same JVM.
      ConfigurationHelper.setJobtrackerAddr(job, "local");
      if (!BaseSqoopTestCase.isOnPhysicalCluster()) {
        job.set(CommonArgs.FS_DEFAULT_NAME, CommonArgs.LOCAL_FS);
      }
      String warehouseDir = getWarehouseDir();
      Path warehousePath = new Path(warehouseDir);
      Path inputPath = new Path(warehousePath, getTableName());
      Path outputPath = new Path(warehousePath, getTableName() + "-out");

      job.setMapperClass(ReparseMapper.class);
      job.setNumReduceTasks(0);
      FileInputFormat.addInputPath(job, inputPath);
      FileOutputFormat.setOutputPath(job, outputPath);

      job.setOutputKeyClass(Text.class);
      job.setOutputValueClass(NullWritable.class);

      JobClient.runJob(job);
    } catch (InvalidOptionsException ioe) {
      fail(ioe.toString());
    } catch (ParseException pe) {
      fail(pe.toString());
    } finally {
      if (null != prevClassLoader) {
        ClassLoaderStack.setCurrentClassLoader(prevClassLoader);
      }
    }
  }
  /**
   * *************************************************************************** {@link Runnable}
   * Interface **************************************************************************
   */
  public void run(String[] args) throws IOException {

    if (needsHelp(args)) {
      printHelp();
      System.exit(0);
    }

    try {
      CommandLine cli = _parser.parse(_options, args, true);
      runApplication(cli, args);
    } catch (MissingOptionException ex) {
      System.err.println("Missing argument: " + ex.getMessage());
      printHelp();
    } catch (MissingArgumentException ex) {
      System.err.println("Missing argument: " + ex.getMessage());
      printHelp();
    } catch (UnrecognizedOptionException ex) {
      System.err.println("Unknown argument: " + ex.getMessage());
      printHelp();
    } catch (AlreadySelectedException ex) {
      System.err.println("Argument already selected: " + ex.getMessage());
      printHelp();
    } catch (ParseException ex) {
      System.err.println(ex.getMessage());
      printHelp();
    } catch (TransformSpecificationException ex) {
      System.err.println("error with transform line: " + ex.getLine());
      System.err.println(ex.getMessage());
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Example #15
0
 /**
  * This is the starting point of the compiler.
  *
  * @param args Command line arguments to control the compiler
  */
 public static void main(String[] args) {
   try {
     run(args);
   } catch (FileNotFoundException e) {
     System.err.println("FILE NOT FOUND: " + e.getLocalizedMessage());
     System.exit(FILE_NOT_FOUND_ERROR);
   } catch (ParseException e) {
     System.err.println("PARSE ERROR: " + e.getLocalizedMessage());
     System.exit(PARSE_ERROR);
   } catch (ShadowException e) {
     System.err.println("ERROR IN FILE: " + e.getLocalizedMessage());
     e.printStackTrace();
     System.exit(TYPE_CHECK_ERROR);
   } catch (IOException e) {
     System.err.println("FILE DEPENDENCY ERROR: " + e.getLocalizedMessage());
     e.printStackTrace();
     System.exit(TYPE_CHECK_ERROR);
   } catch (org.apache.commons.cli.ParseException e) {
     System.err.println("COMMAND LINE ERROR: " + e.getLocalizedMessage());
     Arguments.printHelp();
     System.exit(COMMAND_LINE_ERROR);
   } catch (ConfigurationException e) {
     System.err.println("CONFIGURATION ERROR: " + e.getLocalizedMessage());
     Arguments.printHelp();
     System.exit(CONFIGURATION_ERROR);
   } catch (TypeCheckException e) {
     System.err.println("TYPE CHECK ERROR: " + e.getLocalizedMessage());
     System.exit(TYPE_CHECK_ERROR);
   } catch (CompileException e) {
     System.err.println("COMPILATION ERROR: " + e.getLocalizedMessage());
     System.exit(COMPILE_ERROR);
   }
 }
Example #16
0
  public CommandLine parseAndValidateArguments(String[] args) {
    CommandLineParser parser = new DefaultParser();

    CommandLine cmd;
    try {
      cmd = parser.parse(options, args);
    } catch (ParseException e) {
      System.err.println(e.getMessage());
      printHelp();
      return null;
    }

    if (cmd.hasOption(CommandLineOption.HELP.getShortcut())) {
      printHelp();
      return null;
    }

    if (!cmd.hasOption(CommandLineOption.ACCESS_KEY.getShortcut())
        || !cmd.hasOption(CommandLineOption.SECRET_KEY.getShortcut())) {
      System.err.println("Parameters accessKey and secretKey are required.");
      printHelp();
      return null;
    }

    if (!cmd.hasOption(CommandLineOption.VOICE_LIST.getShortcut())) {
      if (!cmd.hasOption(CommandLineOption.INPUT_FILE.getShortcut())
          || !cmd.hasOption(CommandLineOption.OUTPUT_DIR.getShortcut())) {
        System.err.println("Parameters inputFile and outputDir are required.");
        printHelp();
        return null;
      }
    }

    return cmd;
  }
Example #17
0
  public void init(String[] args) throws UserError {
    Context.reset();
    CommandLineParser globalParser = new GnuParser();

    List<String> globalArgs = new ArrayList<String>();

    boolean inGlobal = true;
    for (String arg : args) {
      if (inGlobal) {
        if (arg.startsWith("--")) {
          globalArgs.add(arg);
        } else {
          this.command = arg;
          inGlobal = false;
        }
      } else {
        commandArgs.add(arg);
      }
    }

    try {
      this.globalArguments =
          globalParser.parse(globalOptions, globalArgs.toArray(new String[globalArgs.size()]));
    } catch (ParseException e) {
      throw new UserError("Error parsing global command line argument: " + e.getMessage());
    }
  }
    public static Options parseArgs(String cmdArgs[]) {
      CommandLineParser parser = new GnuParser();
      CmdLineOptions options = getCmdLineOptions();
      try {
        CommandLine cmd = parser.parse(options, cmdArgs, false);

        if (cmd.hasOption(HELP_OPTION)) {
          printUsage(options);
          System.exit(0);
        }

        String[] args = cmd.getArgs();
        if (args.length == 0) {
          System.err.println("No sstables to split");
          printUsage(options);
          System.exit(1);
        }
        Options opts = new Options(Arrays.asList(args));
        opts.debug = cmd.hasOption(DEBUG_OPTION);
        opts.verbose = cmd.hasOption(VERBOSE_OPTION);
        opts.snapshot = !cmd.hasOption(NO_SNAPSHOT_OPTION);
        opts.sizeInMB = DEFAULT_SSTABLE_SIZE;

        if (cmd.hasOption(SIZE_OPTION))
          opts.sizeInMB = Integer.valueOf(cmd.getOptionValue(SIZE_OPTION));

        return opts;
      } catch (ParseException e) {
        errorMsg(e.getMessage(), options);
        return null;
      }
    }
Example #19
0
  public synchronized int run(String[] args) {
    if (instanceExists) {
      throw new IllegalStateException("CLI instance already used");
    }
    instanceExists = true;

    CLIParser parser = new CLIParser("falcondb", FALCON_HELP);
    parser.addCommand(
        HELP_CMD, "", "Display usage for all commands or specified command", new Options(), false);
    parser.addCommand(VERSION_CMD, "", "Show Falcon DB version information", new Options(), false);
    parser.addCommand(CREATE_CMD, "", "Create Falcon DB schema", getOptions(), false);
    parser.addCommand(UPGRADE_CMD, "", "Upgrade Falcon DB schema", getOptions(), false);

    try {
      CLIParser.Command command = parser.parse(args);
      if (command.getName().equals(HELP_CMD)) {
        parser.showHelp();
      } else if (command.getName().equals(VERSION_CMD)) {
        showVersion();
      } else {
        if (!command.getCommandLine().hasOption(SQL_FILE_OPT)
            && !command.getCommandLine().hasOption(RUN_OPT)) {
          throw new Exception("'-sqlfile <FILE>' or '-run' options must be specified");
        }
        CommandLine commandLine = command.getCommandLine();
        String sqlFile =
            (commandLine.hasOption(SQL_FILE_OPT))
                ? commandLine.getOptionValue(SQL_FILE_OPT)
                : File.createTempFile("falcondb-", ".sql").getAbsolutePath();
        boolean run = commandLine.hasOption(RUN_OPT);
        if (command.getName().equals(CREATE_CMD)) {
          createDB(sqlFile, run);
        } else if (command.getName().equals(UPGRADE_CMD)) {
          upgradeDB(sqlFile, run);
        }
        System.out.println("The SQL commands have been written to: " + sqlFile);
        if (!run) {
          System.out.println(
              "WARN: The SQL commands have NOT been executed, you must use the '-run' option");
        }
      }
      return 0;
    } catch (ParseException ex) {
      System.err.println("Invalid sub-command: " + ex.getMessage());
      System.err.println();
      System.err.println(parser.shortHelp());
      return 1;
    } catch (Exception ex) {
      System.err.println();
      System.err.println("Error: " + ex.getMessage());
      System.err.println();
      System.err.println("Stack trace for the error was (for debug purposes):");
      System.err.println("--------------------------------------");
      ex.printStackTrace(System.err);
      System.err.println("--------------------------------------");
      System.err.println();
      return 1;
    }
  }
 private CommandLine parseArguments(final String[] args) {
   try {
     return new DefaultParser().parse(options, args);
   } catch (ParseException e) {
     printHelp(e.getMessage());
     return null;
   }
 }
Example #21
0
  /**
   * Called only in standalone mode
   *
   * @param args
   */
  private void startMetricsServer(String[] args) {
    AnsiConsole.systemInstall();
    String version =
        ((MetricsServer.class.getPackage().getImplementationVersion() != null)
            ? MetricsServer.class.getPackage().getImplementationVersion()
            : "'undefined'");
    System.out.println(
        ansi()
            .fg(RED)
            .render("@|bold Starting BigLoupe Metrics server version |@")
            .fg(GREEN)
            .a(version)
            .fg(WHITE));
    logger.info("Starting BigLoupe Metrics server version " + version);

    try {
      commandLineParser(args);
      applyCommonOption();

      Server server = startWebServer(version);

      keepAliveLatch = new CountDownLatch(1);
      // keep this thread alive (non daemon thread) until we shutdown
      Runtime.getRuntime()
          .addShutdownHook(
              new Thread() {
                @Override
                public void run() {
                  keepAliveLatch.countDown();
                }
              });

      keepAliveThread =
          new Thread(
              new Runnable() {
                @Override
                public void run() {
                  try {
                    keepAliveLatch.await();
                  } catch (InterruptedException e) {
                    // bail out
                  }
                }
              },
              "BigLoupe metrics-server[keepAlive/" + version + "]");
      keepAliveThread.setDaemon(false);
      keepAliveThread.start();

      Runtime.getRuntime().addShutdownHook(new Thread(new MetricsServerCleaner(server)));
    } catch (ParseException e) {
      System.out.println(e.getMessage());
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp("java -jar bigloupe-chart.jar [options]", options);
      System.exit(-1);
    } catch (Exception e) {
      throw new IllegalArgumentException(e);
    }
  }
Example #22
0
  public static void main(String[] args) {
    int counter = 10000;
    Product product = null;

    Options options = new Options();
    options.addOption("p", "product", true, "Class name of the product to use for benchmark");
    options.addOption("n", true, "Number of repetitions");

    Parser parser = new PosixParser();
    try {
      CommandLine commandLine = parser.parse(options, args);
      if (commandLine.hasOption('p')) {
        product = (Product) Class.forName(commandLine.getOptionValue('p')).newInstance();
      }
      if (commandLine.hasOption('n')) {
        counter = Integer.parseInt(commandLine.getOptionValue('n'));
      }
    } catch (ParseException e) {
      e.printStackTrace();
    } catch (InstantiationException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    Harness harness = new Harness();
    // harness.addMetric(new SerializationSpeedMetric(1) {
    // public String toString() {
    // return "Initial run serialization";
    // }
    // });
    // harness.addMetric(new DeserializationSpeedMetric(1, false) {
    // public String toString() {
    // return "Initial run deserialization";
    // }
    // });
    harness.addMetric(new SerializationSpeedMetric(counter));
    harness.addMetric(new DeserializationSpeedMetric(counter, false));
    if (product == null) {
      harness.addProduct(new NoCache());
      harness.addProduct(new Cache122());
      harness.addProduct(new RealClassCache());
      harness.addProduct(new SerializedClassCache());
      harness.addProduct(new AliasedAttributeCache());
      harness.addProduct(new DefaultImplementationCache());
      harness.addProduct(new NoCache());
    } else {
      harness.addProduct(product);
    }
    harness.addTarget(new BasicTarget());
    harness.addTarget(new ExtendedTarget());
    harness.addTarget(new ReflectionTarget());
    harness.addTarget(new SerializableTarget());
    harness.run(new TextReporter(new PrintWriter(System.out, true)));
    System.out.println("Done.");
  }
Example #23
0
  @SuppressWarnings("static-access")
  public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(
        OptionBuilder.withArgName("name")
            .hasArg()
            .withDescription("name of the archive")
            .create(NAME_OPTION));
    options.addOption(
        OptionBuilder.withArgName("path")
            .hasArg()
            .withDescription("WARC files location")
            .create(DIR_OPTION));
    options.addOption(
        OptionBuilder.withArgName("n")
            .hasArg()
            .withDescription("Start from the n-th WARC file")
            .create(START_OPTION));

    options.addOption("create", false, "create new table");
    options.addOption("append", false, "append to existing table");

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
      cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
      System.err.println("Error parsing command line: " + exp.getMessage());
      System.exit(-1);
    }

    if (!cmdline.hasOption(DIR_OPTION) || !cmdline.hasOption(NAME_OPTION)) {
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp(IngestFiles.class.getCanonicalName(), options);
      System.exit(-1);
    }

    if (!cmdline.hasOption(CREATE_OPTION) && !cmdline.hasOption(APPEND_OPTION)) {
      System.err.println(
          String.format("Must specify either -%s or -%s", CREATE_OPTION, APPEND_OPTION));
      HelpFormatter formatter = new HelpFormatter();
      formatter.printHelp(IngestFiles.class.getCanonicalName(), options);
      System.exit(-1);
    }

    String path = cmdline.getOptionValue(DIR_OPTION);
    File inputFolder = new File(path);

    int i = 0;
    if (cmdline.hasOption(START_OPTION)) {
      i = Integer.parseInt(cmdline.getOptionValue(START_OPTION));
    }

    String name = cmdline.getOptionValue(NAME_OPTION);
    boolean create = cmdline.hasOption(CREATE_OPTION);
    IngestFiles load = new IngestFiles(name, create);
    load.ingestFolder(inputFolder, i);
  }
Example #24
0
  public static void main(String[] args) {
    Scanner scanner = new Scanner();
    CommandLine cmds;
    try {
      cmds = scanner.getCommands(args);
    } catch (ParseException e) {
      System.out.println("Could not parse command line arguments. Error:\n" + e.getStackTrace());
      return;
    }
    String modPath = null;
    if ((modPath = cmds.getOptionValue("i")) == null) {
      System.out.println("Need to provide a path to the Minecraft mod .jar");
      return;
    }
    String libPath = null;
    if ((libPath = cmds.getOptionValue("l")) == null) {
      System.out.println("Need to provide a path to the Minecraft install directory");
      return;
    }
    File modFile = new File(modPath);
    if (!modFile.exists() || modFile.isDirectory()) {
      System.out.println("Could not find mod at provided path");
      return;
    }
    if (!checkHasExtension(modFile, ".jar")) {
      System.out.println("File does not have .jar extension");
      return;
    }
    // /home/michael/.minecraft/mods/test-1.0.jar
    List<String> classNames = scanner.getClassNames(modFile);
    System.out.println("Class names:");
    for (String name : classNames) {
      System.out.println(name);
    }
    System.out.println("Executing methods with no arguments");
    for (String name : classNames) {
      System.out.println(
          "Executing class: "
              + name
              + "\n------------------------------------------------------------------------------------");
      scanner.executeClassMethods(modFile, name, libPath);
    }

    boolean timeout;
    try {
      timeout = scanner.executor.awaitTermination(10, TimeUnit.SECONDS);
      if (timeout) {
        System.out.println("Executor did no timeout");
      } else {
        System.out.println("Executor did timeout");
      }
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    System.exit(0);
  }
Example #25
0
 public static void parse(String[] args) {
   final MovsimCommandLine commandLine = new MovsimCommandLine();
   try {
     commandLine.createAndParse(args);
   } catch (ParseException e) {
     System.err.println("Parsing failed.  Reason: " + e.getMessage());
     commandLine.optionHelp();
   }
 }
Example #26
0
  // TODO add exception for invalid options
  private void loadCLO(String[] args) {
    Options options = new Options();

    String[][] clolist = {
      // {"variable/optionname", "description"},
      {"genConfig", "general configuration file location"},
      {"inWeightsLoc", "input weights configuration file location"},
      {"inDBLoc", "input database file location"},
      {"outWeightsLoc", "output weights configuration file location"},
      {"outDBLoc", "output database file location"},
      {"p3pLocation", "adding to DB: single policy file location"},
      {"p3pDirLocation", "adding to DB: multiple policy directory location"},
      {"newDB", "create new database in place of old one (doesn't check for existence of old one"},
      {"newPolicyLoc", "the policy object to process"},
      {"userResponse", "response to specified policy"},
      {"userIO", "user interface"},
      {"userInit", "initialization via user interface"},
      {"policyDB", "PolicyDatabase backend"},
      {"cbrV", "CBR to use"},
      {"blanketAccept", "automatically accept the user suggestion"},
      {"loglevel", "level of things save to the log- see java logging details"},
      {"policyDB", "PolicyDatabase backend"},
      {"NetworkRType", "Network Resource type"},
      {"NetworkROptions", "Network Resource options"},
      {"confidenceLevel", "Confidence threshold for consulting a networked resource"},
      {"useNet", "use networking options"},
      {"loglocation", "where to save the log file"},
      {"loglevel", "the java logging level to use. See online documentation for enums."}
    };

    for (String[] i : clolist) {
      options.addOption(i[0], true, i[1]);
    }

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
      cmd = parser.parse(options, args);
    } catch (ParseException e) {
      System.err.println("Error parsing commandline arguments.");
      e.printStackTrace();
      System.exit(3);
    }
    /*
    for(String i : args)
    {
    	System.err.println(i);
    }
    */
    for (String[] i : clolist) {
      if (cmd.hasOption(i[0])) {
        System.err.println("found option i: " + i);
        genProps.setProperty(i[0], cmd.getOptionValue(i[0]));
      }
    }
    System.err.println(genProps);
  }
 public void parse() {
   CommandLineParser parser = new DefaultParser();
   try {
     line = parser.parse(options, args);
   } catch (ParseException exp) {
     System.err.println("Parsing failed.  Reason: " + exp.getMessage());
     System.exit(1);
   }
 }
Example #28
0
 public boolean processOptions(String[] args) {
   CommandLineParser parser = new PosixParser();
   try {
     cli = parser.parse(options, args);
   } catch (ParseException e) {
     Log.error(this, "Command line parse failure: " + e.getMessage());
     return false;
   }
   return !hasUnrecognized();
 }
 /** @param args */
 public static void main(String[] args) {
   Options options = buildOptions();
   try {
     CommandLine line = new BasicParser().parse(options, args);
     processCommandLine(line, options);
   } catch (ParseException exp) {
     System.err.println(exp.getMessage());
     printHelp(options);
   }
 }
  /**
   * Main entry point for ToolRunner (see ToolRunner docs)
   *
   * @param argv The parameters passed to this program.
   * @return 0 on success, non zero on error.
   */
  @Override
  public int run(String[] argv) throws Exception {
    int exitCode = 0;

    Options options = buildOptions();
    if (argv.length == 0) {
      printHelp();
      return -1;
    }

    CommandLineParser parser = new PosixParser();
    CommandLine cmd;

    try {
      cmd = parser.parse(options, argv);
    } catch (ParseException e) {
      System.out.println("Error parsing command-line options: " + e.getMessage());
      printHelp();
      return -1;
    }

    if (cmd.hasOption("h")) { // print help and exit
      printHelp();
      return -1;
    }

    boolean printToScreen = false;
    String inputFilenameArg = cmd.getOptionValue("i");
    String outputFilenameArg = cmd.getOptionValue("o");
    String processor = cmd.getOptionValue("p");
    if (processor == null) {
      processor = defaultProcessor;
    }

    if (cmd.hasOption("v")) { // print output to screen too
      printToScreen = true;
      System.out.println("input  [" + inputFilenameArg + "]");
      System.out.println("output [" + outputFilenameArg + "]");
    }

    try {
      go(
          EditsVisitorFactory.getEditsVisitor(
              outputFilenameArg,
              processor,
              TokenizerFactory.getTokenizer(inputFilenameArg),
              printToScreen));
    } catch (EOFException e) {
      System.err.println("Input file ended unexpectedly. Exiting");
    } catch (IOException e) {
      System.err.println("Encountered exception. Exiting: " + e.getMessage());
    }

    return exitCode;
  }