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

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

Introduction

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

Prototype

public boolean hasOption(char opt) 

Source Link

Document

Query to see if an option has been set.

Usage

From source file:com.thoughtworks.xstream.benchmark.cache.CacheBenchmark.java

public static void main(String[] args) {
    int counter = 10000;
    Product product = null;//ww w .java  2  s  .c  om

    Options options = new Options();
    options.addOption("p", "product", true, "Class name of the product to use for benchmark");
    options.addOption("n", true, "Number of repetitions");

    Parser parser = new PosixParser();
    try {
        CommandLine commandLine = parser.parse(options, args);
        if (commandLine.hasOption('p')) {
            product = (Product) Class.forName(commandLine.getOptionValue('p')).newInstance();
        }
        if (commandLine.hasOption('n')) {
            counter = Integer.parseInt(commandLine.getOptionValue('n'));
        }
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    Harness harness = new Harness();
    // harness.addMetric(new SerializationSpeedMetric(1) {
    // public String toString() {
    // return "Initial run serialization";
    // }
    // });
    // harness.addMetric(new DeserializationSpeedMetric(1, false) {
    // public String toString() {
    // return "Initial run deserialization";
    // }
    // });
    harness.addMetric(new SerializationSpeedMetric(counter));
    harness.addMetric(new DeserializationSpeedMetric(counter, false));
    if (product == null) {
        harness.addProduct(new NoCache());
        harness.addProduct(new Cache122());
        harness.addProduct(new RealClassCache());
        harness.addProduct(new SerializedClassCache());
        harness.addProduct(new AliasedAttributeCache());
        harness.addProduct(new DefaultImplementationCache());
        harness.addProduct(new NoCache());
    } else {
        harness.addProduct(product);
    }
    harness.addTarget(new BasicTarget());
    harness.addTarget(new ExtendedTarget());
    harness.addTarget(new ReflectionTarget());
    harness.addTarget(new SerializableTarget());
    harness.run(new TextReporter(new PrintWriter(System.out, true)));
    System.out.println("Done.");
}

From source file:com.dumontierlab.pdb2rdf.cluster.ClusterServer.java

public static void main(String[] args) {

    Options options = createOptions();//ww  w . j a  v  a2 s . c  om
    CommandLineParser parser = createCliParser();

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

        if (!cmd.hasOption("dir")) {
            LOG.fatal("You need to specify the input directory");
            System.exit(1);
        }
        File inputDir = new File(cmd.getOptionValue("dir"));
        if (!inputDir.exists() || !inputDir.isDirectory()) {
            LOG.fatal("The specified input directory is not a valid directory");
            System.exit(1);
        }

        int port = DEFAULT_PORT;
        if (cmd.hasOption("port")) {
            try {
                port = Integer.parseInt(cmd.getOptionValue("port"));
            } catch (NumberFormatException e) {
                LOG.fatal("Invalid port number", e);
                System.exit(1);
            }
        }
        boolean gzip = cmd.hasOption("gzip");

        try {
            startServer(inputDir, gzip, port);
        } catch (Exception e) {
            LOG.fatal("Unable to start the server.", e);
            System.exit(1);
        }

    } catch (ParseException e) {
        LOG.fatal("Unable understand your command.");
        printUsage();
        System.exit(1);
    }

}

From source file:de.citec.csra.highlight.HighlightService.java

public static void main(String[] args)
        throws InitializeException, RSBException, InterruptedException, ParseException {

    Options opts = new Options();
    opts.addOption("scope", true, "RSB scope for highlight targets.\nDefault: '" + scope + "'");
    opts.addOption("server", true, "RSB server for configuration, e.g., tokens.\nDefault: '" + cfg + "'");
    opts.addOption("help", false, "Print this help and exit");

    String footer = null;//from w ww  .  ja  v a2s .c o m
    //      String footer = "\nThe following sub-scopes are registered automatically:\n"
    //            + "\n.../preset for color presets:\n" + Arrays.toString(ColorConfig.values())
    //            + "\n.../color for color values:\n" + "HSV (comma separated)"
    //            + "\n.../power for power states:\n" + Arrays.toString(PowerState.State.values())
    //            + "\n.../history for history commands:\n" + Arrays.toString(ColorHistory.values());

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(opts, args);
    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("csra-highlight-service [OPTION...]", "where OPTION includes:", opts, footer);
        System.exit(0);
    }

    if (System.getenv().containsKey(SCOPEVAR)) {
        scope = System.getenv(SCOPEVAR);
    }

    String s = cmd.getOptionValue("scope");
    if (s != null) {
        scope = s;
    }
    scope = scope.replaceAll("/$", "");

    String c = cmd.getOptionValue("cfg");
    if (c != null) {
        cfg = c;
    }
    cfg = cfg.replaceAll("/$", "");

    Defaults.loadDefaults();
    ExecutorService exec = Executors.newFixedThreadPool(2);

    exec.submit(() -> {
        try {
            ConfigServer cfgServer = new ConfigServer(cfg);
            cfgServer.execute();
        } catch (RSBException ex) {
            LOG.log(Level.SEVERE, "Config server failed", ex);
        }
    });

    exec.submit(() -> {
        try {
            TaskServer server = new TaskServer(scope, new HighlightTaskHandler());
            server.execute();
        } catch (RSBException | InterruptedException ex) {
            LOG.log(Level.SEVERE, "Task server failed", ex);
        }
    });

}

From source file:cd.what.DutchBot.Main.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException, IrcException, InterruptedException,
        ConfigurationException, InstantiationException, IllegalAccessException {
    String configfile = "irc.properties";
    DutchBot bot = null;//from   w  w w. j av  a 2s  . co m

    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("config").withArgName("configfile").hasArg()
            .withDescription("Load configuration from configfile, or use the default irc.cfg").create("c"));
    options.addOption(OptionBuilder.withLongOpt("server").withArgName("<url>").hasArg()
            .withDescription("Connect to this server").create("s"));
    options.addOption(OptionBuilder.withLongOpt("port").hasArg().withArgName("port")
            .withDescription("Connect to the server with this port").create("p"));
    options.addOption(OptionBuilder.withLongOpt("password").hasArg().withArgName("password")
            .withDescription("Connect to the server with this password").create("pw"));
    options.addOption(OptionBuilder.withLongOpt("nick").hasArg().withArgName("nickname")
            .withDescription("Connect to the server with this nickname").create("n"));
    options.addOption(OptionBuilder.withLongOpt("nspass").hasArg().withArgName("password")
            .withDescription("Sets the password for NickServ").create("ns"));
    options.addOption("h", "help", false, "Displays this menu");

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cli = parser.parse(options, args);
        if (cli.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("DutchBot", options);
            return;
        }
        // check for override config file
        if (cli.hasOption("c"))
            configfile = cli.getOptionValue("c");

        bot = new DutchBot(configfile);

        // Read the cli parameters
        if (cli.hasOption("pw"))
            bot.setServerPassword(cli.getOptionValue("pw"));
        if (cli.hasOption("s"))
            bot.setServerAddress(cli.getOptionValue("s"));
        if (cli.hasOption("p"))
            bot.setIrcPort(Integer.parseInt(cli.getOptionValue("p")));
        if (cli.hasOption("n"))
            bot.setBotName(cli.getOptionValue("n"));
        if (cli.hasOption("ns"))
            bot.setNickservPassword(cli.getOptionValue("ns"));

    } catch (ParseException e) {
        System.err.println("Error parsing command line vars " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("DutchBot", options);
        System.exit(1);
    }

    boolean result = bot.tryConnect();

    if (result)
        bot.logMessage("Connected");
    else {
        System.out.println(" Connecting failed :O");
        System.exit(1);
    }
}

From source file:edu.msu.cme.rdp.readseq.ToFasta.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("m", "mask", true, "Mask sequence name indicating columns to drop");
    String maskSeqid = null;//w  w  w .j a  v  a2 s  .  c o m

    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("mask")) {
            maskSeqid = line.getOptionValue("mask");
        }

        args = line.getArgs();
        if (args.length == 0) {
            throw new Exception("");
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp("USAGE: to-fasta <input-file>", options);
        System.err.println("ERROR: " + e.getMessage());
        System.exit(1);
        return;
    }

    SeqReader reader = null;

    FastaWriter out = new FastaWriter(System.out);
    Sequence seq;
    int totalSeqs = 0;
    long totalTime = System.currentTimeMillis();

    for (String fname : args) {
        if (fname.equals("-")) {
            reader = new SequenceReader(System.in);
        } else {
            File seqFile = new File(fname);

            if (maskSeqid == null) {
                reader = new SequenceReader(seqFile);
            } else {
                reader = new IndexedSeqReader(seqFile, maskSeqid);
            }
        }

        long startTime = System.currentTimeMillis();
        int thisFileTotalSeqs = 0;
        while ((seq = reader.readNextSequence()) != null) {
            out.writeSeq(seq.getSeqName().replace(" ", "_"), seq.getDesc(), seq.getSeqString());
            thisFileTotalSeqs++;
        }
        totalSeqs += thisFileTotalSeqs;
        System.err.println("Converted " + thisFileTotalSeqs + " (total sequences: " + totalSeqs
                + ") sequences from " + fname + " (" + reader.getFormat() + ") to fasta in "
                + (System.currentTimeMillis() - startTime) / 1000 + " s");
    }
    System.err.println("Converted " + totalSeqs + " to fasta in "
            + (System.currentTimeMillis() - totalTime) / 1000 + " s");

    out.close();
}

From source file:net.hedges.fandangled.commandline.GenericCli.java

public static void main(String[] args) {
    options = buildOptions();//from   w  ww  . j a v  a 2  s .  c  o  m

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(options, args);
        verbose = line.hasOption('v');
        if (line.hasOption('h')) {
            usage();
            System.exit(0);
        }
        String template = line.getOptionValue("templates");
        String input = line.getOptionValue("input");
        String output = line.getOptionValue("output");

        String prefix = line.getOptionValue("prefix", "");
        String extension = line.getOptionValue("extension", ".txt");

        File inputFile = new File(input);
        File outputDir = new File(output);
        File templateDir = new File(template);

        checkFilesAndDirectories(inputFile, outputDir, templateDir);

        GenericCodec codec = new GenericCodec();
        codec.setTemplatePath(templateDir.getAbsolutePath());
        codec.setExtension(extension);
        codec.setPrefix(prefix);

        Interface _interface = InterfaceBuilder.parse(inputFile);

        codec.encode(_interface, outputDir);

    } catch (ParseException e) {
        System.err.print(e.getMessage() + "\n");
        usage();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.blackducksoftware.tools.vuln_collector.VCRunner.java

public static void main(String[] args) throws Exception {
    System.out.println(TITLE);/* w  w w  .  ja  v  a 2s .  co  m*/
    CommandLineParser parser = new DefaultParser();

    options.addOption("h", "help", false, "show help.");

    Option projectNameOption = new Option("projectName", true, "Name of Project (optional)");
    projectNameOption.setRequired(false);
    options.addOption(projectNameOption);

    Option configFileOption = new Option("config", true, "Location of configuration file (required)");
    configFileOption.setRequired(true);
    options.addOption(configFileOption);

    try {

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

        if (cmd.hasOption("h"))
            help();

        String[] projectNameList = null;
        File configFile = null;

        if (cmd.hasOption(VCConstants.CL_PROJECT_NAME)) {
            String projectName = cmd.getOptionValue(VCConstants.CL_PROJECT_NAME);
            log.info("Project name: " + projectName);
            // Could be a single project or comma delim
            projectNameList = VCProcessor.getProjectList(projectName);
        }

        // Config File
        if (cmd.hasOption(VCConstants.CL_CONFIG)) {
            String configFilePath = cmd.getOptionValue(VCConstants.CL_CONFIG);
            log.info("Config file location: " + configFilePath);
            configFile = new File(configFilePath);
            if (!configFile.exists()) {
                log.error("Configuration file does not exist at location: " + configFile);
                System.exit(-1);
            }
        } else {
            log.error("Must specify configuration file!");
            help();
        }

        VCProcessor processor = new VCProcessor(configFile.toString(), projectNameList);
        processor.processReport();

    } catch (ParseException e) {
        log.error("Error parsing: " + e.getMessage());
        help();
    } catch (Exception e) {
        log.error("General error: " + e.getMessage());

    }

}

From source file:di.uniba.it.tee2.wiki.Wikidump2Text.java

/**
 * @param args the command line arguments
 *//*from  w  w w . j a  va  2s  . c  om*/
public static void main(String[] args) {
    try {
        CommandLine cmd = cmdParser.parse(options, args);
        if (cmd.hasOption("l") && cmd.hasOption("d") && cmd.hasOption("o")) {
            encoding = cmd.getOptionValue("e", "UTF-8");
            int counter = 0;
            try {
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                        new GZIPOutputStream(new FileOutputStream(cmd.getOptionValue("o"))), "UTF-8"));
                WikipediaDumpIterator it = new WikipediaDumpIterator(new File(cmd.getOptionValue("d")),
                        encoding);
                PageCleaner cleaner = PageCleanerWrapper.getInstance(cmd.getOptionValue("l"));
                while (it.hasNext()) {
                    WikiPage wikiPage = it.next();
                    ParsedPage parsedPage = wikiPage.getParsedPage();
                    if (parsedPage != null) {
                        String title = wikiPage.getTitle();
                        if (!title.matches(notValidTitle)) {
                            if (parsedPage.getText() != null) {
                                writer.append(cleaner.clean(parsedPage.getText()));
                                writer.newLine();
                                writer.newLine();
                                counter++;
                                if (counter % 10000 == 0) {
                                    System.out.println(counter);
                                    writer.flush();
                                }
                            }
                        }
                    }
                }
                writer.flush();
                writer.close();
            } catch (Exception ex) {
                Logger.getLogger(Wikidump2Text.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("Indexed pages: " + counter);
        } else {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("Wikipedia dump to text", options, true);
        }
    } catch (ParseException ex) {
        Logger.getLogger(Wikidump2Text.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.martinlamas.dicomserver.DicomServer.java

public static void main(String[] args) {
    int port = DEFAULT_PORT;

    String aeTitle = DEFAULT_AE_TITLE;
    File storageDirectory = new File(DEFAULT_STORAGE_DIRECTORY);

    try {//  w  w  w .  j a  va 2 s  .c  om
        CommandLine line = new DefaultParser().parse(getOptions(), args);

        if (line.hasOption("p"))
            port = Integer.valueOf(line.getOptionValue("p"));

        if (line.hasOption("d"))
            storageDirectory = new File(line.getOptionValue("d"));

        if (line.hasOption("t"))
            aeTitle = line.getOptionValue("t");

        List<DicomServerApplicationEntity> applicationEntities = new ArrayList<DicomServerApplicationEntity>();

        DicomServerApplicationEntity applicationEntity = new DicomServerApplicationEntity(aeTitle,
                storageDirectory);

        applicationEntities.add(applicationEntity);

        showBanner();

        IDicomStoreSCPServer server = new DicomStoreSCPServer(port, applicationEntities);
        server.start();
    } catch (ParseException e) {
        printUsage();
    } catch (Exception e) {
        logger.error("Unable to start DICOM server: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.osrdata.etltoolbox.fileloader.Main.java

/**
 * Main entry point into the application.
 * @param args command line argunemtns// ww  w .j  a  v a  2s  .  c o m
 */
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(new Option("s", "spec", true, "Source-to-target specification file"));
    options.addOption(new Option("d", "directory", true, "Source directory to load"));
    options.addOption(new Option("f", "file", true, "File to perform operation on"));
    options.addOption(new Option("r", "replace", false, "Replace previously loaded data"));
    options.addOption(new Option("t", "trace", true, "Trace records processed at specified interval"));

    CommandLineParser parser = new BasicParser();

    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("spec") && (line.hasOption("directory") || line.hasOption("file"))) {
            FileLoader loader = new FileLoader(line);

            loader.init();

            if (line.hasOption("file")) {
                loader.load(new File(line.getOptionValue("file")));
            } else if (line.hasOption("directory")) {
                File directory = new File(line.getOptionValue("directory"));

                if (directory.isDirectory()) {
                    File[] files = directory.listFiles();

                    for (File file : files) {
                        loader.load(file);
                    }
                } else {
                    log.fatal(directory.getAbsolutePath() + " does not appear to be a directory.");
                }
            }
        } else {
            usage();
        }
    } catch (ParseException e) {
        usage();
    } catch (IOException e) {
        e.printStackTrace();
    }
}