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:il.ac.tau.yoavram.pes.SimulationConfigurer.java

public SimulationConfigurer(String[] args, Date date) throws IOException {
    CommandLine cmdLine = PesCommandLineParser.parse(args);
    // TODO check stuff
    springXmlConfig = this.getClass().getClassLoader()
            .getResource(cmdLine.getOptionValue(PesCommandLineParser.OptCode.Xml.toString()));
    properties = new Properties();
    if (cmdLine.hasOption(PesCommandLineParser.OptCode.FileProperties.toString())) {
        String filename = cmdLine.getOptionValue(PesCommandLineParser.OptCode.FileProperties.toString());
        properties = loadPropertiesFromClasspath(properties, filename);
    }/*w  w w  .  ja va2  s .c  om*/
    if (cmdLine.hasOption(PesCommandLineParser.OptCode.Properties.toString())) {
        Properties cmdLineProps = cmdLine
                .getOptionProperties(PesCommandLineParser.OptCode.Properties.toString());
        properties.putAll(cmdLineProps);
        logger.info("Command line properties given: " + cmdLineProps.toString());
    }

    String log4jConfigFilename = null;
    if (cmdLine.hasOption(PesCommandLineParser.OptCode.Log.toString())) {
        log4jConfigFilename = cmdLine.getOptionValue(PesCommandLineParser.OptCode.Log.toString());
    } else {
        log4jConfigFilename = LOG4J_DEFAULT_CONFIG_FILE;
    }

    Properties log4jProps = loadPropertiesFromClasspath(log4jConfigFilename);

    if (!properties.containsKey(JOB_NAME_KEY)) {
        String fullpath = springXmlConfig.getFile();
        String[] parts = fullpath.split("/");
        String lastPart = parts[parts.length - 1];
        String filename = lastPart.replace(XML_EXTENSION, EMPTY_STRING);
        properties.setProperty(JOB_NAME_KEY, filename);
    }
    if (!properties.containsKey(TIME)) {
        properties.setProperty(TIME, TimeUtils.formatDate(date));
    }

    logFilename = properties.getProperty("log.dir") + File.separator + properties.getProperty(JOB_NAME_KEY)
            + File.separator + properties.getProperty(JOB_NAME_KEY) + '.' + properties.getProperty(TIME)
            + LOG_EXTENTION;
    log4jProps.setProperty("log4j.appender.FILE.File", logFilename);
    logger.info("Logging to file " + logFilename);
    PropertyConfigurator.configure(log4jProps);
    logger.info("Finished configuring simulation");
}

From source file:com.googlecode.icegem.cacheutils.replication.CheckReplicationTool.java

/**
 * Parses command-line arguments and sets the local variables
 * /*w  w  w .  j ava  2s. c o  m*/
 * @param commandLineArguments
 *            - the list of command-line arguments
 */
protected void parseCommandLineArguments(String[] commandLineArguments) {
    Options options = constructGnuOptions();

    if (commandLineArguments.length < 1) {
        printHelp(options);
    }

    CommandLineParser parser = new GnuParser();
    try {
        CommandLine line = parser.parse(options, commandLineArguments);

        if (line.hasOption(HELP_OPTION)) {
            printHelp(options);
        }

        if (line.hasOption(REGION_OPTION)) {
            regionName = line.getOptionValue(REGION_OPTION);
        }

        if (line.hasOption(TIMEOUT_OPTION)) {
            String timeoutString = line.getOptionValue(TIMEOUT_OPTION);
            timeout = Long.parseLong(timeoutString);
        }

        if (line.hasOption(CLUSTER_OPTION)) {
            clustersProperties = line.getOptionProperties(CLUSTER_OPTION);

            if (clustersProperties.keySet().size() < 2) {
                Utils.exitWithFailure("At least two clusters should be defined");
            }
        } else {
            Utils.exitWithFailure("No clusters defined");
        }

    } catch (Throwable t) {
        Utils.exitWithFailure("Throwable caught during the command-line arguments parsing", t);
    }
}

From source file:alluxio.cli.fs.command.MountCommand.java

@Override
public int run(CommandLine cl) throws AlluxioException, IOException {
    String[] args = cl.getArgs();
    if (args.length == 0) {
        Map<String, MountPointInfo> mountTable = mFileSystem.getMountTable();
        UfsCommand.printMountInfo(mountTable);
        return 0;
    }/* w  w w  . j a va 2 s.  co  m*/
    AlluxioURI alluxioPath = new AlluxioURI(args[0]);
    AlluxioURI ufsPath = new AlluxioURI(args[1]);
    MountOptions options = MountOptions.defaults();

    if (cl.hasOption(READONLY_OPTION.getLongOpt())) {
        options.setReadOnly(true);
    }
    if (cl.hasOption(SHARED_OPTION.getLongOpt())) {
        options.setShared(true);
    }
    if (cl.hasOption(OPTION_OPTION.getLongOpt())) {
        Properties properties = cl.getOptionProperties(OPTION_OPTION.getLongOpt());
        options.setProperties(Maps.fromProperties(properties));
    }
    mFileSystem.mount(alluxioPath, ufsPath, options);
    System.out.println("Mounted " + ufsPath + " at " + alluxioPath);
    return 0;
}

From source file:com.googlecode.icegem.cacheutils.regioncomparator.CompareTool.java

protected void parseCommandLineArguments(String[] commandLineArguments) {
    Options options = constructGnuOptions();
    if (commandLineArguments.length < 1) {
        printHelp(options);//from w w  w.  j a v a 2  s . co m
        Utils.exitWithSuccess();
    }
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine line = parser.parse(options, commandLineArguments);
        if (!line.hasOption("region") || line.hasOption("help")
                || !(line.hasOption("locators") || line.hasOption("servers"))) {
            printHelp(options);
            Utils.exitWithSuccess();
        }
        if (line.hasOption("packages"))
            scanPackagesOption = Arrays.asList(line.getOptionValue("packages").split(","));
        regionName = line.getOptionValue("region");
        if (line.hasOption("locators"))
            locatorsProperties = line.getOptionProperties("locators");
        if (line.hasOption("servers"))
            serversOption = line.getOptionValue("servers");

    } catch (ParseException exp) {
        System.err.println("Parsing options failed. " + exp.getMessage());
        printHelp(options);
        Utils.exitWithSuccess();
    }
}

From source file:io.github.retz.cli.Launcher.java

static Configuration parseConfiguration(String[] args) throws ParseException, IOException, URISyntaxException {
    assert args != null;
    Configuration result = new Configuration();

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(OPTIONS, args);

    result.configFile = cmd.getOptionValue(OPT_CONFIG.getOpt(), "/opt/retz-client/etc/retz.properties");
    LOG.info("Configuration file: {}", result.configFile);
    result.fileConfig = new FileConfiguration(result.configFile);

    result.remoteCommand = Optional.ofNullable(cmd.getOptionValue(OPT_YAESS_COMMAND.getOpt()));
    // TODO: validation to prevent command injections
    LOG.info("Remote command: `{}`", result.remoteCommand);

    result.appName = Optional.ofNullable(cmd.getOptionValue(OPT_APP_NAME.getOpt()));
    LOG.info("Application: {}", result.appName);

    String persistentFiles = cmd.getOptionValue(OPT_PERSISTENT_FILE_URIS.getOpt());
    if (persistentFiles == null) {
        result.persistentFileUris = new LinkedList<>();
    } else {/*from  w w  w.java 2 s . com*/
        result.persistentFileUris = Arrays.asList(persistentFiles.split(","));
    }
    LOG.info("Persistent file locations: {}", result.persistentFileUris);

    String files = cmd.getOptionValue(OPT_FILE_URIS.getOpt());
    if (files == null) {
        result.fileUris = new LinkedList<>(); // just an empty list
    } else {
        result.fileUris = asList(files.split(","));
    }
    LOG.info("File locations: {}", result.fileUris);

    result.jobEnv = cmd.getOptionProperties(OPT_JOB_ENV.getOpt());
    LOG.info("Environment variable of job ... {}", result.jobEnv);

    result.jobResultDir = Optional.ofNullable(cmd.getOptionValue(OPT_JOB_RESULTS.getOpt()));
    LOG.info("Job results are to be saved at {}", result.jobResultDir);

    // TODO: move default value to somewhere else as static value
    // TODO: write tests on Range.parseRange and Range#toString
    result.cpu = Range.parseRange(cmd.getOptionValue(OPT_CPU.getOpt(), "2-"));
    result.memMB = Range.parseRange(cmd.getOptionValue(OPT_MEM_MB.getOpt(), "512-"));
    result.gpu = Range.parseRange(cmd.getOptionValue(OPT_GPU.getOpt(), "0-0"));
    LOG.info("Range of CPU and Memory: {} {}MB ({} gpus)", result.cpu, result.memMB, result.gpu);

    String maybeDiskMBstring = cmd.getOptionValue(OPT_DISK_MB.getOpt());
    if (maybeDiskMBstring == null) {
        result.diskMB = Optional.empty();
    } else {
        result.diskMB = Optional.ofNullable(Integer.parseInt(maybeDiskMBstring));
        LOG.info("Disk reservation size: {}MB", result.diskMB.get());
    }

    result.trustPVFiles = cmd.hasOption(OPT_TRUST_PVFILES.getOpt());
    LOG.info("Check PV files: {}", result.trustPVFiles);

    String jobIdStr = cmd.getOptionValue(OPT_JOB_ID.getOpt());
    if (jobIdStr == null) {
        result.jobId = Optional.empty();
    } else {
        result.jobId = Optional.of(Integer.parseInt(jobIdStr));
    }

    return result;
}

From source file:com.globalsight.ling.tm3.tools.TM3Command.java

protected SessionFactory getSessionFactory(CommandLine command) {
    String username = null, password = null, connStr = null;
    // Order of operations:
    // - start with defaults
    // - load the file specified with -properties (if set), or the
    // default properties file.
    // - Look for command line options to override.
    if (command.hasOption(PROPERTIES)) {
        loadPropertiesFromFile(properties, command.getOptionValue(PROPERTIES), true);
    } else {/*from  w ww  . j a  v a2  s  . com*/
        loadDefaultProperties(properties);
    }
    // Override any file properties with things passed on the command line
    Properties overrideProps = command.getOptionProperties(PROPERTY);
    for (Map.Entry<Object, Object> e : overrideProps.entrySet()) {
        properties.setProperty((String) e.getKey(), (String) e.getValue());
    }

    username = properties.getProperty(TM3_USER_PROPERTY);
    password = properties.getProperty(TM3_PASSWORD_PROPERTY);
    connStr = properties.getProperty(TM3_CONNECTION_PROPERTY);
    if (username == null || password == null || connStr == null) {
        usage("Must specify " + TM3_USER_PROPERTY + ", " + TM3_PASSWORD_PROPERTY + ", and "
                + TM3_CONNECTION_PROPERTY + " with -Dprop=val or via properties file");
    }

    Properties hibernateProps = new Properties(properties);
    hibernateProps.put("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");
    hibernateProps.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
    hibernateProps.put("hibernate.connection.url", connStr);
    hibernateProps.put("hibernate.connection.username", username);
    hibernateProps.put("hibernate.connection.password", password);
    hibernateProps.put("hibernate.cglib.use_reflection_optimizer", "false"); // this
                                                                             // is
                                                                             // default
                                                                             // in
                                                                             // hibernate
                                                                             // 3.2
    hibernateProps.put("hibernate.show_sql", "false");
    hibernateProps.put("hibernate.format_sql", "false");
    hibernateProps.put("hibernate.connection.pool_size", "1");
    hibernateProps.put("hibernate.cache.provider_class", "org.hibernate.cache.HashtableCacheProvider");
    // A little sketchy. Due to some undocumented (?) Hibernate
    // behavior, it will pick up hibernate cfg properties from elsewhere
    // in the classpath, even though we've specified them by hand.
    // As a result, this may end up unintentionally running c3p0
    // connection pooling, which will release connections on commit.
    // This causes problems for multi-transaction commands (like
    // GlobalSight's migrate-tm), because it will kill the connection
    // in mid-operation. As a result, we force the release mode to
    // keep the connection open until we're done.
    hibernateProps.put("hibernate.connection.release_mode", "on_close");
    Configuration cfg = new Configuration().addProperties(hibernateProps);
    cfg = HibernateConfig.extendConfiguration(cfg);
    if (requiresDataFactory()) {
        cfg = getDataFactory().extendConfiguration(cfg);
    }

    return cfg.buildSessionFactory();
}

From source file:com.net2plan.cli.tools.CLIReport.java

@Override
public void executeFromCommandLine(String[] args) throws ParseException {
    CommandLineParser parser = new CommandLineParser();
    CommandLine cli = parser.parse(OPTIONS, args);

    File classFile = (File) cli.getParsedOptionValue("class-file");
    String className = (String) cli.getParsedOptionValue("class-name");

    File inputFile = (File) cli.getParsedOptionValue("input-file");
    NetPlan netPlan = new NetPlan(inputFile);

    File outputFile = (File) cli.getParsedOptionValue("output-file");

    IReport report = ClassLoaderUtils.getInstance(classFile, className, IReport.class);

    List<Triple<String, String, String>> defaultReportParameters = null;
    try {/*  www.  j a v  a 2 s .c  om*/
        defaultReportParameters = report.getParameters();
    } catch (UnsupportedOperationException ex) {
    }

    Map<String, String> reportParameters = CommandLineParser.getParameters(defaultReportParameters,
            cli.getOptionProperties("report-param"));
    Map<String, String> net2planParameters = Configuration.getNet2PlanOptions();

    System.out.println("Net2Plan parameters");
    System.out.println("-----------------------------");
    System.out.println(StringUtils.mapToString(net2planParameters, "=", String.format("%n")));
    System.out.println();
    System.out.println("Report parameters");
    System.out.println("-----------------------------");
    System.out.println(reportParameters.isEmpty() ? "None"
            : StringUtils.mapToString(reportParameters, "=", String.format("%n")));
    System.out.println();
    System.out.println("Executing report...");
    System.out.println();

    long init = System.nanoTime();
    String html = report.executeReport(netPlan, reportParameters, net2planParameters);
    long end = System.nanoTime();

    HTMLUtils.saveToFile(outputFile, html);

    System.out.println(String.format("%n%nReport finished successfully in %f seconds", (end - init) / 1e9));
}

From source file:in.hatimi.nosh.support.CmdLineManager.java

private boolean injectField(CommandLine cmdLine, Object target, Field field) {
    CmdLineOption clo = field.getAnnotation(CmdLineOption.class);
    if (clo == null) {
        return true;
    }//from ww  w  .  ja va  2s  .  c  o m

    String nameToUse = clo.name();
    if (StringUtils.isBlank(nameToUse)) {
        nameToUse = clo.longName();
    }

    if (clo.argCount() == 0) {
        if (cmdLine.hasOption(nameToUse)) {
            return injectBoolean(target, field, true);
        } else {
            return injectBoolean(target, field, false);
        }
    }
    if (clo.argCount() == 1) {
        String value = cmdLine.getOptionValue(nameToUse);
        if (value != null) {
            return injectString(target, field, value);
        }
    } else if (clo.valueSeparator() > 0) {
        Properties props = cmdLine.getOptionProperties(nameToUse);
        if (props != null) {
            return injectProperties(target, field, props);
        }
    } else if (clo.argCount() > 1) {
        String[] values = cmdLine.getOptionValues(nameToUse);
        if (values != null && values.length > 0) {
            return injectStringArray(target, field, values);
        }
    }
    return true;
}

From source file:com.net2plan.cli.tools.CLIOnlineSimulation.java

@Override
public final void executeFromCommandLine(String[] args) throws ParseException {
    CommandLineParser parser = new CommandLineParser();
    CommandLine cli = parser.parse(OPTIONS, args);
    Map<String, String> net2planParameters = Configuration.getNet2PlanOptions();

    /* Load event generator and event processor objects */
    File generatorClassFile = (File) cli.getParsedOptionValue("generator-class-file");
    String generatorClassName = (String) cli.getParsedOptionValue("generator-class-name");
    File provisioningClassFile = (File) cli.getParsedOptionValue("processor-class-file");
    String provisioningClassName = (String) cli.getParsedOptionValue("processor-class-name");

    IExternal aux_eventGenerator = ClassLoaderUtils.getInstance(generatorClassFile, generatorClassName,
            IEventGenerator.class);
    IExternal aux_eventProcessor = ClassLoaderUtils.getInstance(provisioningClassFile, provisioningClassName,
            IEventProcessor.class);

    /* Read simulation, event generator and event processor parameters */
    Properties customSimulationParameters = cli.getOptionProperties("sim-param");
    Properties customEventGeneratorParameters = cli.getOptionProperties("generator-param");
    Properties customEventProcessorParameters = cli.getOptionProperties("processor-param");

    /* Read the input netPlan file */
    File inputFile = (File) cli.getParsedOptionValue("input-file");
    File outputFile = (File) cli.getParsedOptionValue("output-file");

    /* Initialize and run simulation */
    NetPlan aux_netPlan = new NetPlan(inputFile);
    String html = runSimulation(new SimKernel(), aux_netPlan, aux_eventGenerator,
            customEventGeneratorParameters, aux_eventProcessor, customEventProcessorParameters,
            customSimulationParameters, net2planParameters).getSecond();
    HTMLUtils.saveToFile(outputFile, html);
}

From source file:com.net2plan.cli.tools.CLINetworkDesign.java

@Override
public void executeFromCommandLine(String[] args) throws ParseException {
    final CommandLineParser parser = new CommandLineParser();
    final CommandLine cli = parser.parse(OPTIONS, args);

    final File classFile = (File) cli.getParsedOptionValue("class-file");
    final String className = (String) cli.getParsedOptionValue("class-name");

    NetPlan netPlan;/*from  ww w.  j  a  v  a2 s.c om*/
    if (cli.hasOption("input-file")) {
        final File inputFile = (File) cli.getParsedOptionValue("input-file");
        netPlan = new NetPlan(inputFile);
    } else {
        netPlan = new NetPlan();
    }

    if (cli.hasOption("traffic-file")) {
        NetPlan demands = new NetPlan((File) cli.getParsedOptionValue("traffic-file"));

        NetworkLayer layer = (cli.hasOption("traffic-layer"))
                ? netPlan
                        .getNetworkLayerFromId(((Number) cli.getParsedOptionValue("traffic-layer")).longValue())
                : netPlan.getNetworkLayerDefault();

        netPlan.removeAllDemands(layer);
        for (Demand demand : demands.getDemands()) {
            netPlan.addDemand(demand.getIngressNode(), demand.getEgressNode(), demand.getOfferedTraffic(),
                    demand.getAttributes(), layer);
        }
        netPlan.removeAllMulticastDemands(layer);
        for (MulticastDemand demand : demands.getMulticastDemands()) {
            netPlan.addMulticastDemand(demand.getIngressNode(), demand.getEgressNodes(),
                    demand.getOfferedTraffic(), demand.getAttributes(), layer);
        }
    }

    File outputFile = (File) cli.getParsedOptionValue("output-file");

    IAlgorithm algorithm = ClassLoaderUtils.getInstance(classFile, className, IAlgorithm.class);
    List<Triple<String, String, String>> defaultAlgorithmParameters = null;
    try {
        defaultAlgorithmParameters = algorithm.getParameters();
    } catch (UnsupportedOperationException ex) {
    }

    Map<String, String> algorithmParameters = CommandLineParser.getParameters(defaultAlgorithmParameters,
            cli.getOptionProperties("alg-param"));
    Configuration.updateSolverLibraryNameParameter(algorithmParameters); // put default path to libraries if solverLibraryName is ""
    Map<String, String> net2planParameters = Configuration.getNet2PlanOptions();

    System.out.println("Net2Plan parameters");
    System.out.println("-----------------------------");
    System.out.println(StringUtils.mapToString(net2planParameters, "=", String.format("%n")));
    System.out.println();
    System.out.println("Algorithm parameters");
    System.out.println("-----------------------------");
    System.out.println(algorithmParameters.isEmpty() ? "None"
            : StringUtils.mapToString(algorithmParameters, "=", String.format("%n")));
    System.out.println();
    System.out.println("Executing algorithm...");
    System.out.println();

    long init = System.nanoTime();
    String out = algorithm.executeAlgorithm(netPlan, algorithmParameters, net2planParameters);
    netPlan.saveToFile(outputFile);
    long end = System.nanoTime();

    System.out.println(String.format("%n%nAlgorithm finished successfully in %f seconds%nOutput message: %s",
            (end - init) / 1e9, out));
}