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

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

Introduction

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

Prototype

Options

Source Link

Usage

From source file:com.floreantpos.main.Main.java

/**
 * @param args//from   w ww.  jav a2  s.co  m
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(DEVELOPMENT_MODE, true, "State if this is developmentMode"); //$NON-NLS-1$
    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);
    String optionValue = commandLine.getOptionValue(DEVELOPMENT_MODE);
    Locale defaultLocale = TerminalConfig.getDefaultLocale();
    if (defaultLocale != null) {
        Locale.setDefault(defaultLocale);
    }

    Application application = Application.getInstance();

    if (optionValue != null) {
        application.setDevelopmentMode(Boolean.valueOf(optionValue));
    }

    application.start();
}

From source file:com.discursive.jccook.cmdline.SomeApp.java

public static void main(String[] args) throws Exception {

    // Create a Parser
    CommandLineParser parser = new BasicParser();
    Options options = new Options();
    options.addOption("h", "help", false, "Print this usage information");
    options.addOption("v", "verbose", false, "Print out VERBOSE information");

    OptionGroup optionGroup = new OptionGroup();
    optionGroup.addOption(OptionBuilder.hasArg(true).withArgName("file").withLongOpt("file").create('f'));
    optionGroup.addOption(OptionBuilder.hasArg(true).withArgName("email").withLongOpt("email").create('m'));
    options.addOptionGroup(optionGroup);

    // Parse the program arguments
    try {/*  w w w . java  2s . co  m*/
        CommandLine commandLine = parser.parse(options, args);

        if (commandLine.hasOption('h')) {
            printUsage(options);
            System.exit(0);
        }

        // ... do important stuff ...
    } catch (Exception e) {
        System.out.println("You provided bad program arguments!");
        printUsage(options);
        System.exit(1);
    }
}

From source file:com.adobe.aem.demomachine.Base64Encoder.java

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

    String value = null;/*w w w .j a v a  2 s  .c o m*/

    // Command line options for this tool
    Options options = new Options();
    options.addOption("v", true, "Value");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("v")) {
            value = cmd.getOptionValue("v");
        }

        if (value == null) {
            System.out.println("Command line parameters: -v value");
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    byte[] encodedBytes = Base64.encodeBase64(value.getBytes());
    System.out.println(new String(encodedBytes));

}

From source file:de.jackwhite20.japs.server.Main.java

public static void main(String[] args) throws Exception {

    Config config = null;/* w w w.  ja va2 s. com*/

    if (args.length > 0) {
        Options options = new Options();
        options.addOption("h", true, "Address to bind to");
        options.addOption("p", true, "Port to bind to");
        options.addOption("b", true, "The backlog");
        options.addOption("t", true, "Worker thread count");
        options.addOption("d", false, "If debug is enabled or not");
        options.addOption("c", true, "Add server as a cluster");
        options.addOption("ci", true, "Sets the cache check interval");
        options.addOption("si", true, "Sets the snapshot interval");

        CommandLineParser commandLineParser = new BasicParser();
        CommandLine commandLine = commandLineParser.parse(options, args);

        if (commandLine.hasOption("h") && commandLine.hasOption("p") && commandLine.hasOption("b")
                && commandLine.hasOption("t")) {

            List<ClusterServer> clusterServers = new ArrayList<>();

            if (commandLine.hasOption("c")) {
                for (String c : commandLine.getOptionValues("c")) {
                    String[] splitted = c.split(":");
                    clusterServers.add(new ClusterServer(splitted[0], Integer.parseInt(splitted[1])));
                }
            }

            config = new Config(commandLine.getOptionValue("h"),
                    Integer.parseInt(commandLine.getOptionValue("p")),
                    Integer.parseInt(commandLine.getOptionValue("b")), commandLine.hasOption("d"),
                    Integer.parseInt(commandLine.getOptionValue("t")), clusterServers,
                    (commandLine.hasOption("ci")) ? Integer.parseInt(commandLine.getOptionValue("ci")) : 300,
                    (commandLine.hasOption("si")) ? Integer.parseInt(commandLine.getOptionValue("si")) : -1);
        } else {
            System.out.println(
                    "Usage: java -jar japs-server.jar -h <Host> -p <Port> -b <Backlog> -t <Threads> [-c IP:Port IP:Port] [-d]");
            System.out.println(
                    "Example (with debugging enabled): java -jar japs-server.jar -h localhost -p 1337 -b 100 -t 4 -d");
            System.out.println(
                    "Example (with debugging enabled and cluster setup): java -jar japs-server.jar -h localhost -p 1337 -b 100 -t 4 -c localhost:1338 -d");
            System.exit(-1);
        }
    } else {
        File configFile = new File("config.json");
        if (!configFile.exists()) {
            try {
                Files.copy(JaPS.class.getClassLoader().getResourceAsStream("config.json"), configFile.toPath(),
                        StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                System.err.println("Unable to load default config!");
                System.exit(-1);
            }
        }

        try {
            config = new Gson().fromJson(
                    Files.lines(configFile.toPath()).map(String::toString).collect(Collectors.joining(" ")),
                    Config.class);
        } catch (IOException e) {
            System.err.println("Unable to load 'config.json' in current directory!");
            System.exit(-1);
        }
    }

    if (config == null) {
        System.err.println("Failed to create a Config!");
        System.err.println("Please check the program parameters or the 'config.json' file!");
    } else {
        System.err.println("Using Config: " + config);

        JaPS jaPS = new JaPS(config);
        jaPS.init();
        jaPS.start();
        jaPS.stop();
    }
}

From source file:it.crs4.features.ImageToAvro.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    CommandLine cmd = null;//from   ww w . j av a 2  s. co  m
    try {
        cmd = parseCmdLine(opts, args);
    } catch (ParseException e) {
        System.err.println("ERROR: " + e.getMessage());
        System.exit(1);
    }
    String fn = null;
    try {
        fn = cmd.getArgs()[0];
    } catch (ArrayIndexOutOfBoundsException e) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("java ImageToAvro IMG_FILE", opts);
        System.exit(2);
    }
    String outDirName = null;
    if (cmd.hasOption("outdir")) {
        outDirName = cmd.getOptionValue("outdir");
        File outDir = new File(outDirName);
        if (!outDir.exists()) {
            boolean ret = outDir.mkdirs();
            if (!ret) {
                System.err.format("ERROR: can't create %s\n", outDirName);
                System.exit(3);
            }
        }
    }

    String name = PathTools.stripext(PathTools.basename(fn));
    ImageReader reader = new ImageReader();
    reader.setId(fn);
    LOGGER.info("Reading from {}", fn);
    BioImgFactory factory = new BioImgFactory(reader);
    int seriesCount = factory.getSeriesCount();

    // FIXME: add support for XY slicing
    String seriesName;
    String outFn;
    for (int i = 0; i < seriesCount; i++) {
        seriesName = String.format("%s_%d", name, i);
        outFn = new File(outDirName, seriesName + ".avro").getPath();
        factory.setSeries(i);
        factory.writeSeries(seriesName, outFn);
        LOGGER.info("Writing to {}", outFn);
    }
    reader.close();
    LOGGER.info("All done");
}

From source file:com.hurence.logisland.runner.StreamProcessingRunner.java

/**
 * main entry point/*from  www. ja va  2  s. c  o m*/
 *
 * @param args
 */
public static void main(String[] args) {

    logger.info("starting StreamProcessingRunner");

    //////////////////////////////////////////
    // Commande lien management
    Parser parser = new GnuParser();
    Options options = new Options();

    String helpMsg = "Print this message.";
    Option help = new Option("help", helpMsg);
    options.addOption(help);

    OptionBuilder.withArgName("conf");
    OptionBuilder.withLongOpt("config-file");
    OptionBuilder.isRequired();
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("config file path");
    Option conf = OptionBuilder.create("conf");
    options.addOption(conf);

    Optional<EngineContext> engineInstance = Optional.empty();
    try {
        System.out.println(BannerLoader.loadBanner());

        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String configFile = line.getOptionValue("conf");

        // load the YAML config
        LogislandConfiguration sessionConf = ConfigReader.loadConfig(configFile);

        // instantiate engine and all the processor from the config
        engineInstance = ComponentFactory.getEngineContext(sessionConf.getEngine());
        if (!engineInstance.isPresent()) {
            throw new IllegalArgumentException("engineInstance could not be instantiated");
        }
        if (!engineInstance.get().isValid()) {
            throw new IllegalArgumentException("engineInstance is not valid with input configuration !");
        }
        logger.info("starting Logisland session version {}", sessionConf.getVersion());
        logger.info(sessionConf.getDocumentation());
    } catch (Exception e) {
        logger.error("unable to launch runner", e);
        System.exit(-1);
    }
    String engineName = engineInstance.get().getEngine().getIdentifier();
    try {
        // start the engine
        EngineContext engineContext = engineInstance.get();
        logger.info("start engine {}", engineName);
        engineInstance.get().getEngine().start(engineContext);
        logger.info("awaitTermination for engine {}", engineName);
        engineContext.getEngine().awaitTermination(engineContext);
        System.exit(0);
    } catch (Exception e) {
        logger.error("something went bad while running the job {} : {}", engineName, e);
        System.exit(-1);
    }

}

From source file:com.cohesionforce.AvroToParquet.java

public static void main(String[] args) {

    String inputFile = null;/* ww  w .j a  v a2 s .  com*/
    String outputFile = null;

    HelpFormatter formatter = new HelpFormatter();
    // create Options object
    Options options = new Options();

    // add t option
    options.addOption("i", true, "input avro file");
    options.addOption("o", true, "ouptut Parquet file");
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
        inputFile = cmd.getOptionValue("i");
        if (inputFile == null) {
            formatter.printHelp("AvroToParquet", options);
            return;
        }
        outputFile = cmd.getOptionValue("o");
    } catch (ParseException exc) {
        System.err.println("Problem with command line parameters: " + exc.getMessage());
        return;
    }

    File avroFile = new File(inputFile);

    if (!avroFile.exists()) {
        System.err.println("Could not open file: " + inputFile);
        return;
    }
    try {

        DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>();
        DataFileReader<GenericRecord> dataFileReader;
        dataFileReader = new DataFileReader<GenericRecord>(avroFile, datumReader);
        Schema avroSchema = dataFileReader.getSchema();

        // choose compression scheme
        CompressionCodecName compressionCodecName = CompressionCodecName.SNAPPY;

        // set Parquet file block size and page size values
        int blockSize = 256 * 1024 * 1024;
        int pageSize = 64 * 1024;

        String base = FilenameUtils.removeExtension(avroFile.getAbsolutePath()) + ".parquet";
        if (outputFile != null) {
            File file = new File(outputFile);
            base = file.getAbsolutePath();
        }

        Path outputPath = new Path("file:///" + base);

        // the ParquetWriter object that will consume Avro GenericRecords
        ParquetWriter<GenericRecord> parquetWriter;
        parquetWriter = new AvroParquetWriter<GenericRecord>(outputPath, avroSchema, compressionCodecName,
                blockSize, pageSize);
        for (GenericRecord record : dataFileReader) {
            parquetWriter.write(record);
        }
        dataFileReader.close();
        parquetWriter.close();
    } catch (IOException e) {
        System.err.println("Caught exception: " + e.getMessage());
    }
}

From source file:edu.usc.pgroup.floe.client.commands.KillApp.java

/**
 * Entry point for Scale command.//from w ww  .ja  v  a2 s  .c  om
 * @param args command line arguments sent by the floe.py script.
 */
public static void main(final String[] args) {

    Options options = new Options();

    Option appOption = OptionBuilder.withArgName("name").hasArg().isRequired()
            .withDescription("Application Name").create("app");

    options.addOption(appOption);

    CommandLineParser parser = new BasicParser();
    CommandLine line;

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

    } catch (ParseException e) {
        LOGGER.error("Invalid command: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("scale options", options);
        return;
    }

    String app = line.getOptionValue("app");

    LOGGER.info("Application: {}", app);

    try {
        FloeClient.getInstance().killApp(app);
    } catch (TException e) {
        LOGGER.error("Error while connecting to the coordinator: {}", e);
    }
}

From source file:com.subakva.formicid.Main.java

public static void main(final String[] args) {
    Options options = new Options();
    options.addOption("p", "projecthelp", false, "print project help information");
    options.addOption("f", "file", true, "use given buildfile");
    options.addOption("h", "help", false, "print this message");
    options.addOption("d", "debug", false, "print debugging information");
    options.addOption("v", "verbose", false, "be extra verbose");
    options.addOption("q", "quiet", false, "be extra quiet");

    CommandLine cli;/*from   ww w . ja v a 2  s  . c o  m*/
    try {
        cli = new GnuParser().parse(options, args);
    } catch (ParseException e) {
        System.out.println("Error: " + e.getMessage());
        new HelpFormatter().printHelp(CLI_SYNTAX, options);
        return;
    }

    String scriptName = cli.getOptionValue("f", "build.js");
    if (cli.hasOption("h")) {
        new HelpFormatter().printHelp(CLI_SYNTAX, options);
        return;
    } else if (cli.hasOption("p")) {
        runScript(scriptName, "projecthelp", null);
    } else {
        runScript(scriptName, "build", cli);
    }
}

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

/**
 * Apliacion principal o main de la librera.
 * @param args the command line arguments
 */// ww w  .j  av a  2s.  co m
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());
    }

}