Example usage for org.apache.commons.cli UnrecognizedOptionException getOption

List of usage examples for org.apache.commons.cli UnrecognizedOptionException getOption

Introduction

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

Prototype

public String getOption() 

Source Link

Document

Returns the unrecognized option.

Usage

From source file:name.martingeisse.ecotools.simulator.ui.Main.java

/**
 * The main method.//w ww.  j a  va2  s .  com
 * @param args command-line arguments
 * @throws Exception Any exceptions are passed to the environment.
 */
public static void main(String[] args) throws Exception {

    /** define command-line options **/
    Options options = new Options();
    options.addOption("i", false, "interactive mode (do not start simulation automatically)");
    options.addOption("l", true, "load program");
    options.addOption("r", true, "load ROM contents");
    options.addOption("d", true, "enable disk simulation with the specified disk image file");
    options.addOption("t", true, "enable terminal simulation with the specified number of terminals (0..2)");
    options.addOption("g", false, "enable graphics controller simulation");
    options.addOption("c", false, "enable console simulation");
    options.addOption("C", false, "enable block console simulation");
    options.addOption("o", true, "enable output device simulation and write output to the specified file");
    options.addOption("s", false, "enable null sound device");

    /** print help for the empty command line **/
    if (args.length == 0) {
        showUsgeAndExit(options);
    }

    /** parse the command line **/
    CommandLineParser commandLineParser = new PosixParser();
    CommandLine commandLine;
    try {
        commandLine = commandLineParser.parse(options, args);
    } catch (UnrecognizedOptionException e) {
        System.out.println("unrecognized option: " + e.getOption());
        showUsgeAndExit(options);
        return;
    }

    /** build the simulator configuration **/
    SimulatorConfiguration configuration = new SimulatorConfiguration();

    /** load configuration files **/
    for (String arg : commandLine.getArgs()) {
        configuration.loadConfigurationFile(arg);
    }

    /** interpret the options **/

    if (commandLine.hasOption("l")) {
        configuration.setProgramFilename(commandLine.getOptionValue("l"));
    }

    if (commandLine.hasOption("r")) {
        configuration.setRomFilename(commandLine.getOptionValue("r"));
    }

    if (commandLine.hasOption("d")) {
        configuration.setDiskFilename(commandLine.getOptionValue("d"));
    }

    if (commandLine.hasOption("t")) {
        String terminalCountSpecification = commandLine.getOptionValue("t");
        try {
            configuration.setTerminalCount(
                    (terminalCountSpecification == null) ? 0 : Integer.parseInt(terminalCountSpecification));
        } catch (NumberFormatException e) {
            System.out.println("number format error in number of terminals: " + terminalCountSpecification);
        }
    }

    if (commandLine.hasOption("i")) {
        configuration.setInteractive(true);
    }

    if (commandLine.hasOption("g")) {
        configuration.setGraphics(true);
    }

    if (commandLine.hasOption("c")) {
        configuration.setConsole(true);
    }

    if (commandLine.hasOption("C")) {
        configuration.setBlockConsole(true);
    }

    if (commandLine.hasOption("o")) {
        configuration.setOutputFilename(commandLine.getOptionValue("o"));
    }

    if (commandLine.hasOption("s")) {
        configuration.setSound(true);
    }

    configuration.checkConsistency();
    configuration.deriveSettings();

    /** setup simulation framework and run **/
    EcoSimulatorFramework framework = new EcoSimulatorFramework();
    configuration.applyPreCreate(framework);
    framework.create();
    configuration.applyPostCreate(framework);
    framework.open();
    framework.mainLoop();
    framework.dispose();
    framework.exit();

}

From source file:ab.demo.MainEntry.java

public static void main(String args[]) {

    LoggingHandler.initConsoleLog();//www  . ja v  a  2s.  c  o  m

    //args = new String[]{"-su"};
    Options options = new Options();
    options.addOption("s", "standalone", false, "runs the reinforcement learning agent in standalone mode");
    options.addOption("p", "proxyPort", true, "the port which is to be used by the proxy");
    options.addOption("h", "help", false, "displays this help");
    options.addOption("n", "naiveAgent", false, "runs the naive agent in standalone mode");
    options.addOption("c", "competition", false, "runs the naive agent in the server/client competition mode");
    options.addOption("u", "updateDatabaseTables", false, "executes CREATE TABLE IF NOT EXIST commands");
    options.addOption("l", "level", true, "if set the agent is playing only in this one level");
    options.addOption("m", "manual", false,
            "runs the empirical threshold determination agent in standalone mode");
    options.addOption("r", "real", false, "shows the recognized shapes in a new frame");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;
    StandaloneAgent agent;

    Properties properties = new Properties();
    InputStream configInputStream = null;

    try {
        Class.forName("org.sqlite.JDBC");
        //parse configuration file
        configInputStream = new FileInputStream("config.properties");

        properties.load(configInputStream);

    } catch (IOException exception) {
        exception.printStackTrace();
    } catch (ClassNotFoundException exception) {
        exception.printStackTrace();
    } finally {
        if (configInputStream != null) {
            try {
                configInputStream.close();
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
    }

    String dbPath = properties.getProperty("db_path");
    String dbUser = properties.getProperty("db_user");
    String dbPass = properties.getProperty("db_pass");
    DBI dbi = new DBI(dbPath, dbUser, dbPass);

    QValuesDAO qValuesDAO = dbi.open(QValuesDAO.class);
    GamesDAO gamesDAO = dbi.open(GamesDAO.class);
    MovesDAO movesDAO = dbi.open(MovesDAO.class);
    ProblemStatesDAO problemStatesDAO = dbi.open(ProblemStatesDAO.class);

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("help", options);
            return;
        }

        int proxyPort = 9000;
        if (cmd.hasOption("proxyPort")) {
            proxyPort = Integer.parseInt(cmd.getOptionValue("proxyPort"));
            logger.info("Set proxy port to " + proxyPort);
        }
        Proxy.setPort(proxyPort);

        LoggingHandler.initFileLog();

        if (cmd.hasOption("standalone")) {
            agent = new ReinforcementLearningAgent(gamesDAO, movesDAO, problemStatesDAO, qValuesDAO);
        } else if (cmd.hasOption("naiveAgent")) {
            agent = new NaiveStandaloneAgent();
        } else if (cmd.hasOption("manual")) {
            agent = new ManualGamePlayAgent(gamesDAO, movesDAO, problemStatesDAO);
        } else if (cmd.hasOption("competition")) {
            System.out.println("We haven't implemented a competition ready agent yet.");
            return;
        } else {
            System.out.println("Please specify which solving strategy we should be using.");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("help", options);
            return;
        }

        if (cmd.hasOption("updateDatabaseTables")) {
            qValuesDAO.createTable();
            gamesDAO.createTable();
            movesDAO.createTable();
            problemStatesDAO.createTable();
            problemStatesDAO.createObjectsTable();
        }

        if (cmd.hasOption("level")) {
            agent.setFixedLevel(Integer.parseInt(cmd.getOptionValue("level")));
        }

        if (cmd.hasOption("real")) {
            ShowSeg.useRealshape = true;
            Thread thread = new Thread(new ShowSeg());
            thread.start();
        }

    } catch (UnrecognizedOptionException e) {
        System.out.println("Unrecognized commandline option: " + e.getOption());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("help", options);
        return;
    } catch (ParseException e) {
        System.out.println(
                "There was an error while parsing your command line input. Did you rechecked your syntax before running?");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("help", options);
        return;
    }

    agent.run();
}

From source file:general.Main.java

/**
 * Selects the files to be processed and specifies the files to write to.
 *
 * @param args Arguments to specify runtime behavior.
 *///  ww  w  .j a  v  a 2  s  .  co  m
public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException,
        InstantiationException, IllegalAccessException {
    Options options = new Options();
    options.addOption("l", "logging", false, "enables file logging");
    options.addOption("j", "jena", false, "uses the Jena SPARQL Parser");
    options.addOption("o", "openrdf", false, "uses the OpenRDF SPARQL Parser");
    options.addOption("f", "file", true, "defines the input file prefix");
    options.addOption("h", "help", false, "displays this help");
    options.addOption("t", "tsv", false, "reads from .tsv-files");
    // options.addOption("p", "parquet", false, "read from .parquet-files");
    options.addOption("n", "numberOfThreads", true, "number of used threads, default 1");
    options.addOption("b", "withBots", false, "enables metric calculation for bot queries+");
    options.addOption("p", "readPreprocessed", false, "enables reading of preprocessed files");

    //some parameters which can be changed through parameters
    //QueryHandler queryHandler = new OpenRDFQueryHandler();
    String inputFilePrefix;
    String inputFileSuffix = ".tsv";
    String queryParserName = "OpenRDF";
    Class inputHandlerClass = null;
    Class queryHandlerClass = null;
    int numberOfThreads = 1;

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("help", options);
            return;
        }
        if (cmd.hasOption("openrdf")) {
            queryHandlerClass = OpenRDFQueryHandler.class;
        }
        if (cmd.hasOption("tsv")) {
            inputFileSuffix = ".tsv";
            inputHandlerClass = InputHandlerTSV.class;
        }
        if (cmd.hasOption("parquet")) {
            inputFileSuffix = ".parquet";
            Logger.getLogger("org").setLevel(Level.WARN);
            Logger.getLogger("akka").setLevel(Level.WARN);
            SparkConf conf = new SparkConf().setAppName("SPARQLQueryAnalyzer").setMaster("local");
            JavaSparkContext sc = new JavaSparkContext(conf);
            inputHandlerClass = InputHandlerParquet.class;
        }
        if (inputHandlerClass == null) {
            System.out.println("Please specify which parser to use, either -t for TSV or -p for parquet.");
        }
        if (cmd.hasOption("file")) {
            inputFilePrefix = cmd.getOptionValue("file").trim();
        } else {
            System.out.println(
                    "Please specify at least the file which we should work on using the option '--file PREFIX' or 'f PREFIX'");
            return;
        }
        if (cmd.hasOption("logging")) {
            LoggingHandler.initFileLog(queryParserName, inputFilePrefix);
        }
        if (cmd.hasOption("numberOfThreads")) {
            numberOfThreads = Integer.parseInt(cmd.getOptionValue("numberOfThreads"));
        }
        if (cmd.hasOption("withBots")) {
            withBots = true;
        }
        if (cmd.hasOption("readPreprocessed")) {
            readPreprocessed = true;
        }
    } catch (UnrecognizedOptionException e) {
        System.out.println("Unrecognized commandline option: " + e.getOption());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("help", options);
        return;
    } catch (ParseException e) {
        System.out.println(
                "There was an error while parsing your command line input. Did you rechecked your syntax before running?");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("help", options);
        return;
    }

    LoggingHandler.initConsoleLog();

    loadPreBuildQueryTypes();

    long startTime = System.nanoTime();

    ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);

    for (int day = 1; day <= 31; day++) {
        String inputFile = inputFilePrefix + String.format("%02d", day) + inputFileSuffix;
        Runnable parseOneMonthWorker = new ParseOneMonthWorker(inputFile, inputFilePrefix, inputHandlerClass,
                queryParserName, queryHandlerClass, day);
        executor.execute(parseOneMonthWorker);
    }
    executor.shutdown();

    while (!executor.isTerminated()) {
        //wait until all workers are finished
    }

    writeQueryTypes(inputFilePrefix);

    long stopTime = System.nanoTime();
    long millis = TimeUnit.MILLISECONDS.convert(stopTime - startTime, TimeUnit.NANOSECONDS);
    Date date = new Date(millis);
    System.out.println("Finished executing with all threads: "
            + new SimpleDateFormat("mm-dd HH:mm:ss:SSSSSSS").format(date));
}

From source file:Executable.LinkImputeR.java

/**
 * Main function/*from   ww  w.j a  v  a2 s .c  om*/
 * @param args Command line arguments
 * @throws Exception If an uncaught error occurs
 */
public static void main(String[] args) throws Exception {
    try {
        Options options = new Options();

        OptionGroup all = new OptionGroup();
        all.addOption(Option.builder("c").build());
        all.addOption(Option.builder("s").build());
        all.addOption(Option.builder("v").build());
        all.addOption(Option.builder("h").build());
        options.addOptionGroup(all);

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

        String[] fileNames = commands.getArgs();

        XMLConfiguration c;
        boolean done = false;

        if (commands.hasOption("c")) {
            if (fileNames.length == 2) {
                c = convert(new File(fileNames[0]));
                writeXML(c, new File(fileNames[1]));
            } else {
                System.out.println("An input and output file must be provided");
                System.out.println();
                help();
            }
            done = true;
        }

        if (commands.hasOption("s")) {
            if (fileNames.length == 1) {
                c = convert(new File(fileNames[0]));
                accuracy(c);
            } else {
                System.out.println("An input file must be provided");
                System.out.println();
                help();
            }
            done = true;
        }

        if (commands.hasOption("v")) {
            System.out.println("LinkImputeR version 1.1.3");
            done = true;
        }

        if (commands.hasOption("h")) {
            help();
            done = true;
        }

        if (!done) {
            if (fileNames.length == 3) {
                File xml = new File(fileNames[0]);

                FileBasedConfigurationBuilder<XMLConfiguration> builder = new FileBasedConfigurationBuilder<>(
                        XMLConfiguration.class).configure(new Parameters().xml().setFile(xml));

                XMLConfiguration config = builder.getConfiguration();

                switch (config.getString("mode")) {
                case "accuracy":
                    accuracy(config);
                    break;
                case "impute":
                    if (args.length == 3) {
                        impute(config, args[1], new File(args[2]));
                    } else {
                        impute(config, null, null);
                    }
                    break;
                }
            } else {
                System.out.println("An input file, case name and output file must be provided (in that order)");
                System.out.println();
                help();
            }
        }
    } catch (UnrecognizedOptionException ex) {
        System.err.println("Unrecognised command line option (" + ex.getOption() + ")");
        System.err.println();
        help();
    } catch (AlreadySelectedException ex) {
        System.err.println("Only one option can be selected at a time");
        System.err.println();
        help();
    } catch (VCFException ex) {
        System.err.println("=====");
        System.err.println("ERROR");
        System.err.println("=====");
        System.err.println("There's a problem with the VCF file");
        System.err.println(ex.getMessage());
        System.err.println();
        System.err.println("Technical details follow:");
        throw ex;
    } catch (INIException ex) {
        System.err.println("=====");
        System.err.println("ERROR");
        System.err.println("=====");
        System.err.println("There's a problem with the ini file");
        System.err.println(ex.getMessage());
        System.err.println();
        System.err.println("Technical details follow:");
        throw ex;
    } catch (OutputException ex) {
        System.err.println("=====");
        System.err.println("ERROR");
        System.err.println("=====");
        System.err.println("There's a problem writing an output file");
        System.err.println(ex.getMessage());
        System.err.println();
        System.err.println("Technical details follow:");
        throw ex;
    } catch (AlgorithmException ex) {
        System.err.println("=====");
        System.err.println("ERROR");
        System.err.println("=====");
        System.err.println("There's a problem with the algorithms");
        System.err.println(ex.getMessage());
        System.err.println();
        System.err.println("Technical details follow:");
        throw ex;
    } catch (ProgrammerException ex) {
        System.err.println("=====");
        System.err.println("ERROR");
        System.err.println("=====");
        System.err.println("Well this is embarrassing.  This shouldn't have happened.  "
                + "Please contact the maintainer if you can not solve the error"
                + "from the technical details.");
        System.err.println();
        System.err.println("Technical details follow:");
        throw ex;
    } catch (Exception ex) {
        System.err.println("=====");
        System.err.println("ERROR");
        System.err.println("=====");
        System.err.println("Well this is embarrassing.  This was not expected to have happened.  "
                + "Please contact the maintainer if you can not solve the error"
                + "from the technical details.");
        System.err.println();
        System.err.println("Note: The maintainer would be interested in knowing "
                + "about any XML related messages so he can write nicer error "
                + "messages for these problems.");
        System.err.println();
        System.err.println("Technical details follow:");
        throw ex;
    }
}

From source file:calculadora.controlador.ControladorCLI.java

/**
 * Metodo realiza la segunda etapa de analisis del commons cli de Apache.
 *
 * Lee la linea de comandos y una vez la lee con exito pasa el comando a que
 * busque la funcion de ese comando./*from  www  .  j a va  2  s . c  om*/
 *
 * Si los argumentos recibidos son mayores de tres no conviene parsear, ya
 * que nunca deveria ser mayor de 3.
 *
 * Controlo aqui la excepcion para poder personalizarla y poder mostrar la
 * informacion correcta por pantalla con el comando equivocado.
 *
 * @see PosixParser POSIX
 * @see CommandLineParser
 * @see CommandLine
 * @exception MissingArgumentException error de argumentos de comandos
 * @exception UnrecognizedOptionException no reconoce el comando
 * @exception ParseException error al parsear los comandos
 * @param args Linea de comandos
 * @throws IllegalArgumentException error argumentos de java o programa
 * @throws NumberFormatException error de tipo de argumentos
 */
private void leerComando(String[] args) throws IllegalArgumentException, NumberFormatException {
    try {
        //Si hay mas de 3 argumentos directamente error, no conviene parsear
        if (args.length > 3) {
            notificarError(
                    "Demasiados comandos o argumentos, solo se puede " + "realizar una operacion cada vez.");
        } else {
            CommandLineParser parser = new PosixParser();
            CommandLine cmdLine = parser.parse(opciones, args);
            buscarComando(cmdLine);
        }
    } catch (MissingArgumentException mae) {
        //Si la opcion es de posix largo muestro el nombre del comando largo
        //Sino muestro el posix corto de error.
        notificarError(mae.getOption().hasLongOpt()
                ? "El comando '--" + mae.getOption().getLongOpt() + "' necesita mas argumentos."
                : "El comando '-" + mae.getOption().getOpt() + "' necesita mas argumentos.");
    } catch (UnrecognizedOptionException uoe) {
        notificarError("'" + uoe.getOption() + "' no se reconoce como " + "comando interno del programa.");
    } catch (ParseException pe) {
        notificarError(pe.getMessage());
    }
}

From source file:com.planet57.gshell.util.cli2.CliProcessor.java

public void process(final String... args) throws Exception {
    checkNotNull(args);/* w  w  w.j a v a  2s . c om*/
    if (log.isTraceEnabled()) {
        log.trace("Processing: {}", Arrays.toString(args));
    }

    CliParser parser = flavor.create();
    log.trace("Parser: {}", parser);

    CommandLine cl;
    try {
        cl = parser.parse(createOptions(), args, stopAtNonOption);
    } catch (UnrecognizedOptionException e) {
        throw new ProcessingException(messages.UNDEFINED_OPTION(e.getOption()));
    } catch (MissingArgumentException e) {
        OptionDescriptor desc = ((Opt) e.getOption()).getDescriptor();
        throw new ProcessingException(messages.MISSING_OPERAND(desc.getSyntax(), desc.getToken()));
    } catch (ParseException e) {
        throw new ProcessingException(e);
    }

    Set<CliDescriptor> present = new HashSet<>();
    boolean override = false;

    if (log.isTraceEnabled()) {
        log.trace("Parsed options: {}", Arrays.toString(cl.getOptions()));
    }

    for (Object tmp : cl.getOptions()) {
        Opt opt = (Opt) tmp;
        log.trace("Processing option: {}", opt);

        OptionDescriptor desc = opt.getDescriptor();
        present.add(desc);

        // Track the override, this is used to handle when --help present, but a required arg/opt is missing
        if (!override) {
            override = desc.getOverride();
        }

        Handler handler = Handlers.create(desc);
        String[] values = opt.getValues();

        if (values == null || values.length == 0) {
            // Set the value
            handler.handle(opt.getValue());
        } else {
            // Set the values
            for (String value : values) {
                handler.handle(value);
            }
        }
    }

    log.trace("Remaining arguments: {}", cl.getArgList());

    int i = 0;
    for (final String arg : cl.getArgs()) {
        log.trace("Processing argument: {}", arg);

        // Check if we allow an argument or we have overflowed
        if (i >= argumentDescriptors.size()) {
            throw new ProcessingException(argumentDescriptors.size() == 0 ? messages.NO_ARGUMENT_ALLOWED(arg)
                    : messages.TOO_MANY_ARGUMENTS(arg));
        }

        ArgumentDescriptor desc = argumentDescriptors.get(i);
        present.add(desc);

        // For single-valued args, increment the argument index, else let the multivalued handler consume it
        if (!desc.isMultiValued()) {
            i++;
        }

        // Set the value
        Handler handler = Handlers.create(desc);
        handler.handle(arg);
    }

    // Check for any required arguments which were not present
    if (!override) {
        try {
            parser.ensureRequiredOptionsPresent();
        } catch (MissingOptionException e) {
            throw new ProcessingException(messages.REQUIRED_OPTION_MISSING(e.getMissingOptions()));
        }

        for (ArgumentDescriptor arg : argumentDescriptors) {
            if (arg.isRequired() && !present.contains(arg)) {
                throw new ProcessingException(messages.REQUIRED_ARGUMENT_MISSING(arg.getToken()));
            }
        }
    }

    // TODO: Handle setting defaults
}

From source file:com.netflix.exhibitor.standalone.ExhibitorCreator.java

public ExhibitorCreator(String[] args) throws Exception {
    ExhibitorCLI cli = new ExhibitorCLI();

    CommandLine commandLine;/*from   w  w w. j  av  a 2 s.com*/
    try {
        CommandLineParser parser = new PosixParser();
        commandLine = parser.parse(cli.getOptions(), args);
        if (commandLine.hasOption('?') || commandLine.hasOption(HELP)
                || (commandLine.getArgList().size() > 0)) {
            throw new ExhibitorCreatorExit(cli);
        }
    } catch (UnrecognizedOptionException e) {
        throw new ExhibitorCreatorExit("Unknown option: " + e.getOption(), cli);
    } catch (ParseException e) {
        throw new ExhibitorCreatorExit(cli);
    }

    checkMutuallyExclusive(cli, commandLine, S3_BACKUP, FILESYSTEMBACKUP);

    String s3Region = commandLine.getOptionValue(S3_REGION, null);
    PropertyBasedS3Credential awsCredentials = null;
    if (commandLine.hasOption(S3_CREDENTIALS)) {
        awsCredentials = new PropertyBasedS3Credential(new File(commandLine.getOptionValue(S3_CREDENTIALS)));
    }

    BackupProvider backupProvider = null;
    if ("true".equalsIgnoreCase(commandLine.getOptionValue(S3_BACKUP))) {
        backupProvider = new S3BackupProvider(new S3ClientFactoryImpl(), awsCredentials, s3Region);
    } else if ("true".equalsIgnoreCase(commandLine.getOptionValue(FILESYSTEMBACKUP))) {
        backupProvider = new FileSystemBackupProvider();
    }

    int timeoutMs = Integer.parseInt(commandLine.getOptionValue(TIMEOUT, "30000"));
    int logWindowSizeLines = Integer.parseInt(commandLine.getOptionValue(LOGLINES, "1000"));
    int configCheckMs = Integer.parseInt(commandLine.getOptionValue(CONFIGCHECKMS, "30000"));
    String useHostname = commandLine.getOptionValue(HOSTNAME, cli.getHostname());
    int httpPort = Integer.parseInt(commandLine.getOptionValue(HTTP_PORT, "8080"));
    String extraHeadingText = commandLine.getOptionValue(EXTRA_HEADING_TEXT, null);
    boolean allowNodeMutations = "true".equalsIgnoreCase(commandLine.getOptionValue(NODE_MUTATIONS, "true"));

    String configType = commandLine.hasOption(SHORT_CONFIG_TYPE) ? commandLine.getOptionValue(SHORT_CONFIG_TYPE)
            : (commandLine.hasOption(CONFIG_TYPE) ? commandLine.getOptionValue(CONFIG_TYPE) : null);
    if (configType == null) {
        throw new MissingConfigurationTypeException(
                "Configuration type (-" + SHORT_CONFIG_TYPE + " or --" + CONFIG_TYPE + ") must be specified",
                cli);
    }

    ConfigProvider configProvider = makeConfigProvider(configType, cli, commandLine, awsCredentials,
            backupProvider, useHostname, s3Region);
    if (configProvider == null) {
        throw new ExhibitorCreatorExit(cli);
    }
    boolean isNoneConfigProvider = (configProvider instanceof NoneConfigProvider);
    if (isNoneConfigProvider) {
        backupProvider = null;
    }

    JQueryStyle jQueryStyle;
    try {
        jQueryStyle = JQueryStyle.valueOf(commandLine.getOptionValue(JQUERY_STYLE, "red").toUpperCase());
    } catch (IllegalArgumentException e) {
        throw new ExhibitorCreatorExit(cli);
    }

    securityFile = commandLine.getOptionValue(SECURITY_FILE);
    realmSpec = commandLine.getOptionValue(REALM);
    remoteAuthSpec = commandLine.getOptionValue(REMOTE_CLIENT_AUTHORIZATION);

    String realm = commandLine.getOptionValue(BASIC_AUTH_REALM);
    String user = commandLine.getOptionValue(CONSOLE_USER);
    String password = commandLine.getOptionValue(CONSOLE_PASSWORD);
    String curatorUser = commandLine.getOptionValue(CURATOR_USER);
    String curatorPassword = commandLine.getOptionValue(CURATOR_PASSWORD);
    SecurityHandler handler = null;
    if (notNullOrEmpty(realm) && notNullOrEmpty(user) && notNullOrEmpty(password) && notNullOrEmpty(curatorUser)
            && notNullOrEmpty(curatorPassword)) {
        log.warn(Joiner.on(", ").join(BASIC_AUTH_REALM, CONSOLE_USER, CONSOLE_PASSWORD, CURATOR_USER,
                CURATOR_PASSWORD) + " - have been deprecated. Use TBD instead");
        handler = makeSecurityHandler(realm, user, password, curatorUser, curatorPassword);
    }

    String aclId = commandLine.getOptionValue(ACL_ID);
    String aclScheme = commandLine.getOptionValue(ACL_SCHEME);
    String aclPerms = commandLine.getOptionValue(ACL_PERMISSIONS);
    ACLProvider aclProvider = null;
    if (notNullOrEmpty(aclId) || notNullOrEmpty(aclScheme) || notNullOrEmpty(aclPerms)) {
        aclProvider = getAclProvider(cli, aclId, aclScheme, aclPerms);
        if (aclProvider == null) {
            throw new ExhibitorCreatorExit(cli);
        }
    }

    ServoRegistration servoRegistration = null;
    if ("true".equalsIgnoreCase(commandLine.getOptionValue(SERVO_INTEGRATION, "false"))) {
        servoRegistration = new ServoRegistration(new JmxMonitorRegistry("exhibitor"), 60000);
    }

    String preferencesPath = commandLine.getOptionValue(PREFERENCES_PATH);

    this.builder = ExhibitorArguments.builder().connectionTimeOutMs(timeoutMs)
            .logWindowSizeLines(logWindowSizeLines).thisJVMHostname(useHostname).configCheckMs(configCheckMs)
            .extraHeadingText(extraHeadingText).allowNodeMutations(allowNodeMutations).jQueryStyle(jQueryStyle)
            .restPort(httpPort).aclProvider(aclProvider).servoRegistration(servoRegistration)
            .preferencesPath(preferencesPath);

    this.securityHandler = handler;
    this.backupProvider = backupProvider;
    this.configProvider = configProvider;
    this.httpPort = httpPort;
}

From source file:org.eclipse.jetty.Starter.java

/**
 * Starts the jetty server using the war file in which this class is embedded
 *//* w ww .  ja va 2 s  .  com*/
public static void main(String[] args) {
    Options options = buildOptions();
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine cmd = parser.parse(options, args);
        String hostname = cmd.getOptionValue('h', "localhost");
        int port = parsePort(cmd);
        if (cmd.hasOption('l')) {
            String loggingFile = cmd.getOptionValue('l');
            if (!new File(loggingFile).exists()) {
                System.out.println(
                        "The provided logging configuration file " + loggingFile + " does not exists!");
                printHelp(options);
                return;
            }
            System.setProperty("log4j.configuration", "file:" + loggingFile);
        }
        if (cmd.hasOption('c')) {
            String propertiesFile = cmd.getOptionValue('c');
            if (!new File(propertiesFile).exists()) {
                System.out.println("The provided properties file " + propertiesFile + " does not exists!");
                printHelp(options);
                return;
            }
            System.setProperty("configFile", propertiesFile);
        }

        startServer(hostname, port);

    } catch (MissingArgumentException mae) {
        System.out.println("The option " + mae.getOption().getOpt() + " is missing required argument!");
        printHelp(options);
    } catch (UnrecognizedOptionException uoe) {
        System.out.println("Usage of unsupported option " + uoe.getOption() + "!");
        printHelp(options);
    } catch (ParseException pe) {
        System.out.println("Wrong command line arguments provided!");
        printHelp(options);
    }
}

From source file:org.sonatype.gshell.util.cli2.CliProcessor.java

public void process(final String... args) throws Exception {
    assert args != null;

    CliParser parser = null;//w  w w. j a  v a  2s.  c o  m

    switch (flavor) {
    case POSIX:
        parser = new PosixParser();
        break;
    case GNU:
        parser = new GnuParser();
        break;
    }

    assert parser != null;

    CommandLine cl;

    try {
        cl = parser.parse(createOptions(), args, stopAtNonOption);
    } catch (UnrecognizedOptionException e) {
        throw new ProcessingException(Messages.UNDEFINED_OPTION.format(e.getOption()));
    } catch (MissingArgumentException e) {
        OptionDescriptor desc = ((Opt) e.getOption()).getDescriptor();
        throw new ProcessingException(
                Messages.MISSING_OPERAND.format(desc.getSyntax(), desc.renderToken(messages)));
    } catch (ParseException e) {
        throw new ProcessingException(e);
    }

    Set<CliDescriptor> present = new HashSet<CliDescriptor>();
    boolean override = false;

    for (Object tmp : cl.getOptions()) {
        Opt opt = (Opt) tmp;
        log.trace("Processing option: {}", opt);

        OptionDescriptor desc = opt.getDescriptor();
        present.add(desc);

        // Track the override, this is used to handle when --help present, but a required arg/opt is missing
        if (!override) {
            override = desc.getOverride();
        }

        Handler handler = Handlers.create(desc);
        String[] values = opt.getValues();

        if (values == null || values.length == 0) {
            // Set the value
            handler.handle(opt.getValue());
        } else {
            // Set the values
            for (String value : values) {
                handler.handle(value);
            }
        }
    }

    log.trace("Remaining arguments: {}", cl.getArgList());

    int i = 0;
    for (final String arg : cl.getArgs()) {
        log.trace("Processing argument: {}", arg);

        // Check if we allow an argument or we have overflowed
        if (i >= argumentDescriptors.size()) {
            throw new ProcessingException(
                    argumentDescriptors.size() == 0 ? Messages.NO_ARGUMENT_ALLOWED.format(arg)
                            : Messages.TOO_MANY_ARGUMENTS.format(arg));
        }

        ArgumentDescriptor desc = argumentDescriptors.get(i);
        present.add(desc);

        // For single-valued args, increment the argument index, else let the multivalued handler consume it
        if (!desc.isMultiValued()) {
            i++;
        }

        // Set the value
        Handler handler = Handlers.create(desc);
        handler.handle(arg);
    }

    // Check for any required arguments which were not present
    if (!override) {
        try {
            parser.ensureRequiredOptionsPresent();
        } catch (MissingOptionException e) {
            throw new ProcessingException(Messages.REQUIRED_OPTION_MISSING.format(e.getMissingOptions()));
        }

        for (ArgumentDescriptor arg : argumentDescriptors) {
            if (arg.isRequired() && !present.contains(arg)) {
                throw new ProcessingException(
                        Messages.REQUIRED_ARGUMENT_MISSING.format(arg.renderToken(messages)));
            }
        }
    }

    // TODO: Handle setting defaults
}