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

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

Introduction

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

Prototype

public Object getOptionObject(char opt) 

Source Link

Document

Return the Object type of this Option.

Usage

From source file:mx.unam.fesa.mss.MSSMain.java

/**
 * @param args//www .  j  a  v  a2s. c  om
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {

    //
    // managing command line options using commons-cli
    //

    Options options = new Options();

    // help option
    //
    options.addOption(
            OptionBuilder.withDescription("Prints this message.").withLongOpt("help").create(OPT_HELP));

    // port option
    //
    options.addOption(OptionBuilder.withDescription("The port in which the MineSweeperServer will listen to.")
            .hasArg().withType(new Integer(0)).withArgName("PORT").withLongOpt("port").create(OPT_PORT));

    // parsing options
    //
    int port = DEFAULT_PORT;
    try {
        // using GNU standard
        //
        CommandLine line = new GnuParser().parse(options, args);

        if (line.hasOption(OPT_HELP)) {
            new HelpFormatter().printHelp("mss [options]", options);
            return;
        }

        if (line.hasOption(OPT_PORT)) {
            try {
                port = (Integer) line.getOptionObject(OPT_PORT);
            } catch (Exception e) {
            }
        }
    } catch (ParseException e) {
        System.err.println("Could not parse command line options correctly: " + e.getMessage());
        return;
    }

    //
    // configuring logging services
    //

    try {
        LogManager.getLogManager()
                .readConfiguration(ClassLoader.getSystemResourceAsStream(DEFAULT_LOGGING_CONFIG_FILE));
    } catch (Exception e) {
        throw new Error("Could not load logging properties file", e);
    }

    //
    // setting up UDP server
    //      

    try {
        new MSServer(port);
    } catch (Exception e) {
        LoggerFactory.getLogger(MSSMain.class).error("Could not execute MineSweeper server: ", e);
    }
}

From source file:mx.unam.fesa.isoo.msp.MSPMain.java

/**
 * @param args//from ww w.j a va  2 s.  co m
 * @throws Exception
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {

    //
    // creating options
    //

    Options options = new Options();

    // help option
    //
    options.addOption(
            OptionBuilder.withDescription("Prints this message.").withLongOpt("help").create(OPT_HELP));

    // server option
    //
    options.addOption(OptionBuilder.withDescription("The server this MineSweeperPlayer will connect to.")
            .hasArg().withArgName("SERVER").withLongOpt("server").create(OPT_SERVER));

    // port option
    //
    options.addOption(OptionBuilder.withDescription("The port this MineSweeperPlayer will connect to.").hasArg()
            .withType(new Integer(0)).withArgName("PORT").withLongOpt("port").create(OPT_PORT));

    // parsing options
    //
    String hostname = DEFAULT_SERVER;
    int port = DEFAULT_PORT;
    try {
        // using GNU standard
        //
        CommandLine line = new GnuParser().parse(options, args);

        if (line.hasOption(OPT_HELP)) {
            new HelpFormatter().printHelp("msc [options]", options);
            return;
        }

        if (line.hasOption(OPT_PORT)) {
            try {
                port = (Integer) line.getOptionObject(OPT_PORT);
            } catch (Exception e) {
            }
        }

        if (line.hasOption(OPT_SERVER)) {
            hostname = line.getOptionValue(OPT_PORT);
        }
    } catch (ParseException e) {
        System.err.println("Could not parse command line options correctly: " + e.getMessage());
        return;
    }

    //
    // configuring logging services
    //

    try {
        LogManager.getLogManager()
                .readConfiguration(ClassLoader.getSystemResourceAsStream(DEFAULT_LOGGING_CONFIG_FILE));
    } catch (Exception e) {
        throw new Error("Could not load logging properties file.", e);
    }

    //
    // setting up Mine Sweeper client
    //

    try {
        new MSClient(hostname, port);
    } catch (Exception e) {
        System.err.println("Could not execute MineSweeper client: " + e.getMessage());
    }
}

From source file:br.edu.ufcg.lsd.oursim.ui.CLI.java

/**
 * Exemplo://from  w ww.  j  a  v a 2  s.  c  o m
 * 
 * <pre>
 *   java -jar oursim.jar -w resources/trace_filtrado_primeiros_1000_jobs.txt -m resources/hostinfo_sdsc.dat -synthetic_av -o oursim_trace.txt
 *   -w resources/trace_filtrado_primeiros_1000_jobs.txt -s persistent -nr 20 -md resources/hostinfo_sdsc.dat -av resources/disponibilidade.txt -o oursim_trace.txt
 *   -w resources/new_iosup_workload.txt -s persistent -pd resources/iosup_site_description.txt -wt iosup -nr 1 -synthetic_av -o oursim_trace.txt
 *   -w resources/new_workload.txt -s persistent -pd resources/marcus_site_description.txt -wt marcus -nr 20 -d -o oursim_trace.txt
 *   1 ms + 1 dia = 2678400 segundos
 * </pre>
 * 
 * @param args
 * @throws FileNotFoundException
 */
public static void main(String[] args) throws IOException {

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    List<Closeable> closeables = new ArrayList<Closeable>();

    CommandLine cmd = parseCommandLine(args, prepareOptions(), HELP, USAGE, EXECUTION_LINE);

    File outputFile = (File) cmd.getOptionObject(OUTPUT);
    PrintOutput printOutput = new PrintOutput(outputFile, false);
    JobEventDispatcher.getInstance().addListener(printOutput);
    closeables.add(printOutput);
    if (cmd.hasOption(EXTRACT_REMOTE_WORKLOAD)) {
        File remoteWorkloadFile = (File) cmd.getOptionObject(EXTRACT_REMOTE_WORKLOAD);
        Output remoteWorkloadExtractor = new RemoteTasksExtractorOutput(remoteWorkloadFile);
        closeables.add(remoteWorkloadExtractor);
        JobEventDispatcher.getInstance().addListener(remoteWorkloadExtractor);
    }
    Grid grid = prepareGrid(cmd);

    ComputingElementEventCounter computingElementEventCounter = prepareOutputAccounting(cmd,
            cmd.hasOption(VERBOSE));

    Input<? extends AvailabilityRecord> availability = defineAvailability(cmd, grid.getMapOfPeers());

    prepareOptionalOutputFiles(cmd, grid, (SyntheticAvailabilityCharacterizationAbstract) availability,
            closeables);

    long timeOfFirstSubmission = cmd.getOptionValue(WORKLOAD_TYPE).equals("gwa")
            ? GWAFormat.extractSubmissionTimeFromFirstJob(cmd.getOptionValue(WORKLOAD))
            : 0;
    Workload workload = defineWorkloadType(cmd, cmd.getOptionValue(WORKLOAD), grid.getMapOfPeers(),
            timeOfFirstSubmission);

    JobSchedulerPolicy jobScheduler = defineScheduler(cmd, grid.getListOfPeers());

    OurSim oursim = new OurSim(EventQueue.getInstance(), grid, jobScheduler, workload, availability);

    oursim.setActiveEntity(new ActiveEntityImp());

    if (cmd.hasOption(HALT_SIMULATION)) {
        oursim.addHaltEvent(((Number) cmd.getOptionObject(HALT_SIMULATION)).longValue());
    }

    oursim.start();

    for (Closeable c : closeables) {
        c.close();
    }

    EventQueue.getInstance().clear();

    // adiciona mtricas-resumo ao fim do arquivo
    FileWriter fw = new FileWriter(cmd.getOptionValue(OUTPUT), true);
    closeables.add(fw);
    stopWatch.stop();
    fw.write("# Simulation                  duration:" + stopWatch + ".\n");

    double utilization = grid.getUtilization();
    double realUtilization = grid.getTrueUtilization();

    int numberOfResourcesByPeer = Integer.parseInt(cmd.getOptionValue(NUM_RESOURCES_BY_PEER, "0"));
    fw.write(formatSummaryStatistics(computingElementEventCounter, "NA", "NA", false, grid.getPeers().size(),
            numberOfResourcesByPeer, utilization, realUtilization, stopWatch.getTime()) + "\n");
    fw.close();

    System.out.println(
            getSummaryStatistics(computingElementEventCounter, "NA", "NA", false, grid.getPeers().size(),
                    numberOfResourcesByPeer, utilization, realUtilization, stopWatch.getTime()));

}

From source file:com.flaptor.hounder.indexer.RmiIndexerStub.java

public static void main(String[] args) {

    // create the parser
    CommandLineParser parser = new PosixParser();
    CommandLine line = null;
    Options options = getOptions();/*from  www.j  a  v a2  s .  c  om*/
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("RmiIndexerStub -h <hostName> -p <basePort> [options] ", options);
        System.exit(1);
    }

    boolean doOptimize = line.hasOption("optimize");
    boolean doCheckpoint = line.hasOption("checkpoint");
    boolean doStop = line.hasOption("stop");
    Integer port = ((Long) line.getOptionObject("port")).intValue();
    String host = line.getOptionValue("host");

    try {
        RmiIndexerStub stub = new RmiIndexerStub(port, host);

        if (line.hasOption("deleteUrl")) {
            String url = line.getOptionValue("deleteUrl");
            Document dom = generateDeleteDocument(url);
            indexOrFail(stub, dom, "Could not delete " + url);
            System.out.println("delete " + url + " command accepted by indexer");
        }

        if (line.hasOption("deleteFile")) {

            BufferedReader reader = new BufferedReader(new FileReader(line.getOptionValue("deleteFile")));
            while (reader.ready()) {
                String url = reader.readLine();
                if (url.length() > 0 && url.charAt(0) != '#') { // ignore empty lines and comments
                    Document dom = generateDeleteDocument(url);
                    indexOrFail(stub, dom, "Could not delete " + url);
                    System.out.println("delete " + url + " command accepted by indexer");
                }
            }
            reader.close();
        }

        if (doOptimize) {
            Document dom = generateCommandDocument("optimize");
            indexOrFail(stub, dom, "Could not send optimize command.");
            System.out.println("optimize command accepted by indexer");
        }

        if (doCheckpoint) {
            Document dom = generateCommandDocument("checkpoint");
            indexOrFail(stub, dom, "Could not send checkpoint command.");
            System.out.println("checkpoint command accepted by indexer");

        }
        if (doStop) {
            Document dom = generateCommandDocument("close");
            indexOrFail(stub, dom, "Could not send stop command.");
            System.out.println("stop command accepted by indexer");
        }
    } catch (Exception e) {
        System.err.println("An error occurred: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.github.trohovsky.jira.analyzer.Main.java

public static void main(String[] args) throws Exception {

    final Options options = new Options();
    options.addOption("u", true, "username");
    options.addOption("p", true, "password (optional, if not provided, the password is prompted)");
    options.addOption("h", false, "show this help");
    options.addOption("s", true,
            "use the strategy for querying and output, the strategy can be either 'issues_toatal' (default) or"
                    + " 'per_month'");
    options.addOption("d", true, "CSV delimiter");

    // parsing of the command line arguments
    final CommandLineParser parser = new DefaultParser();
    CommandLine cmdLine = null;
    try {// w w w .  jav a2 s .  c om
        cmdLine = parser.parse(options, args);
        if (cmdLine.hasOption('h') || cmdLine.getArgs().length == 0) {
            final HelpFormatter formatter = new HelpFormatter();
            formatter.setOptionComparator(null);
            formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, null);
            return;
        }
        if (cmdLine.getArgs().length != 3) {
            throw new ParseException("You should specify exactly three arguments JIRA_SERVER JQL_QUERY_TEMPLATE"
                    + " PATH_TO_PARAMETER_FILE");
        }
    } catch (ParseException e) {
        System.err.println("Error parsing command line: " + e.getMessage());
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, null);
        return;
    }
    final String csvDelimiter = (String) (cmdLine.getOptionValue('d') != null ? cmdLine.getOptionObject('d')
            : CSV_DELIMITER);

    final URI jiraServerUri = URI.create(cmdLine.getArgs()[0]);
    final String jqlQueryTemplate = cmdLine.getArgs()[1];
    final List<List<String>> queryParametersData = readCSVFile(cmdLine.getArgs()[2], csvDelimiter);
    final String username = cmdLine.getOptionValue("u");
    String password = cmdLine.getOptionValue("p");
    final String strategy = cmdLine.getOptionValue("s");

    try {
        // initialization of the REST client
        final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
        if (username != null) {
            if (password == null) {
                final Console console = System.console();
                final char[] passwordCharacters = console.readPassword("Password: ");
                password = new String(passwordCharacters);
            }
            restClient = factory.createWithBasicHttpAuthentication(jiraServerUri, username, password);
        } else {
            restClient = factory.create(jiraServerUri, new AnonymousAuthenticationHandler());
        }
        final SearchRestClient searchRestClient = restClient.getSearchClient();

        // choosing of an analyzer strategy
        AnalyzerStrategy analyzer = null;
        if (strategy != null) {
            switch (strategy) {
            case "issues_total":
                analyzer = new IssuesTotalStrategy(searchRestClient);
                break;
            case "issues_per_month":
                analyzer = new IssuesPerMonthStrategy(searchRestClient);
                break;
            default:
                System.err.println("The strategy does not exist");
                return;
            }
        } else {
            analyzer = new IssuesTotalStrategy(searchRestClient);
        }

        // analyzing
        for (List<String> queryParameters : queryParametersData) {
            analyzer.analyze(jqlQueryTemplate, queryParameters);
        }
    } finally {
        // destroy the REST client, otherwise it stucks
        restClient.close();
    }
}

From source file:br.edu.ufcg.lsd.oursim.ui.CLI.java

private static Grid prepareGrid(CommandLine cmd) throws FileNotFoundException {
    Grid grid = null;//from   w  w w . j av a 2s.c  om
    ResourceSharingPolicy sharingPolicy = cmd.hasOption(NOF) ? NoFSharingPolicy.getInstance()
            : FifoSharingPolicy.getInstance();
    File peerDescriptionFile = (File) cmd.getOptionObject(PEERS_DESCRIPTION);
    if (cmd.hasOption(MACHINES_DESCRIPTION)) {
        File machinesDescriptionFile = (File) cmd.getOptionObject(MACHINES_DESCRIPTION);
        grid = SystemConfigurationCommandParser.readPeersDescription(peerDescriptionFile,
                machinesDescriptionFile, sharingPolicy);
    } else {
        int numberOfResourcesByPeer = Integer.parseInt(cmd.getOptionValue(NUM_RESOURCES_BY_PEER, "0"));
        grid = SystemConfigurationCommandParser.readPeersDescription(peerDescriptionFile,
                numberOfResourcesByPeer, sharingPolicy);
    }
    return grid;
}

From source file:br.edu.ufcg.lsd.oursim.ui.CLI.java

private static void prepareOptionalOutputFiles(CommandLine cmd, Grid grid,
        SyntheticAvailabilityCharacterizationAbstract availability, List<Closeable> closeables)
        throws IOException {
    if (cmd.hasOption(UTILIZATION)) {
        BufferedWriter bw = createBufferedWriter((File) cmd.getOptionObject(UTILIZATION));
        grid.setUtilizationBuffer(bw);//  w  ww.  j av  a2  s  .  c o m
        closeables.add(bw);
    }

    if (cmd.hasOption(WORKER_EVENTS)) {
        BufferedWriter bw2 = createBufferedWriter((File) cmd.getOptionObject(WORKER_EVENTS));
        availability.setBuffer(bw2);
        closeables.add(bw2);
    }

    if (cmd.hasOption(TASK_EVENTS)) {
        TaskPrintOutput taskOutput = new TaskPrintOutput((File) cmd.getOptionObject(TASK_EVENTS));
        TaskEventDispatcher.getInstance().addListener(taskOutput);
        closeables.add(taskOutput);
    }
}

From source file:br.edu.ufcg.lsd.oursim.ui.CLI.java

private static Input<AvailabilityRecord> defineAvailability(CommandLine cmd, Map<String, Peer> peersMap)
        throws FileNotFoundException {
    Input<AvailabilityRecord> availability = null;
    if (cmd.hasOption(DEDICATED_RESOURCES)) {
        availability = new DedicatedResourcesAvailabilityCharacterization(peersMap.values());
    } else if (cmd.hasOption(AVAILABILITY)) {
        long startingTime = AvailabilityTraceFormat
                .extractTimeFromFirstAvailabilityRecord(cmd.getOptionValue(AVAILABILITY), true);
        availability = new AvailabilityCharacterization(cmd.getOptionValue(AVAILABILITY), startingTime, true);
    } else if (cmd.hasOption(SYNTHETIC_AVAILABILITY)) {
        //         long availabilityThreshold = ((Number) cmd.getOptionObject(SYNTHETIC_AVAILABILITY)).longValue();
        //         String avType = cmd.getOptionValues(SYNTHETIC_AVAILABILITY).length == 2 ? cmd.getOptionValues(SYNTHETIC_AVAILABILITY)[1] : "";
        long availabilityThreshold = cmd.hasOption(SYNTHETIC_AVAILABILITY_DURATION)
                ? ((Number) cmd.getOptionObject(SYNTHETIC_AVAILABILITY_DURATION)).longValue()
                : Long.MAX_VALUE;
        String avType = (String) cmd.getOptionObject(SYNTHETIC_AVAILABILITY);
        if (avType.equals("mutka")) {
            availability = new MarkovModelAvailabilityCharacterization(peersMap, availabilityThreshold, 0);
        } else if (avType.equals("ourgrid")) {
            availability = new OurGridAvailabilityCharacterization(peersMap, availabilityThreshold, 0);
        }/*from w  w  w.  j  a va 2s  .  co m*/
    }

    if (availability == null) {
        showMessageAndExit("Combinao de parmetros de availability invlida.");
    }

    return availability;
}

From source file:de.uni_rostock.goodod.tools.Configuration.java

private HierarchicalConfiguration getConfigMap(String args[]) {

    CombinedConfiguration cfg = new CombinedConfiguration();
    HierarchicalConfiguration envCfg = new CombinedConfiguration();
    String repoRoot = System.getenv("GOODOD_REPO_ROOT");
    boolean helpMode = false;

    envCfg.addProperty("repositoryRoot", repoRoot);
    if (null == args) {
        return cfg;
    }//from w  w  w  .  j  a  v  a2 s .  c om
    GnuParser cmdLineParser = new GnuParser();
    CommandLine cmdLine = null;
    try {
        // parse the command line arguments
        cmdLine = cmdLineParser.parse(options, args);
    } catch (ParseException exception) {
        logger.fatal("Could not validate command-line.", exception);
        System.exit(1);
    }

    if (cmdLine.hasOption('c')) {
        envCfg.addProperty("configFile", cmdLine.getOptionValue('c'));
    }
    if (cmdLine.hasOption('t')) {
        envCfg.addProperty("threadCount", cmdLine.getOptionObject('t'));
    }

    if (cmdLine.hasOption('s')) {
        envCfg.addProperty("similarity", cmdLine.getOptionValue('s'));
    }
    if (cmdLine.hasOption('h')) {
        envCfg.addProperty("helpMode", true);
        helpMode = true;
    }
    if (cmdLine.hasOption('d')) {
        envCfg.addProperty("debug", true);
    }
    if (cmdLine.hasOption('1')) {
        envCfg.addProperty("one-way", true);
    }
    //Fetch the remaining arguments, but alas, commons-cli is not generics aware
    @SuppressWarnings("unchecked")
    List<String> argList = cmdLine.getArgList();
    HierarchicalConfiguration testConfig = null;
    try {
        if (argList.isEmpty() && (false == helpMode)) {
            logger.fatal("No test specification provided.");
            System.exit(1);
        } else if (1 == argList.size()) {
            File testFile = new File(argList.get(0));
            testConfig = readTestConfig(testFile);
            assert (null != testConfig);
            envCfg.addProperty("testFile", testFile.toString());

        } else if (false == helpMode) {
            /*
             *  For > 1 file, we assume that both are ontologies and we
             *  construct ourselves a test case configuration for them.
             */
            testConfig = new HierarchicalConfiguration();
            String ontologyA = argList.get(0);
            String ontologyB = argList.get(1);
            testConfig.addProperty("testName", "Comparison of " + ontologyA + " and " + ontologyB);
            testConfig.addProperty("notInRepository", true);
            Node studentOntologies = new Node("studentOntologies");
            Node groupA = new Node("groupA", Collections.singletonList(ontologyA));
            Node groupB = new Node("groupB", Collections.singletonList(ontologyB));
            studentOntologies.addChild(groupA);
            studentOntologies.addChild(groupB);
            testConfig.getRoot().addChild(studentOntologies);
            if (2 < argList.size()) {
                logger.warn("Ignoring extra arguments to comparison between individual ontologies.");
            }
            envCfg.addProperty("testFile", "unknown.plist");
        }
    } catch (Throwable t) {
        logger.fatal("Could not load test configuration.", t);
        System.exit(1);
    }
    cfg.addConfiguration(envCfg, "environment");
    if (false == helpMode) {
        cfg.addConfiguration(testConfig, "TestSubTree", "testDescription");
    }
    return cfg;
}

From source file:org.squale.squalix.core.Squalix.java

/**
 * Rcupre les paramtres de la ligne de commande
 * /*from   www . ja  v a2  s.  c o  m*/
 * @param pArgs liste des paramtres.
 * @throws ParseException
 * @roseuid 42CE4F340204
 * @throws ParseException si la liste des arguments est mal interprte
 */
private static void getParameters(final String[] pArgs) throws ParseException {
    CommandLine cmd = parser.parse(optionsDemarage, pArgs, false);

    mSite = (String) cmd.getOptionObject(Messages.getString("main.site_option"));

    if (cmd.hasOption(Messages.getString("main.configFile_option"))) {
        mConfigFile = (String) cmd.getOptionObject(Messages.getString("main.configFile_option"));
    }

    if (cmd.hasOption(Messages.getString("main.configCronExpression_option"))) {
        mCron = (String) cmd.getOptionObject(Messages.getString("main.configCronExpression_option"));
        if (mCron == null) {
            mCron = "";
        }
        mQuartzActive = true;
    }
    if (cmd.hasOption(Messages.getString("main.configCron_option"))) {
        mCron = "";
        mQuartzActive = true;
    }

}