Example usage for org.apache.commons.cli CommandLine getOptionProperties

List of usage examples for org.apache.commons.cli CommandLine getOptionProperties

Introduction

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

Prototype

public Properties getOptionProperties(String opt) 

Source Link

Document

Retrieve the map of values associated to the option.

Usage

From source file:pyromaniac.AcaciaMain.java

/**
 * Populate settings from command line./*from   w w  w  .ja  v a  2 s  .  c om*/
 *
 * @param clObj object containing command line parameters
 * @return the Acacia run settings, with defaults overriden by user-specified values from the command line
 * @throws Exception any exception that occurs while populating settings from the command line
 */
private HashMap<String, String> populateSettingsFromCommandLine(CommandLine clObj) throws Exception {
    HashMap<String, String> settings = AcaciaEngine.getEngine().getDefaultSettings();

    //we are only interested in -D

    Properties p = clObj.getOptionProperties("D");

    for (Object key : p.keySet()) {
        String keyS = (String) key;

        Object val = p.get(key);
        String valS = (String) val;
        if (settings.containsKey(keyS)) {
            //only way to set parameter to null using command line.
            if (valS.equals("null")) {
                valS = null;
            }

            System.out.println("Loading from commandline: " + keyS + "=" + valS);
            settings.put(keyS, valS);
        } else {
            throw new Exception("No such parameter: " + keyS);
        }
    }

    return settings;
}

From source file:solidbase.Main.java

/**
 * For internal (testing) use only: a main method that does not catch and print exceptions.
 *
 * @param args The arguments from the command line.
 * @throws SQLExecutionException When an {@link SQLException} is thrown during execution of a database change.
 *///from   w w w . j  av  a  2  s .c  o m
// TODO Make this protected.
static public void main0(String... args) throws SQLExecutionException {
    if (console == null)
        console = new Console();

    // Configure the commandline options

    Options options = new Options();
    options.addOption("verbose", false, "be extra verbose");
    options.addOption("dumplog", true, "export historical upgrade results to an XML file");
    options.addOption("driver", true, "sets the JDBC driverclass");
    options.addOption("url", true, "sets the URL for the database");
    options.addOption("username", true, "sets the default user name to connect with");
    options.addOption("password", true, "sets the password of the default user");
    options.addOption("target", true, "sets the target version to upgrade to");
    options.addOption("upgradefile", true, "specifies the file containing the database upgrades");
    options.addOption("sqlfile", true, "specifies an SQL file to execute");
    options.addOption("D", true, "parameter to the SQL file or upgrade file");
    options.addOption("config", true, "specifies a properties file to use");
    options.addOption("downgradeallowed", false, "allow downgrades to reach the target");
    options.addOption("help", false, "Brings up this page");

    options.getOption("dumplog").setArgName("filename");
    options.getOption("driver").setArgName("classname");
    options.getOption("url").setArgName("url");
    options.getOption("username").setArgName("username");
    options.getOption("password").setArgName("password");
    options.getOption("target").setArgName("version");
    options.getOption("upgradefile").setArgName("filename");
    options.getOption("sqlfile").setArgName("filename");
    options.getOption("D").setArgName("property=value");
    options.getOption("D").setArgs(2);
    options.getOption("D").setValueSeparator('=');
    options.getOption("config").setArgName("filename");

    // Read the commandline options

    CommandLine line;
    try {
        line = new GnuParser().parse(options, args);
    } catch (ParseException e) {
        console.println(e.getMessage());
        printHelp(options);
        return;
    }

    solidbase.config.Options opts = new solidbase.config.Options(line.hasOption("verbose"),
            line.hasOption("dumplog"), line.getOptionValue("driver"), line.getOptionValue("url"),
            line.getOptionValue("username"), line.getOptionValue("password"), line.getOptionValue("target"),
            line.getOptionValue("upgradefile"), line.getOptionValue("sqlfile"), line.getOptionValue("config"),
            line.hasOption("downgradeallowed"), line.hasOption("help"), line.getOptionProperties("D"));

    if (opts.help) {
        printHelp(options);
        return;
    }

    Progress progress = new Progress(console, opts.verbose);
    Configuration configuration = new Configuration(progress, pass, opts);

    if (pass == 1) {
        reload(args, configuration.getDriverJars(), opts.verbose);
        return;
    }

    String error = configuration.getFirstError();
    if (error != null) {
        console.println(error);
        printHelp(options);
        return;
    }

    if (configuration.isVoid()) {
        printHelp(options);
        return;
    }

    solidbase.config.Database def = configuration.getDefaultDatabase();
    Runner runner = new Runner();
    runner.setProgressListener(progress);
    runner.setConnectionAttributes("default", def.getDriver(), def.getUrl(), def.getUserName(),
            def.getPassword());
    for (solidbase.config.Database connection : configuration.getSecondaryDatabases())
        runner.setConnectionAttributes(connection.getName(), connection.getDriver(), connection.getUrl(),
                connection.getUserName(), connection.getPassword());

    for (Entry<Object, Object> entry : configuration.getParameters().entrySet())
        runner.addParameter((String) entry.getKey(), (String) entry.getValue());

    if (configuration.getSqlFile() != null) {
        runner.setSQLFile(Resources.getResource(configuration.getSqlFile()));
        runner.executeSQL();
    } else if (opts.dumplog) {
        runner.setUpgradeFile(Resources.getResource(configuration.getUpgradeFile()));
        runner.setOutputFile(Resources.getResource(line.getOptionValue("dumplog")));
        runner.logToXML();
    } else {
        runner.setUpgradeFile(Resources.getResource(configuration.getUpgradeFile()));
        runner.setUpgradeTarget(configuration.getTarget());
        runner.setDowngradeAllowed(opts.downgradeallowed);
        runner.upgrade();
    }
}

From source file:uk.ac.ebi.smsd.cmd.ArgumentHandler.java

/**
 * Parses the options in the command line arguments and returns an array of
 * strings corresponding to the filenames given as arguments only
 *
 * @param args/*w ww  .  ja  v  a2 s .  c o  m*/
 * @throws org.apache.commons.cli.ParseException
 */
@SuppressWarnings("static-access")
public void parseCommandLineOptions(String[] args) throws ParseException {

    options = new Options();

    options.addOption("h", "help", false, "Help page for command usage");

    options.addOption("s", false, "SubStructure detection");

    options.addOption("a", false, "Add Hydrogen");

    options.addOption("x", false, "Match Atom Type");

    options.addOption("r", false, "Remove Hydrogen");

    options.addOption("z", false, "Ring matching");

    options.addOption("b", false, "Match Bond types (Single, Double etc)");

    options.addOption(Option.builder("q").argName("query_file").hasArg().desc("Query filename").build());

    options.addOption(Option.builder("t").argName("target_file").hasArg().desc("Target filename").build());
    options.addOption(Option.builder("S").argName("suffix").hasArg().desc("Add suffix to the files").build());

    options.addOption("g", false, "create png of the mapping");

    options.addOption(Option.builder("d").argName("WIDTHxHEIGHT").hasArg()
            .desc("Dimension of the image in pixels").build());

    options.addOption("m", false, "Report all Mappings");

    String filterDescr = "Default: 0, Stereo: 1, " + "Stereo+Fragment: 2, Stereo+Fragment+Energy: 3";

    options.addOption(Option.builder("f").argName("filter_number").hasArg().desc(filterDescr).build());

    options.addOption("A", false, "Appends output to existing files, else creates new files");

    options.addOption(Option.builder("N").desc("Do N-way MCS on the target SD file").build());

    options.addOption(
            Option.builder("Q").argName("query_type").hasArg().desc("Query type (MOL, SMI, etc.)").build());

    options.addOption(Option.builder("T").argName("target_type").hasArg()
            .desc("Target type (MOL, SMI, SMIF, etc.)").build());

    options.addOption(
            Option.builder("o").argName("filename").hasArg().desc("Output the substructure to a file").build());

    options.addOption(Option.builder("O").argName("type").hasArg().desc("Output type (SMI, MOL)").build());

    options.addOption(Option.builder("I").argName("option=value").hasArg().desc("Image options").build());

    DefaultParser parser = new DefaultParser();
    CommandLine line = parser.parse(options, args, true);

    if (line.hasOption('Q')) {
        queryType = line.getOptionValue("Q");
    } //else {
    //            queryType = "MOL";
    //        } //XXX default type?

    if (line.hasOption('T')) {
        targetType = line.getOptionValue("T");
    } else {
        targetType = "MOL";
    }

    if (line.hasOption('a')) {
        this.setApplyHAdding(true);
    }

    if (line.hasOption('r')) {
        this.setApplyHRemoval(true);
    }

    if (line.hasOption('m')) {
        this.setAllMapping(true);
    }

    if (line.hasOption('s')) {
        this.setSubstructureMode(true);
    }

    if (line.hasOption('g')) {
        this.setImage(true);
    }

    if (line.hasOption('b')) {
        this.setMatchBondType(true);
    }

    if (line.hasOption('z')) {
        this.setMatchRingType(true);
    }

    if (line.hasOption('x')) {
        this.setMatchAtomType(true);
    }

    remainingArgs = line.getArgs();

    if (line.hasOption('h') || line.getOptions().length == 0) {
        //            System.out.println("Hello");
        helpRequested = true;
    }

    if (line.hasOption('S')) {
        String[] suffix_reader = line.getOptionValues('S');
        if (suffix_reader.length < 1) {
            System.out.println("Suffix required!");
            helpRequested = true;
        }
        setSuffix(suffix_reader[0]);
        setApplySuffix(true);
    }

    if (line.hasOption('f')) {
        String[] filters = line.getOptionValues('f');
        if (filters.length < 1) {
            System.out.println("Chemical filter required (Ranges: 0 to 3)!");
            helpRequested = true;
        }
        setChemFilter((int) new Integer(filters[0]));
    }

    if (line.hasOption('q')) {
        queryFilepath = line.getOptionValue('q');
    }

    if (line.hasOption('t')) {
        targetFilepath = line.getOptionValue('t');
    }

    if (line.hasOption("A")) {
        this.setAppendMode(true);
    }

    if (line.hasOption("N")) {
        setNMCS(true);
    }

    if (line.hasOption("o")) {
        outputSubgraph = true;
        outputFilepath = line.getOptionValue("o");
    }

    if (line.hasOption("O")) {
        outputFiletype = line.getOptionValue("O");
    } else {
        outputFiletype = "MOL";
    }

    if (line.hasOption("d")) {
        String dimensionString = line.getOptionValue("d");
        if (dimensionString.contains("x")) {
            String[] parts = dimensionString.split("x");
            try {
                setImageWidth(Integer.parseInt(parts[0]));
                setImageHeight(Integer.parseInt(parts[1]));
                System.out.println("set image dim to " + getImageWidth() + "x" + getImageHeight());
            } catch (NumberFormatException nfe) {
                throw new ParseException("Malformed dimension string " + dimensionString);
            }
        } else {
            throw new ParseException("Malformed dimension string " + dimensionString);
        }
    }

    if (line.hasOption("I")) {
        imageProperties = line.getOptionProperties("I");
        if (imageProperties.isEmpty()) {
            // used just "-I" by itself
            isImageOptionHelp = true;
        }
    }
}

From source file:uk.ac.imperial.presage2.core.cli.Presage2CLI.java

@SuppressWarnings("static-access")
@Command(description = "Add a new simulation.", name = "add")
void add(String[] args) {

    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("name").hasArg()
            .withDescription("Name of the simulation to add.").isRequired().create("name"));
    options.addOption(OptionBuilder.withArgName("classname").hasArg()
            .withDescription("Name of the RunnableSimulation class to execute for this simulation.")
            .isRequired().create("classname"));
    options.addOption(OptionBuilder.withArgName("finishTime").hasArg()
            .withDescription("Simulation cycle to stop execution at.").isRequired().create("finish"));
    options.addOption(OptionBuilder.withArgName("parameter=value").hasArgs().withValueSeparator()
            .withDescription("Parameters to supply to the simulation.").create("P"));
    options.addOption(OptionBuilder.withLongOpt("group").withDescription("Add as a group").create('g'));
    options.addOption("h", "help", false, "Show help");
    options.addOption("enablelog", false, "Enable logging.");

    CommandLineParser parser = new GnuParser();
    CommandLine cmd;
    try {//from  ww  w.ja  v  a2s  .  co  m
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        new HelpFormatter().printHelp("presage2cli add", options, true);
        return;
    }
    if (cmd.hasOption("h")) {
        new HelpFormatter().printHelp("presage2cli add", options, true);
        return;
    }
    if (!cmd.hasOption("enablelog")) {
        Logger.getRootLogger().setLevel(Level.OFF);
    }

    try {
        Integer.parseInt(cmd.getOptionValue("finish"));
    } catch (NumberFormatException e) {
        System.err.println("finishTime must be an integer.");
        return;
    }

    String initialState = "NOT STARTED";
    if (cmd.hasOption('g')) {
        initialState = "GROUP";
    }

    StorageService storage = getDatabase();

    PersistentSimulation sim = storage.createSimulation(cmd.getOptionValue("name"),
            cmd.getOptionValue("classname"), initialState, Integer.parseInt(cmd.getOptionValue("finish")));

    sim.addParameter("finishTime", cmd.getOptionValue("finish"));
    Properties params = cmd.getOptionProperties("P");
    for (Object param : params.keySet()) {
        sim.addParameter(param.toString(), params.get(param).toString());
    }

    System.out.println("Added simulation ID: " + sim.getID());

    stopDatabase();
}