Example usage for org.apache.commons.cli ParseException getLocalizedMessage

List of usage examples for org.apache.commons.cli ParseException getLocalizedMessage

Introduction

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

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:es.sistedes.handle.generator.CliLauncher.java

/**
 * Runs the {@link CliLauncher}/*from ww  w .ja  va  2  s .c o m*/
 * 
 * @param args
 * @throws Exception
 */
private static void run(String[] args) throws Exception {
    try {
        CommandLine commandLine = null;

        try {
            CommandLineParser parser = new DefaultParser();
            commandLine = parser.parse(options, args);
        } catch (ParseException e) {
            printError(e.getLocalizedMessage());
            printHelp();
            throw e;
        }

        Conversor conversor = new Conversor(commandLine.getOptionValue(PREFIX));

        FileInputStream input = null;
        if (commandLine.hasOption(INPUT)) {
            input = new FileInputStream(new File(commandLine.getOptionValue(INPUT)));
            conversor.changeInput(input);
        }

        FileOutputStream output = null;
        if (commandLine.hasOption(OUTPUT)) {
            output = new FileOutputStream(new File(commandLine.getOptionValue(OUTPUT)));
            conversor.changeOutput(output);
        }

        conversor.putOption(ConversorOptions.USE_GUID, commandLine.hasOption(USE_GUID));
        conversor.putOption(ConversorOptions.ADD_DELETE, commandLine.hasOption(ADD_DELETE));
        if (commandLine.hasOption(FILTER)) {
            conversor.putOption(ConversorOptions.FILTER, commandLine.getOptionValue(FILTER));
        }

        try {
            conversor.generate();
        } finally {
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(output);
        }
    } catch (ConversionException | FileNotFoundException e) {
        printError("ERROR: " + e.getLocalizedMessage());
        throw e;
    }
}

From source file:es.csic.iiia.planes.generator.Cli.java

/**
 * Parse the provided list of arguments according to the program's options.
 *
 * @param in_args list of input arguments.
 * @return a configuration object set according to the input options.
 *///from  w w  w .  j a  v  a2 s .  c  o m
private static Configuration parseOptions(String[] in_args) {
    CommandLineParser parser = new PosixParser();
    CommandLine line = null;
    Properties settings = loadDefaultSettings();

    try {
        line = parser.parse(options, in_args);
    } catch (ParseException ex) {
        Logger.getLogger(Cli.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
        showHelp();
    }

    if (line.hasOption('h')) {
        showHelp();
    }

    if (line.hasOption('d')) {
        dumpSettings();
    }

    if (line.hasOption('s')) {
        String fname = line.getOptionValue('s');
        try {
            settings.load(new FileReader(fname));
        } catch (IOException ex) {
            throw new IllegalArgumentException("Unable to load the settings file \"" + fname + "\"");
        }
    }

    // Apply overrides
    settings.setProperty("quiet", String.valueOf(line.hasOption('q')));
    Properties overrides = line.getOptionProperties("o");
    settings.putAll(overrides);

    String[] args = line.getArgs();
    if (args.length < 1) {
        showHelp();
    }
    settings.setProperty("problem", args[0]);

    Configuration c = new Configuration(settings);

    if (line.hasOption('t')) {
        System.exit(0);
    }
    return c;
}

From source file:es.csic.iiia.planes.cli.Cli.java

/**
 * Parse the provided list of arguments according to the program's options.
 * /*from   www . ja  v  a2s.com*/
 * @param in_args
 *            list of input arguments.
 * @return a configuration object set according to the input options.
 */
private static Configuration parseOptions(String[] in_args) {
    CommandLineParser parser = new PosixParser();
    CommandLine line = null;
    Properties settings = loadDefaultSettings();

    try {
        line = parser.parse(options, in_args);
    } catch (ParseException ex) {
        Logger.getLogger(Cli.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
        showHelp();
    }

    if (line.hasOption('h')) {
        showHelp();
    }

    if (line.hasOption('d')) {
        dumpSettings();
    }

    if (line.hasOption('s')) {
        String fname = line.getOptionValue('s');
        try {
            settings.load(new FileReader(fname));
        } catch (IOException ex) {
            throw new IllegalArgumentException("Unable to load the settings file \"" + fname + "\"");
        }
    }

    // Apply overrides
    settings.setProperty("gui", String.valueOf(line.hasOption('g')));
    settings.setProperty("quiet", String.valueOf(line.hasOption('q')));
    Properties overrides = line.getOptionProperties("o");
    settings.putAll(overrides);

    String[] args = line.getArgs();
    if (args.length < 1) {
        showHelp();
    }
    settings.setProperty("problem", args[0]);

    Configuration c = new Configuration(settings);
    System.out.println(c.toString());
    /**
     * Modified by Guillermo B. Print settings to a result file, titled
     * "results.txt"
     */
    try {
        FileWriter fw = new FileWriter("results.txt", true);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter out = new PrintWriter(bw);
        String[] results = c.toString().split("\n");
        // out.println(results[8]);

        for (String s : results) {
            out.println(s);

        }
        // out.println(results[2]);
        // out.println(results[8]);
        out.close();
    } catch (IOException e) {
    }

    /**
     * Modified by Ebtesam Save settings to a .csv file, titled
     * "resultsCSV.csv"
     */

    try {
        FileWriter writer = new FileWriter("resultsCSV.csv", true);
        FileReader reader = new FileReader("resultsCSV.csv");

        String header = "SAR Strategy,# of Searcher UAVs,# of Survivors,"
                + "# of Survivors rescued,Min.Time needed to rescue Survivors,Mean. Time needed to rescue Survivors,Max. Time needed to rescue Survivors,"
                + "# of Survivors found,Min. Time needed to find Survivors,Mean Time needed to find Survivors,Max. Time needed to find Survivors,"
                + "Running Time of Simulation\n";
        if (reader.read() == -1) {
            writer.append(header);
            writer.append("\n");
        }
        reader.close();
        String[] results = c.toString().split("\n");
        writer.append(results[2].substring(10));
        writer.append(",");
        writer.append(results[20].substring(11));
        writer.append(",");
        writer.append(results[30].substring(18));
        writer.write(",");
        writer.close();
    } catch (IOException e) {
    }

    if (line.hasOption('t')) {
        System.exit(0);
    }
    return c;
}

From source file:com.tc.config.schema.setup.BaseConfigurationSetupManagerTest.java

private static CommandLine parseDefaultCommandLine(String[] args, ConfigMode configMode)
        throws ConfigurationSetupException {
    try {/*from ww  w  .java2 s  . com*/
        if (args == null || args.length == 0) {
            return new PosixParser().parse(new Options(), new String[0]);
        } else {
            Options options = createOptions(configMode);

            return new PosixParser().parse(options, args);
        }
    } catch (ParseException pe) {
        throw new ConfigurationSetupException(pe.getLocalizedMessage(), pe);
    }
}

From source file:com.mapd.parser.server.CalciteServerCaller.java

private void doWork(String[] args) {
    CalciteServerWrapper calciteServerWrapper = null;

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

    Option port = Option.builder("p").hasArg().desc("port number").longOpt("port").build();

    Option data = Option.builder("d").hasArg().desc("data directory").required().longOpt("data").build();

    Option extensions = Option.builder("e").hasArg().desc("extension signatures directory")
            .longOpt("extensions").build();

    options.addOption(port);/*w  w  w  . j  av a  2s .  co m*/
    options.addOption(data);
    options.addOption(extensions);

    CommandLineParser parser = new DefaultParser();

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        MAPDLOGGER.error(ex.getLocalizedMessage());
        help(options);
        exit(0);
    }

    int portNum = Integer.valueOf(cmd.getOptionValue("port", "9093"));
    String dataDir = cmd.getOptionValue("data", "data");
    String extensionsDir = cmd.getOptionValue("extensions", "build/QueryEngine");
    final Path extensionFunctionsAstFile = Paths.get(extensionsDir, "ExtensionFunctions.ast");

    //Add logging to our log files directories
    Properties p = new Properties();
    try {
        p.load(getClass().getResourceAsStream("/log4j.properties"));
    } catch (IOException ex) {
        MAPDLOGGER.error("Could not load log4j property file from resources " + ex.getMessage());
    }
    p.put("log.dir", dataDir); // overwrite "log.dir"
    PropertyConfigurator.configure(p);

    calciteServerWrapper = new CalciteServerWrapper(portNum, -1, dataDir, extensionFunctionsAstFile.toString());

    while (true) {
        try {
            Thread t = new Thread(calciteServerWrapper);
            t.start();
            t.join();
            if (calciteServerWrapper.shutdown()) {
                break;
            }
        } catch (Exception x) {
            x.printStackTrace();
        }
    }
}

From source file:com.github.horrorho.inflatabledonkey.args.PropertyLoader.java

@Override
public boolean test(String[] args) throws IllegalArgumentException {
    try {//from www .  j a v a 2 s .c  o  m
        Map<Option, Property> optionKeyMap = optionKeyMapSupplier.get();

        Options options = new Options();
        optionKeyMap.keySet().forEach(options::addOption);

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

        Map<Property, String> properties = Stream.of(commandLine.getOptions())
                .collect(Collectors.toMap(optionKeyMap::get, this::parse));

        if (properties.containsKey(Property.ARGS_HELP)) {
            help(OptionsFactory.options().keySet());
            return false;
        }

        List<String> operands = commandLine.getArgList();
        switch (operands.size()) {
        case 0:
            // No setAuthenticationProperties credentials
            throw new IllegalArgumentException("missing appleid/ password or authentication token");
        case 1:
            // Authentication token
            properties.put(Property.AUTHENTICATION_TOKEN, operands.get(0));
            break;
        case 2:
            // AppleId/ password pair
            properties.put(Property.AUTHENTICATION_APPLEID, operands.get(0));
            properties.put(Property.AUTHENTICATION_PASSWORD, operands.get(1));
            break;
        default:
            throw new IllegalArgumentException(
                    "too many non-optional arguments, expected appleid/ password or authentication token only");
        }
        Property.setProperties(properties);
        return true;

    } catch (ParseException ex) {
        throw new IllegalArgumentException(ex.getLocalizedMessage());
    }
}

From source file:com.mindquarry.jcr.jackrabbit.JackrabbitRMIRepositoryStandalone.java

/**
 * Evaluates the given command line arguments, initializes connection to the
 * persistence layer and starts the specified actions.
 * /*from   w ww .j  av a2  s.c  o  m*/
 * @param args the command line arguments
 */
private CommandLine parse(String[] args) throws Exception {
    // create the parser
    CommandLine line = null;
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getLocalizedMessage());
        printUsage();
        return null;
    }
    return line;
}

From source file:ca.phon.app.modules.EntryPointArgs.java

/**
 * Parse command line arguments.//from  w w  w.ja va  2 s  . com
 * 
 * @param args
 */
public void parseArgs(String[] args) {
    final Options options = new Options();
    options.addOption(PROJECT_NAME_OPT, PROJECT_NAME, true, PROJECT_NAME_DESC);
    options.addOption(PROJECT_LOCATION_OPT, PROJECT_LOCATION, true, PROJECT_LOCATION_DESC);
    options.addOption(CORPUS_NAME_OPT, CORPUS_NAME, true, CORPUS_NAME_DESC);
    options.addOption(SESSION_NAME_OPT, SESSION_NAME, true, SESSION_NAME_DESC);

    final CommandLineParser parser = new EntryPointArgParser();

    try {
        final CommandLine cmdLine = parser.parse(options, args, false);
        for (Option opt : cmdLine.getOptions()) {
            put(opt.getLongOpt(), opt.getValue());
        }
    } catch (ParseException e) {
        LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
}

From source file:com.engineering.ses.spell.clientstubj.cmdclient.CommandClient.java

/***************************************************************************
 * Main loop of the command client/*ww w .j  a va 2s. c  om*/
 * @throws Exception 
 **************************************************************************/
private void mainLoop(String[] args) throws Exception {
    CommandLineParser parser = new BasicParser();

    try {
        m_options = parser.parse(m_optionsDef, args);
    } catch (ParseException ex) {
        showHelp();
        throw new RuntimeException("Invalid arguments: " + ex.getLocalizedMessage());
    }

    start();

    if (m_options.hasOption(OPT_EXEC)) {
        String exec = m_options.getOptionValue(OPT_EXEC);
        if (exec == null || exec.trim().isEmpty()) {
            showHelp();
            throw new RuntimeException("Invalid value for --exec (-e) option: '" + exec + "'");
        }
        executionLoop(exec);
    } else {
        interactiveLoop();
    }
}

From source file:com.mindquarry.persistence.client.CommandLine.java

/**
 * Evaluates the given command line arguments, initializes connection to the
 * persistence layer and starts the specified actions.
 * //from ww w .j av  a 2 s  . c o  m
 * @param args the command line arguments
 */
private void run(String[] args) throws Exception {
    logger = new ConsoleLogger(ConsoleLogger.LEVEL_WARN);

    // create the parser
    org.apache.commons.cli.CommandLine line = null;
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getLocalizedMessage());
        printUsage();
        return;
    }
    // init factory configuration
    DefaultConfiguration config = new DefaultConfiguration("credentials"); //$NON-NLS-1$
    config.setAttribute("login", line.getOptionValue(O_USER)); //$NON-NLS-1$
    config.setAttribute("password", line.getOptionValue(O_PWD)); //$NON-NLS-1$
    config.setAttribute("rmi", line.getOptionValue(O_REPO)); //$NON-NLS-1$

    Map<String, String> mappings = namespaceMappings();
    DefaultConfiguration allMappingsConfig = new DefaultConfiguration("mappings");
    config.addChild(allMappingsConfig);

    for (String prefix : mappings.keySet()) {
        DefaultConfiguration mappingConfig = new DefaultConfiguration("mapping");
        mappingConfig.setAttribute("prefix", prefix);
        mappingConfig.setAttribute("namespace", mappings.get(prefix));
        allMappingsConfig.addChild(mappingConfig);
    }

    // init connection to persistence layer
    CastorSessionFactoryStandalone factory = new CastorSessionFactoryStandalone();
    factory.enableLogging(logger);
    factory.configure(config);
    factory.initialize();

    CastorSessionStandalone session = factory.currentSession();

    // check what actions are specified
    if (line.hasOption(O_PERSIST)) {
        persistTypes(line.getOptionValues(O_PERSIST), session);
    } else if (line.hasOption(O_DEL)) {
        deleteTypes(line.getOptionValues(O_DEL), session);
    }
    session.commit();
}