Example usage for org.apache.commons.cli Option getOpt

List of usage examples for org.apache.commons.cli Option getOpt

Introduction

In this page you can find the example usage for org.apache.commons.cli Option getOpt.

Prototype

public String getOpt() 

Source Link

Document

Retrieve the name of this Option.

Usage

From source file:eu.edisonproject.utility.execute.Main.java

public static void main(String args[]) {
    Options options = new Options();
    Option operation = new Option("op", "operation", true,
            "type of operation to perform. " + "To move cached terms from org.mapdb.DB 'm'");
    operation.setRequired(true);//from ww  w  .  j  av a2  s . c  om
    options.addOption(operation);

    Option input = new Option("i", "input", true, "input file path");
    input.setRequired(true);
    options.addOption(input);

    String helpmasg = "Usage: \n";
    for (Object obj : options.getOptions()) {
        Option op = (Option) obj;
        helpmasg += op.getOpt() + ", " + op.getLongOpt() + "\t Required: " + op.isRequired() + "\t\t"
                + op.getDescription() + "\n";
    }

    try {
        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(options, args);

        switch (cmd.getOptionValue("operation")) {
        case "m":
            DBTools.portTermCache2Hbase(cmd.getOptionValue("input"));
            DBTools.portBabelNetCache2Hbase(cmd.getOptionValue("input"));
            break;
        default:
            System.out.println(helpmasg);
        }

    } catch (Exception ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, helpmasg, ex);
    }
}

From source file:com.ovea.tajin.server.ContainerRunner.java

public static void main(String... args) throws Exception {
    CommandLineParser parser = new GnuParser();
    CommandLine line = parser.parse(options, args);

    if (line.hasOption("help") || !line.hasOption(Properties.CONTAINER.getName())) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ContainerRunner.class.getSimpleName(), options);
        return;//from ww w  .j  a  v  a  2s. com
    }

    // Set default values
    // And override by system properties. This way, we can start ContainerRunner with specific options such as -DjettyConf=.. -DjettyEnv=...
    ContainerConfiguration settings = ContainerConfiguration.from(System.getProperties());
    // Then parse command line
    for (Option option : line.getOptions()) {
        settings.set(Properties.from(option.getOpt()), line.getOptionValue(option.getOpt()));
    }
    Container container = settings.buildContainer(line.getOptionValue(Properties.CONTAINER.getName()));
    container.start();
}

From source file:com.netflix.suro.SuroServer.java

public static void main(String[] args) throws IOException {
    final AtomicReference<Injector> injector = new AtomicReference<Injector>();

    try {/*from ww  w .  j a  v  a  2  s. c o m*/
        // Parse the command line
        Options options = createOptions();
        final CommandLine line = new BasicParser().parse(options, args);

        // Load the properties file
        final Properties properties = new Properties();
        if (line.hasOption('p')) {
            properties.load(new FileInputStream(line.getOptionValue('p')));
        }

        // Bind all command line options to the properties with prefix "SuroServer."
        for (Option opt : line.getOptions()) {
            String name = opt.getOpt();
            String value = line.getOptionValue(name);
            String propName = PROP_PREFIX + opt.getArgName();
            if (propName.equals(DynamicPropertyRoutingMapConfigurator.ROUTING_MAP_PROPERTY)) {
                properties.setProperty(DynamicPropertyRoutingMapConfigurator.ROUTING_MAP_PROPERTY,
                        FileUtils.readFileToString(new File(value)));
            } else if (propName.equals(DynamicPropertySinkConfigurator.SINK_PROPERTY)) {
                properties.setProperty(DynamicPropertySinkConfigurator.SINK_PROPERTY,
                        FileUtils.readFileToString(new File(value)));
            } else if (propName.equals(DynamicPropertyInputConfigurator.INPUT_CONFIG_PROPERTY)) {
                properties.setProperty(DynamicPropertyInputConfigurator.INPUT_CONFIG_PROPERTY,
                        FileUtils.readFileToString(new File(value)));
            } else {
                properties.setProperty(propName, value);
            }
        }

        create(injector, properties);
        injector.get().getInstance(LifecycleManager.class).start();

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    Closeables.close(injector.get().getInstance(LifecycleManager.class), true);
                } catch (IOException e) {
                    // do nothing because Closeables.close will swallow IOException
                }
            }
        });

        waitForShutdown(getControlPort(properties));
    } catch (Throwable e) {
        System.err.println("SuroServer startup failed: " + e.getMessage());
        System.exit(-1);
    } finally {
        Closeables.close(injector.get().getInstance(LifecycleManager.class), true);
    }
}

From source file:com.medsavant.mailer.Mail.java

public static void main(String[] args) throws IOException {
    CommandLineParser parser = new GnuParser();
    Options ops = getOptions();/* w w  w. ja va2s  .  co m*/
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(ops, args);

        // print help
        if (line.hasOption('h') || line.getOptions().length == 0) {
            printHelp();
            return;
        }

        // parse args

        String email = null;
        String emailPass = null;
        String mailingList = null;
        String subject = null;
        String htmlFile = null;

        for (Option o : line.getOptions()) {
            switch (o.getOpt().charAt(0)) {
            case 's':
                subject = o.getValue();
                break;
            case 'e':
                htmlFile = o.getValue();
                break;
            case 'u':
                email = o.getValue();
                break;
            case 'p':
                emailPass = o.getValue();
                break;
            case 'l':
                mailingList = o.getValue();
                break;
            }
        }

        setMailCredentials(email, emailPass, host, port);

        String text = readFileIntoString(new File(htmlFile));

        sendEmail(mailingList, subject, text);

    } catch (org.apache.commons.cli.ParseException exp) {

        printHelp();
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    }
}

From source file:glacierpipe.GlacierPipeMain.java

public static void main(String[] args) throws IOException, ParseException {
    CommandLineParser parser = new GnuParser();

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

    if (cmd.hasOption("help")) {
        try (PrintWriter writer = new PrintWriter(System.err)) {
            printHelp(writer);//from  w w  w.jav  a  2  s  .  c om
        }

        System.exit(0);
    } else if (cmd.hasOption("upload")) {

        // Turn the CommandLine into Properties
        Properties cliProperties = new Properties();
        for (Iterator<?> i = cmd.iterator(); i.hasNext();) {
            Option o = (Option) i.next();

            String opt = o.getLongOpt();
            opt = opt != null ? opt : o.getOpt();

            String value = o.getValue();
            value = value != null ? value : "";

            cliProperties.setProperty(opt, value);
        }

        // Build up a configuration
        ConfigBuilder configBuilder = new ConfigBuilder();

        // Archive name
        List<?> archiveList = cmd.getArgList();
        if (archiveList.size() > 1) {
            throw new ParseException("Too many arguments");
        } else if (archiveList.isEmpty()) {
            throw new ParseException("No archive name provided");
        }

        configBuilder.setArchive(archiveList.get(0).toString());

        // All other arguments on the command line
        configBuilder.setFromProperties(cliProperties);

        // Load any config from the properties file
        Properties fileProperties = new Properties();
        try (InputStream in = new FileInputStream(configBuilder.propertiesFile)) {
            fileProperties.load(in);
        } catch (IOException e) {
            System.err.printf("Warning: unable to read properties file %s; %s%n", configBuilder.propertiesFile,
                    e);
        }

        configBuilder.setFromProperties(fileProperties);

        // ...
        Config config = new Config(configBuilder);

        IOBuffer buffer = new MemoryIOBuffer(config.partSize);

        AmazonGlacierClient client = new AmazonGlacierClient(
                new BasicAWSCredentials(config.accessKey, config.secretKey));
        client.setEndpoint(config.endpoint);

        // Actual upload
        try (InputStream in = new BufferedInputStream(System.in, 4096);
                PrintWriter writer = new PrintWriter(System.err);
                ObservableProperties configMonitor = config.reloadProperties
                        ? new ObservableProperties(config.propertiesFile)
                        : null;
                ProxyingThrottlingStrategy throttlingStrategy = new ProxyingThrottlingStrategy(config);) {
            TerminalGlacierPipeObserver observer = new TerminalGlacierPipeObserver(writer);

            if (configMonitor != null) {
                configMonitor.registerObserver(throttlingStrategy);
            }

            GlacierPipe pipe = new GlacierPipe(buffer, observer, config.maxRetries, throttlingStrategy);
            pipe.pipe(client, config.vault, config.archive, in);
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }

        System.exit(0);
    } else {
        try (PrintWriter writer = new PrintWriter(System.err)) {
            writer.println("No action specified.");
            printHelp(writer);
        }

        System.exit(-1);
    }
}

From source file:asl.seedscan.DQAWeb.java

public static void main(String args[]) {
    db = new MetricDatabase("", "", "");
    findConsoleHandler();/*w  w w .  ja  v a  2 s.co m*/
    consoleHandler.setLevel(Level.ALL);
    Logger.getLogger("").setLevel(Level.CONFIG);

    // Default locations of config and schema files
    File configFile = new File("dqaweb-config.xml");
    File schemaFile = new File("schemas/DQAWebConfig.xsd");
    boolean parseConfig = true;
    boolean testMode = false;

    ArrayList<File> schemaFiles = new ArrayList<File>();
    schemaFiles.add(schemaFile);
    // ==== Command Line Parsing ====
    Options options = new Options();
    Option opConfigFile = new Option("c", "config-file", true,
            "The config file to use for seedscan. XML format according to SeedScanConfig.xsd.");
    Option opSchemaFile = new Option("s", "schema-file", true,
            "The schame file which should be used to verify the config file format. ");
    Option opTest = new Option("t", "test", false, "Run in test console mode rather than as a servlet.");

    OptionGroup ogConfig = new OptionGroup();
    ogConfig.addOption(opConfigFile);

    OptionGroup ogSchema = new OptionGroup();
    ogConfig.addOption(opSchemaFile);

    OptionGroup ogTest = new OptionGroup();
    ogTest.addOption(opTest);

    options.addOptionGroup(ogConfig);
    options.addOptionGroup(ogSchema);
    options.addOptionGroup(ogTest);

    PosixParser optParser = new PosixParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = optParser.parse(options, args, true);
    } catch (org.apache.commons.cli.ParseException e) {
        logger.severe("Error while parsing command-line arguments.");
        System.exit(1);
    }

    Option opt;
    Iterator iter = cmdLine.iterator();
    while (iter.hasNext()) {
        opt = (Option) iter.next();

        if (opt.getOpt().equals("c")) {
            configFile = new File(opt.getValue());
        } else if (opt.getOpt().equals("s")) {
            schemaFile = new File(opt.getValue());
        } else if (opt.getOpt().equals("t")) {
            testMode = true;
        }
    }
    String query = "";
    System.out.println("Entering Test Mode");
    System.out.println("Enter a query string to view results or type \"help\" for example query strings");
    InputStreamReader input = new InputStreamReader(System.in);
    BufferedReader reader = new BufferedReader(input);
    String result = "";

    while (testMode == true) {
        try {

            System.out.printf("Query: ");
            query = reader.readLine();
            if (query.equals("exit")) {
                testMode = false;
            } else if (query.equals("help")) {
                System.out.println("Need to add some help for people"); //TODO
            } else {
                result = processCommand(query);
            }
            System.out.println(result);
        } catch (IOException err) {
            System.err.println("Error reading line, in DQAWeb.java");
        }
    }
    System.err.printf("DONE.\n");
}

From source file:gpframework.RunExperiment.java

/**
 * Application's entry point./*  w  w  w  .j  av a 2  s.c  o m*/
 * 
 * @param args
 * @throws ParseException
 * @throws ParameterException 
 */
public static void main(String[] args) throws ParseException, ParameterException {
    // Failsafe parameters
    if (args.length == 0) {
        args = new String[] { "-f", "LasSortednessFunction", "-n", "5", "-ff", "JoinFactory", "-tf",
                "SortingElementFactory", "-pf", "SortingProgramFactory", "-s", "SMOGPSelection", "-a", "SMOGP",
                "-t", "50", "-e", "1000000000", "-mf", "SingleMutationFactory", "-d", "-bn", "other" };
    }

    // Create options
    Options options = new Options();
    setupOptions(options);

    // Read options from the command line
    CommandLineParser parser = new PosixParser();
    CommandLine cmd;

    // Print help if parameter requirements are not met
    try {
        cmd = parser.parse(options, args);
    }

    // If some parameters are missing, print help
    catch (MissingOptionException e) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java -jar GPFramework \n", options);
        System.out.println();
        System.out.println("Missing parameters: " + e.getMissingOptions());
        return;
    }

    // Re-initialize PRNG
    long seed = System.currentTimeMillis();
    Utils.random = new Random(seed);

    // Set the problem size
    int problemSize = Integer.parseInt(cmd.getOptionValue("n"));

    // Set debug mode and cluster mode
    Utils.debug = cmd.hasOption("d");
    RunExperiment.cluster = cmd.hasOption("c");

    // Initialize fitness function and some factories
    FitnessFunction fitnessFunction = fromName(cmd.getOptionValue("f"), problemSize);
    MutationFactory mutationFactory = fromName(cmd.getOptionValue("mf"));
    Selection selectionCriterion = fromName(cmd.getOptionValue("s"));
    FunctionFactory functionFactory = fromName(cmd.getOptionValue("ff"));
    TerminalFactory terminalFactory = fromName(cmd.getOptionValue("tf"), problemSize);
    ProgramFactory programFactory = fromName(cmd.getOptionValue("pf"), functionFactory, terminalFactory);

    // Initialize algorithm
    Algorithm algorithm = fromName(cmd.getOptionValue("a"), mutationFactory, selectionCriterion);
    algorithm.setParameter("evaluationsBudget", cmd.getOptionValue("e"));
    algorithm.setParameter("timeBudget", cmd.getOptionValue("t"));

    // Initialize problem
    Problem problem = new Problem(programFactory, fitnessFunction);
    Program solution = algorithm.solve(problem);

    Utils.debug("Population results: ");
    Utils.debug(algorithm.getPopulation().toString());
    Utils.debug(algorithm.getPopulation().parse());

    Map<String, Object> entry = new HashMap<String, Object>();

    // Copy algorithm setup
    for (Object o : options.getRequiredOptions()) {
        Option option = options.getOption(o.toString());
        entry.put(option.getLongOpt(), cmd.getOptionValue(option.getOpt()));
    }
    entry.put("seed", seed);

    // Copy results
    entry.put("bestProgram", solution.toString());
    entry.put("bestSolution", fitnessFunction.normalize(solution));

    // Copy all statistics
    entry.putAll(algorithm.getStatistics());

    Utils.debug("Maximum encountered population size: "
            + algorithm.getStatistics().get("maxPopulationSizeToCompleteFront"));
    Utils.debug("Maximum encountered tree size: "
            + algorithm.getStatistics().get("maxProgramComplexityToCompleteFront"));
    Utils.debug("Solution complexity: " + solution.complexity() + "/" + (2 * problemSize - 1));
}

From source file:com.basingwerk.utilisation.Utilisation.java

public static void main(final String[] args) {
    String dataFile = null;//from www .ja  va2s .  c  o m

    Options options = new Options();

    Option helpOption = new Option("h", "help", false, "print this help");
    Option serverURLOption = new Option("l", "logfile", true, "log file");

    options.addOption(helpOption);
    options.addOption(serverURLOption);

    CommandLineParser argsParser = new PosixParser();

    try {
        CommandLine commandLine = argsParser.parse(options, args);

        if (commandLine.hasOption(helpOption.getOpt())) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Usage grapher", options);
            System.exit(0);
        }

        dataFile = commandLine.getOptionValue(serverURLOption.getOpt());
        String[] otherArgs = commandLine.getArgs();

        if (dataFile == null || otherArgs.length > 1) {
            System.out.println("Please specify a logfile");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Usage grapher", options);
            System.exit(0);
        }

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
    }

    final UsagePlotter demo = new UsagePlotter("Usage", new File(dataFile));
    demo.pack();
    RefineryUtilities.centerFrameOnScreen(demo);
    demo.setVisible(true);
}

From source file:eu.edisonproject.training.execute.Main.java

public static void main(String args[]) {
    Options options = new Options();
    Option operation = new Option("op", "operation", true,
            "type of operation to perform. " + "For term extraction use 'x'.\n"
                    + "Example: -op x -i E-COCO/documentation/sampleTextFiles/databases.txt "
                    + "-o E-COCO/documentation/sampleTextFiles/databaseTerms.csv"
                    + "For word sense disambiguation use 'w'.\n"
                    + "Example: -op w -i E-COCO/documentation/sampleTextFiles/databaseTerms.csv "
                    + "-o E-COCO/documentation/sampleTextFiles/databse.avro\n"
                    + "For tf-idf vector extraction use 't'.\n" + "For running the apriori algorithm use 'a'");
    operation.setRequired(true);//w w w  .  j  av  a2s  . c  o m
    options.addOption(operation);

    Option input = new Option("i", "input", true, "input file path");
    input.setRequired(true);
    options.addOption(input);

    Option output = new Option("o", "output", true, "output file");
    output.setRequired(true);
    options.addOption(output);

    Option popertiesFile = new Option("p", "properties", true, "path for a properties file");
    popertiesFile.setRequired(false);
    options.addOption(popertiesFile);

    Option termsFile = new Option("t", "terms", true, "terms file");
    termsFile.setRequired(false);
    options.addOption(termsFile);

    String helpmasg = "Usage: \n";
    for (Object obj : options.getOptions()) {
        Option op = (Option) obj;
        helpmasg += op.getOpt() + ", " + op.getLongOpt() + "\t Required: " + op.isRequired() + "\t\t"
                + op.getDescription() + "\n";
    }

    try {
        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(options, args);

        String propPath = cmd.getOptionValue("properties");
        if (propPath == null) {
            prop = ConfigHelper
                    .getProperties(".." + File.separator + "etc" + File.separator + "configure.properties");
        } else {
            prop = ConfigHelper.getProperties(propPath);
        }
        //            ${user.home}

        switch (cmd.getOptionValue("operation")) {
        case "x":
            termExtraction(cmd.getOptionValue("input"), cmd.getOptionValue("output"));
            break;
        case "w":
            wsd(cmd.getOptionValue("input"), cmd.getOptionValue("output"));
            break;
        case "t":
            calculateTFIDF(cmd.getOptionValue("input"), cmd.getOptionValue("output"));
            break;
        //                case "tt":
        //                    calculateTermTFIDF(cmd.getOptionValue("input"), cmd.getOptionValue("terms"), cmd.getOptionValue("output"));
        //                    break;
        case "a":
            apriori(cmd.getOptionValue("input"), cmd.getOptionValue("output"));
            break;
        default:
            System.out.println(helpmasg);
        }

    } catch (Exception ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, helpmasg, ex);
    }
}

From source file:edu.mit.csail.sdg.alloy4.VizGUI.java

/**
 * @param args/*from  www  .ja  va  2 s .c om*/
 */
public static void main(String[] args) {
    // create the command line parser
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options optionsArg = new Options();
    Option helpOpt = new Option("?", "help", false, "print this message");
    Option inputFileOpt = new Option("f", "file", true, "the name of the xml file to show");
    inputFileOpt.setRequired(true);

    optionsArg.addOption(helpOpt);
    optionsArg.addOption(inputFileOpt);

    CommandLine line = null;
    try {
        // parse the command line arguments
        line = parser.parse(optionsArg, args);

        if (line.hasOption(helpOpt.getOpt())) {
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("vizgui", optionsArg);
            return;
        }

    } catch (ParseException exp) {
        System.err.println("Unexpected exception:" + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("vizgui", optionsArg);
        return;
    }

    String inputFile = null;
    if (line.hasOption(inputFileOpt.getOpt())) {
        inputFile = line.getOptionValue(inputFileOpt.getOpt());
        if (inputFile == null) {
            System.err.println("Invalid input file");
        }
    }

    new edu.mit.csail.sdg.alloy4viz.VizGUI(true, inputFile, null);

}