Example usage for org.apache.commons.cli DefaultParser DefaultParser

List of usage examples for org.apache.commons.cli DefaultParser DefaultParser

Introduction

In this page you can find the example usage for org.apache.commons.cli DefaultParser DefaultParser.

Prototype

DefaultParser

Source Link

Usage

From source file:com.nextdoor.bender.ValidateSchema.java

public static void main(String[] args) throws ParseException, InterruptedException, IOException {

    /*//  w w  w  .  ja v a  2  s.co  m
     * Parse cli arguments
     */
    Options options = new Options();
    options.addOption(Option.builder().longOpt("schema").hasArg()
            .desc("Filename to output schema to. Default: schema.json").build());
    options.addOption(Option.builder().longOpt("configs").hasArgs()
            .desc("List of config files to validate against schema.").build());
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    String schemaFilename = cmd.getOptionValue("schema", "schema.json");
    String[] configFilenames = cmd.getOptionValues("configs");

    /*
     * Validate config files against schema
     */
    boolean hasFailures = false;
    for (String configFilename : configFilenames) {
        StringBuilder sb = new StringBuilder();
        Files.lines(Paths.get(configFilename), StandardCharsets.UTF_8).forEach(p -> sb.append(p + "\n"));

        System.out.println("Attempting to validate " + configFilename);
        try {
            ObjectMapper mapper = BenderConfig.getObjectMapper(configFilename);
            mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
            BenderConfig.load(configFilename, sb.toString(), mapper, true);
            System.out.println("Valid");
            BenderConfig config = BenderConfig.load(configFilename, sb.toString());
        } catch (ConfigurationException e) {
            System.out.println("Invalid");
            e.printStackTrace();
            hasFailures = true;
        }
    }

    if (hasFailures) {
        System.exit(1);
    }
}

From source file:com.threew.validacion.tarjetas.credito.App.java

/**
 * Apliacion principal o main de la librera.
 * @param args the command line arguments
 *///  w ww. ja  va2s  . c om
public static void main(String[] args) {
    /// Preguntar por los argumentos

    // Probar con nmeros de tarjeta 
    Options opciones = new Options();
    /// Agregar opciones
    opciones.addOption("n", true, "el nmero de tarjeta a validar");
    opciones.addOption("c", "el cdigo CVV/CVV2 de la tarjeta a validar");

    /// Analizar la linea de comandos
    CommandLineParser parser = new DefaultParser();

    try {
        /// Linea de comandos
        CommandLine cmd = parser.parse(opciones, args);

        /// Preguntar si a linea de comandos se usa
        if (cmd.hasOption("n") == true) {
            String numero = cmd.getOptionValue("n");
            /// Validar
            validar(numero);

        } else {
            validar(args[1]);
        }

    } catch (ParseException ex) {
        Log.error(ex.toString());
    }

}

From source file:com.shieldsbetter.sbomg.Cli.java

public static void main(String[] args) {
    int result;/*from   w ww  .j a  v a  2  s .  c om*/

    try {
        Options options = new Options();
        options.addOption("f", false, "Force overwrite of files that already exist.");
        options.addOption("q", false, "Quiet all non-error output.");

        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(options, args);

        try {
            Plan p = makePlan(cmd);

            for (File input : p.files()) {
                if (!cmd.hasOption('q')) {
                    System.out.println("Processing " + input.getPath() + "...");
                }

                String modelName = nameWithoutExtension(input);
                File targetPath = p.getDestinationPath(input);
                try (Scanner inputScan = fileToScanner("input", input);
                        Writer outputWriter = outputPathToWriter(targetPath, modelName, cmd);) {
                    Object modelDesc = parseSbomgV1(inputScan);

                    try {
                        ViewModelGenerator.generate(p.getPackage(input), modelName, modelDesc, outputWriter);
                    } catch (IOException ioe) {
                        throw new FileException(buildOutputFile(targetPath, modelName), "writing to target",
                                ioe.getMessage());
                    }
                } catch (IOException ioe) {
                    throw new FileException(buildOutputFile(targetPath, modelName), "opening target",
                            ioe.getMessage());
                }
            }

            result = 0;
        } catch (OperationException oe) {
            System.err.println();
            System.err.println(oe.getMessage());
            result = 1;
        }
    } catch (FileException fe) {
        System.err.println();
        System.err.println("Error " + fe.getTask() + " file " + fe.getFile().getPath() + ":");
        System.err.println("    " + fe.getMessage());

        result = 1;
    } catch (ParseException pe) {
        throw new RuntimeException(pe);
    }

    System.exit(result);
}

From source file:com.twitter.bazel.checkstyle.JavaCheckstyle.java

public static void main(String[] args) throws IOException {
    CommandLineParser parser = new DefaultParser();

    // create the Options
    Options options = new Options();
    options.addOption(Option.builder("f").required(true).hasArg().longOpt("extra_action_file")
            .desc("bazel extra action protobuf file").build());
    options.addOption(Option.builder("c").required(true).hasArg().longOpt("checkstyle_config_file")
            .desc("checkstyle config file").build());

    try {/*from w  ww .  ja  v  a  2s .  com*/
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        String extraActionFile = line.getOptionValue("f");
        String configFile = line.getOptionValue("c");

        String[] sourceFiles = getSourceFiles(extraActionFile);
        if (sourceFiles.length == 0) {
            LOG.fine("No java files found by checkstyle");
            return;
        }

        LOG.fine(sourceFiles.length + " java files found by checkstyle");

        String[] checkstyleArgs = (String[]) ArrayUtils.addAll(new String[] { "-c", configFile }, sourceFiles);

        LOG.fine("checkstyle args: " + Joiner.on(" ").join(checkstyleArgs));
        com.puppycrawl.tools.checkstyle.Main.main(checkstyleArgs);
    } catch (ParseException exp) {
        LOG.severe(String.format("Invalid input to %s: %s", CLASSNAME, exp.getMessage()));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java " + CLASSNAME, options);
    }
}

From source file:Pong.java

public static void main(String... args) throws Exception {
    System.setProperty("os.max.pid.bits", "16");

    Options options = new Options();
    options.addOption("i", true, "Input chronicle path");
    options.addOption("n", true, "Number of entries to write");
    options.addOption("w", true, "Number of writer threads");
    options.addOption("r", true, "Number of reader threads");
    options.addOption("x", false, "Delete the output chronicle at startup");

    CommandLine cmd = new DefaultParser().parse(options, args);
    final Path output = Paths.get(cmd.getOptionValue("o", "/tmp/__test/chr"));
    final long maxCount = Long.parseLong(cmd.getOptionValue("n", "10000000"));
    final int writerThreadCount = Integer.parseInt(cmd.getOptionValue("w", "4"));
    final int readerThreadCount = Integer.parseInt(cmd.getOptionValue("r", "4"));
    final boolean deleteOnStartup = cmd.hasOption("x");

    if (deleteOnStartup) {
        FileUtil.removeRecursive(output);
    }//from   w ww .  j  a va  2 s.  c  o m

    final Chronicle chr = ChronicleQueueBuilder.vanilla(output.toFile()).build();

    final ExecutorService executor = Executors.newFixedThreadPool(4);
    final List<Future<?>> futures = new ArrayList<>();

    final long totalCount = writerThreadCount * maxCount;
    final long t0 = System.nanoTime();

    for (int i = 0; i != readerThreadCount; ++i) {
        final int tid = i;
        futures.add(executor.submit((Runnable) () -> {
            try {
                IntLongMap counts = HashIntLongMaps.newMutableMap();
                ExcerptTailer tailer = chr.createTailer();

                final StringBuilder sb1 = new StringBuilder();
                final StringBuilder sb2 = new StringBuilder();

                long count = 0;
                while (count != totalCount) {
                    if (!tailer.nextIndex())
                        continue;
                    final int id = tailer.readInt();
                    final long val = tailer.readStopBit();
                    final long longValue = tailer.readLong();
                    sb1.setLength(0);
                    sb2.setLength(0);
                    tailer.read8bitText(sb1);
                    tailer.read8bitText(sb2);
                    if (counts.addValue(id, 1) - 1 != val || longValue != 0x0badcafedeadbeefL
                            || !StringInterner.isEqual("FooBar", sb1)
                            || !StringInterner.isEqual("AnotherFooBar", sb2)) {
                        System.out.println("Unexpected value " + id + ", " + val + ", "
                                + Long.toHexString(longValue) + ", " + sb1.toString() + ", " + sb2.toString());
                        return;
                    }
                    ++count;
                    if (count % 1_000_000 == 0) {
                        long t1 = System.nanoTime();
                        System.out.println(tid + " " + (t1 - t0) / 1e6 + " ms");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }));
    }
    for (Future f : futures) {
        f.get();
    }
    executor.shutdownNow();

    final long t1 = System.nanoTime();
    System.out.println("Done. Rough time=" + (t1 - t0) / 1e6 + " ms");
}

From source file:br.usp.poli.lta.cereda.wsn2spa.Main.java

public static void main(String[] args) {

    Utils.printBanner();//  w ww .  j  a  v  a  2 s. co  m
    CommandLineParser parser = new DefaultParser();

    try {

        CommandLine line = parser.parse(Utils.getOptions(), args);

        if (line.hasOption("g")) {
            System.out.println("Flag '-g' found, overriding other flags.");
            System.out.println("Please, wait...");
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception nothandled) {
            }
            SwingUtilities.invokeLater(() -> {
                Editor e = new Editor();
                e.setVisible(true);
            });
        } else {
            enableCLI(line);
        }
    } catch (ParseException nothandled) {
        Utils.printHelp();
    } catch (Exception exception) {
        Utils.printException(exception);
    }
}

From source file:cloudnet.examples.evaluations.ConfigurableEvaluation.java

/**
 * @param args the command line arguments
 *///from   www  .ja  va 2  s.  co  m
public static void main(String[] args) {
    Options options = makeOptions();
    CommandLineParser parser = new DefaultParser();
    try {

        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("vmPlacementSimApp", options);
            return;
        }

        // apply options
        applyOptions(cmd);

        // run simulation
        runSimulation();

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

    // exit in order to stop R-Environment if it is used.
    System.exit(0);
}

From source file:keepassj.cli.KeepassjCli.java

/**
 * @param args the command line arguments
 * @throws org.apache.commons.cli.ParseException
 * @throws java.io.IOException/*from w  w w  .ja  v a  2 s  .  com*/
 */
public static void main(String[] args) throws ParseException, IOException {
    Options options = KeepassjCli.getOptions();
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);
    if (!KeepassjCli.validateOptions(cmd)) {
        HelpFormatter help = new HelpFormatter();
        help.printHelp("Usage: java -jar KeepassjCli -f dbfile [options]", options);
    } else {
        String password;
        if (cmd.hasOption('p')) {
            password = cmd.getOptionValue('p');
        } else {
            Console console = System.console();
            char[] hiddenString = console.readPassword("Enter password for %s\n", cmd.getOptionValue('f'));
            password = String.valueOf(hiddenString);
        }
        KeepassjCli instance = new KeepassjCli(cmd.getOptionValue('f'), password, cmd.getOptionValue('k'));
        System.out.println("Description:" + instance.db.getDescription());
        PwGroup rootGroup = instance.db.getRootGroup();
        System.out.println(String.valueOf(rootGroup.GetEntriesCount(true)) + " entries");
        if (cmd.hasOption('l')) {
            instance.printEntries(rootGroup.GetEntries(true), false);
        } else if (cmd.hasOption('s')) {
            PwObjectList<PwEntry> results = instance.search(cmd.getOptionValue('s'));
            System.out.println("Found " + results.getUCount() + " results for:" + cmd.getOptionValue('s'));
            instance.printEntries(results, false);
        } else if (cmd.hasOption('i')) {
            System.out.println("Entering interactive mode.");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            String input = null;
            PwObjectList<PwEntry> results = null;
            while (!"\\q".equals(input)) {
                if (results != null) {
                    System.out.println("Would you like to view a specific entry? y/n");
                    input = bufferedReader.readLine();
                    if ("y".equalsIgnoreCase(input)) {
                        System.out.print("Enter the title number:");
                        input = bufferedReader.readLine();
                        instance.printCompleteEntry(results.GetAt(Integer.parseInt(input) - 1)); // Since humans start counting at 1
                    }
                    results = null;
                    System.out.println();
                } else {
                    System.out.print("Enter something to search for (or \\q to quit):");
                    input = bufferedReader.readLine();
                    if (!"\\q".equalsIgnoreCase(input)) {
                        results = instance.search(input);
                        instance.printEntries(results, true);
                    }
                }
            }
        }

        // Close before exit
        instance.db.Close();
    }
}

From source file:com.google.cloud.errorreporting.v1beta1.ReportErrorsServiceSmokeTest.java

public static void main(String args[]) {
    Logger.getLogger("").setLevel(Level.WARNING);
    try {/* ww  w. j  a  v  a  2s  . c  o  m*/
        Options options = new Options();
        options.addOption("h", "help", false, "show usage");
        options.addOption(Option.builder().longOpt("project_id").desc("Project id").hasArg()
                .argName("PROJECT-ID").required(true).build());
        CommandLine cl = (new DefaultParser()).parse(options, args);
        if (cl.hasOption("help")) {
            HelpFormatter formater = new HelpFormatter();
            formater.printHelp("ReportErrorsServiceSmokeTest", options);
        }
        executeNoCatch(cl.getOptionValue("project_id"));
        System.out.println("OK");
    } catch (Exception e) {
        System.err.println("Failed with exception:");
        e.printStackTrace(System.err);
        System.exit(1);
    }
}

From source file:main.Main.java

/**
 * The public main function.//  w ww .j  a v  a 2 s .c  o m
 * @param args
 */
public static void main(String[] args) {
    System.out.println("Starting");

    Options options = new Options();

    Option solutionOption = new Option("s", "solution", true,
            "This will be the " + "solution of the cross word game. (aka. This will be the first"
                    + " vertical word on the canvas.)");

    //        solutionOption.setRequired(true);

    Option numOfBatchOption = new Option("n", "numOfBatch", true, "");

    Option verboseOption = new Option("v", "verbose", false, "Print some debug information during running.");
    Option veryVerboseOption = new Option("vv", "very-verbose", false, "Print more debug information.");

    options.addOption(solutionOption);
    options.addOption(numOfBatchOption);
    options.addOption(verboseOption);
    options.addOption(veryVerboseOption);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp("utility-name", options);

        System.exit(1);
        return;
    }

    System.out.println(cmd.getArgList());

    int debugLevel = 0;
    if (cmd.hasOption("verbose")) {
        debugLevel = 1;
    }
    if (cmd.hasOption("very-verbose")) {
        debugLevel = 2;
    }
    String solution = cmd.getOptionValue("solution");
    if (null == solution) {
        startGui();
    } else {
        int numOfBatch = Integer.valueOf(cmd.getOptionValue("numOfBatch", "200"));
        System.out.println(solution);
        Generator gen = new Generator(solution, debugLevel); // <---- EDIT THIS LINE FOR DIFFERENT SOLUTIONS.
        long startTime = System.currentTimeMillis();
        gen.generate(numOfBatch);
        long estimatedTime = System.currentTimeMillis() - startTime;
        System.out.print("estimatedTime: " + estimatedTime + "ms");
    }
}