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:fr.inrialpes.exmo.align.cli.CommonCLI.java

public CommandLine parseCommandLine(String[] args) throws ParseException {
    CommandLineParser parser = new DefaultParser();
    CommandLine line = parser.parse(options, args);
    parameters = line.getOptionProperties("D");
    if (line.hasOption('d')) {
        logger.warn("debug command-line switch DEPRECATED, use logging");
    }/*w ww.  ja  v a 2s .c  o  m*/
    if (line.hasOption('o')) {
        outputfilename = line.getOptionValue('o');
    }
    if (line.hasOption('P')) {
        try {
            String paramfile = line.getOptionValue('P');
            parameters.loadFromXML(new FileInputStream(paramfile));
        } catch (Exception ex) {
            logger.warn("Cannot parse parameter file", ex);
        }
    }
    if (line.hasOption('h')) {
        usage();
        line = null;
    }
    return line;
}

From source file:com.linkedin.cubert.ScriptExecutor.java

/**
 * Properties are collected in the following order--
 * <p/>//w  ww.  j  a  v a 2  s .c o m
 * 1. Azkaban (or other) executor params
 * 2. properties passed through -f argument (for multiple order in CLI order)
 * 3. properties passed as -D arguments directly on CLI
 *
 * @param cmdLine
 * @param executorProps
 * @return
 * @throws URISyntaxException
 * @throws IOException
 */
private static Properties getProperties(CommandLine cmdLine, Properties executorProps)
        throws URISyntaxException, IOException {
    Properties props = new Properties();

    // 1. Substitute executor params
    if (executorProps != null) {
        props.putAll(extractCubertParams(executorProps));
    }

    // 2. -f properties
    String[] propFiles = cmdLine.getOptionValues("f");
    if (propFiles != null && propFiles.length > 0) {
        for (String propFile : propFiles) {
            URI uri = new URI(propFile);
            boolean isHDFS = (uri.getScheme() != null) && uri.getScheme().equalsIgnoreCase("hdfs");
            String path = uri.getPath();
            if (isHDFS) {
                props.load(new BufferedReader(
                        new InputStreamReader(FileSystem.get(new JobConf()).open(new Path(path)))));
            } else {
                props.load(new BufferedReader(new FileReader(path)));
            }
        }
    }

    // 3. -D properties
    if (cmdLine.getOptionProperties("D").size() > 0) {
        props.putAll(cmdLine.getOptionProperties("D"));
    }
    return props;
}

From source file:cn.edu.pku.cbi.mosaichunter.MosaicHunter.java

private static boolean loadConfiguration(String[] args, String configFile) throws Exception {
    OptionBuilder.withArgName("file");
    OptionBuilder.hasArg();/* ww w . jav a 2s. c o m*/
    OptionBuilder.withDescription("config file");
    OptionBuilder.withLongOpt("config");
    Option configFileOption = OptionBuilder.create("C");

    OptionBuilder.withArgName("property=value");
    OptionBuilder.hasArgs(2);
    OptionBuilder.withValueSeparator();
    OptionBuilder.withDescription("properties that overrides the ones in config file");
    OptionBuilder.withLongOpt("properties");
    Option propertiesOption = OptionBuilder.create("P");

    Options options = new Options();
    options.addOption(configFileOption);
    options.addOption(propertiesOption);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException pe) {
        System.out.println(pe.getMessage());
        return false;
    }

    InputStream in = null;

    if (configFile == null || configFile.trim().isEmpty()) {
        configFile = cmd.getOptionValue("C");
        if (configFile != null && new File(configFile).isFile()) {
            in = new FileInputStream(configFile);
        }
    } else {
        in = MosaicHunter.class.getClassLoader().getResourceAsStream(configFile);
    }
    if (in != null) {
        try {
            ConfigManager.getInstance().loadProperties(in);
        } catch (IOException ioe) {
            System.out.println("invalid config file: " + configFile);
            return false;
        } finally {
            in.close();
        }
    }

    Properties properties = cmd.getOptionProperties("P");
    if (properties != null) {
        ConfigManager.getInstance().putAll(properties);
    }

    return !ConfigManager.getInstance().getProperties().isEmpty();
}

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

/**
 * Parse the provided list of arguments according to the program's options.
 * /*from  w  w  w. jav a  2s  . c  o m*/
 * @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.asakusafw.yaess.bootstrap.Yaess.java

static Configuration parseConfiguration(String[] args) throws ParseException {
    assert args != null;
    LOG.debug("Analyzing YAESS bootstrap arguments: {}", Arrays.toString(args));

    ArgumentList argList = ArgumentList.parse(args);
    LOG.debug("Argument List: {}", argList);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(OPTIONS, argList.getStandardAsArray());

    String profile = cmd.getOptionValue(OPT_PROFILE.getOpt());
    LOG.debug("Profile: {}", profile);
    String script = cmd.getOptionValue(OPT_SCRIPT.getOpt());
    LOG.debug("Script: {}", script);
    String batchId = cmd.getOptionValue(OPT_BATCH_ID.getOpt());
    LOG.debug("Batch ID: {}", batchId);
    String flowId = cmd.getOptionValue(OPT_FLOW_ID.getOpt());
    LOG.debug("Flow ID: {}", flowId);
    String executionId = cmd.getOptionValue(OPT_EXECUTION_ID.getOpt());
    LOG.debug("Execution ID: {}", executionId);
    String phaseName = cmd.getOptionValue(OPT_PHASE_NAME.getOpt());
    LOG.debug("Phase name: {}", phaseName);
    String plugins = cmd.getOptionValue(OPT_PLUGIN.getOpt());
    LOG.debug("Plug-ins: {}", plugins);
    Properties arguments = cmd.getOptionProperties(OPT_ARGUMENT.getOpt());
    LOG.debug("Execution arguments: {}", arguments);
    Properties variables = cmd.getOptionProperties(OPT_ENVIRONMENT_VARIABLE.getOpt());
    LOG.debug("Environment variables: {}", variables);
    Properties definitions = cmd.getOptionProperties(OPT_DEFINITION.getOpt());
    LOG.debug("YAESS feature definitions: {}", definitions);

    LOG.debug("Loading plugins: {}", plugins);
    List<File> pluginFiles = CommandLineUtil.parseFileList(plugins);
    ClassLoader loader = CommandLineUtil.buildPluginLoader(Yaess.class.getClassLoader(), pluginFiles);

    Configuration result = new Configuration();
    result.mode = computeMode(flowId, executionId, phaseName);

    LOG.debug("Loading profile: {}", profile);
    File file = new File(profile);
    file = findCustomProfile(file, definitions.getProperty(KEY_CUSTOM_PROFILE));
    try {//w  w w .j a  v a2 s  .c  o m
        definitions.remove(KEY_CUSTOM_PROFILE);
        Map<String, String> env = new HashMap<>();
        env.putAll(System.getenv());
        env.putAll(toMap(variables));
        result.context = new ProfileContext(loader, new VariableResolver(env));
        Properties properties = CommandLineUtil.loadProperties(file);
        result.profile = YaessProfile.load(properties, result.context);
    } catch (Exception e) {
        YSLOG.error(e, "E01001", file.getPath());
        throw new IllegalArgumentException(MessageFormat.format("Invalid profile \"{0}\".", file), e);
    }

    LOG.debug("Loading script: {}", script);
    try {
        Properties properties = CommandLineUtil.loadProperties(new File(script));
        result.script = properties;
    } catch (Exception e) {
        YSLOG.error(e, "E01002", script);
        throw new IllegalArgumentException(MessageFormat.format("Invalid script \"{0}\".", script), e);
    }

    result.batchId = batchId;
    result.flowId = flowId;
    result.executionId = executionId;
    if (phaseName != null) {
        result.phase = ExecutionPhase.findFromSymbol(phaseName);
        if (result.phase == null) {
            throw new IllegalArgumentException(MessageFormat.format("Unknown phase name \"{0}\".", phaseName));
        }
    }

    result.arguments = toMap(arguments);
    result.definitions = toMap(definitions);
    result.extensions = CommandLineUtil.loadExtensions(loader, argList.getExtended());

    LOG.debug("Analyzed YAESS bootstrap arguments");
    return result;
}

From source file:com.github.helenusdriver.driver.tools.Tool.java

/**
 * Creates all defined schemas based on the provided command line information.
 *
 * @author paouelle/*from ww w . jav  a2  s .  co m*/
 *
 * @param  line the command line information
 * @throws Exception if an error occurs while creating schemas
 * @throws LinkageError if the linkage fails for one of the specified entity
 *         class
 * @throws ExceptionInInitializerError if the initialization provoked by one
 *         of the specified entity class fails
 * @throws IllegalArgumentException if no pojos are found in any of the
 *         specified packages
 */
private static void createSchemas(CommandLine line) throws Exception {
    final String[] opts = line.getOptionValues(Tool.schemas.getLongOpt());
    @SuppressWarnings({ "cast", "unchecked", "rawtypes" })
    final Map<String, String> suffixes = (Map<String, String>) (Map) line
            .getOptionProperties(Tool.suffixes.getOpt());
    final boolean matching = line.hasOption(Tool.matches_only.getLongOpt());
    final Sequence s = StatementBuilder.sequence();

    System.out.print(
            Tool.class.getSimpleName() + ": searching for schema definitions in " + Arrays.toString(opts));
    if (!suffixes.isEmpty()) {
        System.out.print(" with " + (matching ? "matching " : "") + "suffixes " + suffixes);
    }
    System.out.println();
    // start by assuming we have classes; if we do they will be nulled from the array
    Tool.createSchemasFromClasses(opts, suffixes, matching, s);
    // now deal with the rest as if they were packages
    Tool.createSchemasFromPackages(opts, suffixes, matching, s);
    if (s.isEmpty() || (s.getQueryString() == null)) {
        System.out.println(Tool.class.getSimpleName() + ": no schemas found matching the specified criteria");
    } else {
        executeCQL(s);
    }
}

From source file:com.github.helenusdriver.driver.tools.Tool.java

/**
 * Inserts all defined objects based on the provided command line information.
 *
 * @author paouelle// w  w w  .j ava 2 s  . co  m
 *
 * @param  line the command line information
 * @throws Exception if an error occurs while inserting objects
 * @throws LinkageError if the linkage fails for one of the specified entity
 *         class
 * @throws ExceptionInInitializerError if the initialization provoked by one
 *         of the specified entity class fails
 * @throws ClassNotFoundException if one of the object creator class is not
 *         found
 * @throws IllegalCycleException if a dependency cycle is detected in the
 *         classes found
 */
private static void insertObjects(CommandLine line) throws Exception {
    final String[] opts = line.getOptionValues(Tool.objects.getLongOpt());
    @SuppressWarnings({ "cast", "unchecked", "rawtypes" })
    final Map<String, String> suffixes = (Map<String, String>) (Map) line
            .getOptionProperties(Tool.suffixes.getOpt());
    final boolean no_dependents = line.hasOption(Tool.no_dependents.getLongOpt());

    System.out
            .print(Tool.class.getSimpleName() + ": searching for object creators in " + Arrays.toString(opts));
    if (!suffixes.isEmpty()) {
        System.out.print(" with suffixes " + suffixes);
    }
    if (no_dependents) {
        System.out.print(" not including dependent creators");
    }
    System.out.println();
    final DirectedGraph<Class<?>> classes = new ConcurrentHashDirectedGraph<>();

    // start by assuming we have classes; if we do they will be nulled from the array
    Tool.findCreatorsFromClasses(classes, opts, no_dependents);
    // now deal with the rest as if they were packages
    Tool.findCreatorsFromPackages(classes, opts, no_dependents);
    // now do a reverse topological sort of the specified graph of classes such that
    // we end up creating objects in the dependent order
    try {
        final List<Class<?>> cs = GraphUtils.sort(classes);

        Collections.reverse(cs);
        Tool.insertObjectsFromClasses(cs, suffixes);
    } catch (IllegalCycleException e) {
        System.out.println(
                Tool.class.getSimpleName() + ": circular creator dependency detected: " + e.getCycle());
        throw e;
    }
}

From source file:com.github.helenusdriver.driver.tools.Tool.java

/**
 * Creates all defined Json schemas based on the provided command line
 * information./*from   w  ww  .  j a  v a 2  s  .c  o  m*/
 *
 * @author paouelle
 *
 * @param  line the command line information
 * @throws Exception if an error occurs while creating schemas
 * @throws LinkageError if the linkage fails for one of the specified entity
 *         class
 * @throws ExceptionInInitializerError if the initialization provoked by one
 *         of the specified entity class fails
 * @throws IllegalArgumentException if no pojos are found in any of the
 *         specified packages
 */
private static void createJsonSchemas(CommandLine line) throws Exception {
    final String[] opts = line.getOptionValues(Tool.jsons.getLongOpt());
    @SuppressWarnings({ "cast", "unchecked", "rawtypes" })
    final Map<String, String> suffixes = (Map<String, String>) (Map) line
            .getOptionProperties(Tool.suffixes.getOpt());
    final boolean matching = line.hasOption(Tool.matches_only.getLongOpt());
    final Map<Class<?>, JsonSchema> schemas = new LinkedHashMap<>();

    System.out.print(
            Tool.class.getSimpleName() + ": searching for Json schema definitions in " + Arrays.toString(opts));
    if (!suffixes.isEmpty()) {
        System.out.print(" with " + (matching ? "matching " : "") + "suffixes " + suffixes);
    }
    System.out.println();
    // start by assuming we have classes; if we do they will be nulled from the array
    Tool.createJsonSchemasFromClasses(opts, suffixes, matching, schemas);
    // now deal with the rest as if they were packages
    Tool.createJsonSchemasFromPackages(opts, suffixes, matching, schemas);
    if (schemas.isEmpty()) {
        System.out.println(
                Tool.class.getSimpleName() + ": no Json schemas found matching the specified criteria");
    } else {
        final String output = line.getOptionValue(Tool.output.getLongOpt(), "." // defaults to current directory
        );
        final File dir = new File(output);

        if (!dir.exists()) {
            dir.mkdirs();
        }
        org.apache.commons.lang3.Validate.isTrue(dir.isDirectory(), "not a directory: %s", dir);
        final ObjectMapper m = new ObjectMapper();

        m.enable(SerializationFeature.INDENT_OUTPUT);
        for (final Map.Entry<Class<?>, JsonSchema> e : schemas.entrySet()) {
            m.writeValue(new File(dir, e.getKey().getName() + ".json"), e.getValue());
            //System.out.println(s.getType() + " = " + m.writeValueAsString(s));
        }
    }
}

From source file:com.nec.congenio.ConfigCli.java

private Map<String, String> libPathDefs(CommandLine cline) {
    Properties props = cline.getOptionProperties("L");
    if (props != null) {
        return ConfigProperties.toAbsolutes(props, new File("."));
    }//  w w  w  . jav a2s .  com
    return Collections.emptyMap();
}

From source file:io.janusproject.Boot.java

private static void parseCommandLineForSystemProperties(CommandLine cmd) {
    if (cmd.hasOption('o')) {
        System.setProperty(JanusConfig.OFFLINE, Boolean.TRUE.toString());
    }/*w w  w  . jav  a 2  s .  c  o m*/
    if (cmd.hasOption('R')) {
        System.setProperty(JanusConfig.BOOT_DEFAULT_CONTEXT_ID_NAME, Boolean.FALSE.toString());
        System.setProperty(JanusConfig.RANDOM_DEFAULT_CONTEXT_ID_NAME, Boolean.TRUE.toString());
    } else if (cmd.hasOption('B')) {
        System.setProperty(JanusConfig.BOOT_DEFAULT_CONTEXT_ID_NAME, Boolean.TRUE.toString());
        System.setProperty(JanusConfig.RANDOM_DEFAULT_CONTEXT_ID_NAME, Boolean.FALSE.toString());
    } else if (cmd.hasOption('W')) {
        System.setProperty(JanusConfig.BOOT_DEFAULT_CONTEXT_ID_NAME, Boolean.FALSE.toString());
        System.setProperty(JanusConfig.RANDOM_DEFAULT_CONTEXT_ID_NAME, Boolean.FALSE.toString());
    }
    // Define the system properties, if not already done by the JRE.
    Properties props = cmd.getOptionProperties("D"); //$NON-NLS-1$
    if (props != null) {
        for (Entry<Object, Object> entry : props.entrySet()) {
            System.setProperty(entry.getKey().toString(), entry.getValue().toString());
        }
    }
}