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:eu.scape_project.archiventory.Archiventory.java

/**
 * Main entry point.// w  w  w .  j  av  a  2s  .c  o m
 *
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();
    // Command line interface
    config = new CliConfig();
    CommandLineParser cmdParser = new PosixParser();
    GenericOptionsParser gop = new GenericOptionsParser(conf, args);
    CommandLine cmd = cmdParser.parse(Options.OPTIONS, gop.getRemainingArgs());
    if ((args.length == 0) || (cmd.hasOption(Options.HELP_OPT))) {
        Options.exit("Usage", 0);
    } else {
        Options.initOptions(cmd, config);
    }
    // Trying to load spring configuration from local file system (same
    // directory where the application is executed). If the spring 
    // configuration is not given as a parameter, it is loaded as a 
    // resource from the class path. 
    if (config.getSpringConfig() != null && (new File(config.getSpringConfig()).exists())) {
        ctx = new FileSystemXmlApplicationContext("file://" + config.getSpringConfig());
    } else {
        ctx = new ClassPathXmlApplicationContext(SPRING_CONFIG_RESOURCE_PATH);
    }
    if (config.isMapReduceJob()) {
        startHadoopJob(conf);
    } else {
        startApplication();
    }
}

From source file:com.genentech.chemistry.openEye.apps.SDFRingSystemExtractor.java

/**
 * @param args/*  ww  w .  j  a  v  a 2  s  .com*/
 */
public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true, "input file oe-supported");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported");
    opt.setRequired(false);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    SDFRingSystemExtractor extractor = new SDFRingSystemExtractor(outFile);
    extractor.run(inFile);
    extractor.close();
}

From source file:javadepchecker.Main.java

/**
 * @param args the command line arguments
 */// w  w w  .  j  ava 2 s  .c  o  m
public static void main(String[] args) throws IOException {
    int exit = 0;
    try {
        CommandLineParser parser = new PosixParser();
        Options options = new Options();
        options.addOption("h", "help", false, "print help");
        options.addOption("i", "image", true, "image directory");
        options.addOption("v", "verbose", false, "print verbose output");
        CommandLine line = parser.parse(options, args);
        String[] files = line.getArgs();
        if (line.hasOption("h") || files.length == 0) {
            HelpFormatter h = new HelpFormatter();
            h.printHelp("java-dep-check [-i <image] <package.env>+", options);
        } else {
            image = line.getOptionValue("i", "");

            for (String arg : files) {
                if (line.hasOption('v')) {
                    System.out.println("Checking " + arg);
                }
                if (!checkPkg(new File(arg))) {
                    exit = 1;
                }
            }
        }
    } catch (ParseException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.exit(exit);
}

From source file:com.bc.fiduceo.post.PostProcessingToolMain.java

public static void main(String[] args) throws ParseException {
    final CommandLineParser parser = new PosixParser();
    final CommandLine commandLine;
    try {//from   www  .j  av  a  2s  .  c  o  m
        commandLine = parser.parse(PostProcessingTool.getOptions(), args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.err.println();
        PostProcessingTool.printUsageTo(System.err);
        return;
    }
    if (commandLine.hasOption("h") || commandLine.hasOption("--help")) {
        PostProcessingTool.printUsageTo(System.out);
        return;
    }

    try {
        final PostProcessingContext context = PostProcessingTool.initializeContext(commandLine);
        final PostProcessingTool tool = new PostProcessingTool(context);
        tool.runPostProcessing();
    } catch (Throwable e) {
        FiduceoLogger.getLogger().severe(e.getMessage());
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:com.genentech.chemistry.openEye.apps.SDFMCSSSphereExclusion.java

public static void main(String... args) throws IOException {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {// w w w.  j  a v  a  2s  .com
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp();
    }
    args = cmd.getArgs();

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    // the only reason not to match centroids in reverse order id if
    // a non-centroid is to be assigned to multiple centroids
    boolean printSphereMatchCount = cmd.hasOption("printSphereMatchCount");
    boolean reverseMatch = !cmd.hasOption("checkSpheresInOrder") && !printSphereMatchCount;
    boolean printAll = cmd.hasOption("printAll") || printSphereMatchCount;
    double radius = Double.parseDouble(cmd.getOptionValue("radius"));
    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String refFile = cmd.getOptionValue("ref");

    SimComparatorFactory<OEMolBase, OEMolBase, SimComparator<OEMolBase>> compFact;
    compFact = getComparatorFactory(cmd);

    SphereExclusion<OEMolBase, SimComparator<OEMolBase>> alg = new SphereExclusion<OEMolBase, SimComparator<OEMolBase>>(
            compFact, refFile, outFile, radius, reverseMatch, printSphereMatchCount, printAll);
    alg.run(inFile);
    alg.close();
}

From source file:edu.msu.cme.rdp.alignment.pairwise.PairwiseKNN.java

public static void main(String[] args) throws Exception {
    File queryFile;/*  w ww  .j a v a 2s  .  c o  m*/
    File refFile;
    AlignmentMode mode = AlignmentMode.glocal;
    int k = 1;
    int wordSize = 0;
    int prefilter = 10; //  The top p closest protein targets
    PrintStream out = new PrintStream(System.out);

    Options options = new Options();
    options.addOption("m", "mode", true,
            "Alignment mode {global, glocal, local, overlap, overlap_trimmed} (default= glocal)");
    options.addOption("k", true, "K-nearest neighbors to return. (default = 1)");
    options.addOption("o", "out", true, "Redirect output to file instead of stdout");
    options.addOption("p", "prefilter", true,
            "The top p closest targets from kmer prefilter step. Set p=0 to disable the prefilter step. (default = 10) ");
    options.addOption("w", "word-size", true,
            "The word size used to find closest targets during prefilter. (default "
                    + ProteinWordGenerator.WORDSIZE + " for protein, " + GoodWordIterator.DEFAULT_WORDSIZE
                    + " for nucleotide)");

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

        if (line.hasOption("mode")) {
            mode = AlignmentMode.valueOf(line.getOptionValue("mode"));
        }

        if (line.hasOption('k')) {
            k = Integer.valueOf(line.getOptionValue('k'));
            if (k < 1) {
                throw new Exception("k must be at least 1");
            }
        }

        if (line.hasOption("word-size")) {
            wordSize = Integer.parseInt(line.getOptionValue("word-size"));
            if (wordSize < 3) {
                throw new Exception("Word size must be at least 3");
            }
        }
        if (line.hasOption("prefilter")) {
            prefilter = Integer.parseInt(line.getOptionValue("prefilter"));
            // prefilter == 0 means no prefilter
            if (prefilter > 0 && prefilter < k) {
                throw new Exception("prefilter must be at least as big as k " + k);
            }
        }

        if (line.hasOption("out")) {
            out = new PrintStream(line.getOptionValue("out"));
        }

        args = line.getArgs();

        if (args.length != 2) {
            throw new Exception("Unexpected number of command line arguments");
        }

        queryFile = new File(args[0]);
        refFile = new File(args[1]);

    } catch (Exception e) {
        new HelpFormatter().printHelp("PairwiseKNN <options> <queryFile> <dbFile>", options);
        System.err.println("ERROR: " + e.getMessage());
        return;
    }

    PairwiseKNN theObj = new PairwiseKNN(queryFile, refFile, out, mode, k, wordSize, prefilter);
    theObj.match();

}

From source file:com.twitter.heron.apiserver.Runtime.java

@SuppressWarnings({ "IllegalCatch", "RegexpSinglelineJava" })
public static void main(String[] args) throws Exception {
    final Options options = createOptions();
    final Options helpOptions = constructHelpOptions();

    CommandLineParser parser = new DefaultParser();

    // parse the help options first.
    CommandLine cmd = parser.parse(helpOptions, args, true);
    if (cmd.hasOption(Flag.Help.name)) {
        usage(options);/*w w  w .  j  av  a  2  s . co m*/
        return;
    }

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println(pe.getMessage());
        usage(options);
        return;
    }

    final boolean verbose = isVerbose(cmd);
    // set and configure logging level
    Logging.setVerbose(verbose);
    Logging.configure(verbose);

    LOG.debug("apiserver overrides:\n {}", cmd.getOptionProperties(Flag.Property.name));

    final String toolsHome = getToolsHome();

    // read command line flags
    final String cluster = cmd.getOptionValue(Flag.Cluster.name);
    final String heronConfigurationDirectory = getConfigurationDirectory(toolsHome, cmd);
    final String heronDirectory = getHeronDirectory(cmd);
    final String releaseFile = getReleaseFile(toolsHome, cmd);
    final String configurationOverrides = loadOverrides(cmd);
    final int port = getPort(cmd);
    final String downloadHostName = getDownloadHostName(cmd);
    final String heronCorePackagePath = getHeronCorePackagePath(cmd);

    final Config baseConfiguration = ConfigUtils.getBaseConfiguration(heronDirectory,
            heronConfigurationDirectory, releaseFile, configurationOverrides);

    final ResourceConfig config = new ResourceConfig(Resources.get());
    final Server server = new Server(port);

    final ServletContextHandler contextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    contextHandler.setContextPath("/");

    LOG.info("using configuration path: {}", heronConfigurationDirectory);

    contextHandler.setAttribute(HeronResource.ATTRIBUTE_CLUSTER, cluster);
    contextHandler.setAttribute(HeronResource.ATTRIBUTE_CONFIGURATION, baseConfiguration);
    contextHandler.setAttribute(HeronResource.ATTRIBUTE_CONFIGURATION_DIRECTORY, heronConfigurationDirectory);
    contextHandler.setAttribute(HeronResource.ATTRIBUTE_CONFIGURATION_OVERRIDE_PATH, configurationOverrides);
    contextHandler.setAttribute(HeronResource.ATTRIBUTE_PORT, String.valueOf(port));
    contextHandler.setAttribute(HeronResource.ATTRIBUTE_DOWNLOAD_HOSTNAME,
            Utils.isNotEmpty(downloadHostName) ? String.valueOf(downloadHostName) : null);
    contextHandler.setAttribute(HeronResource.ATTRIBUTE_HERON_CORE_PACKAGE_PATH,
            Utils.isNotEmpty(heronCorePackagePath) ? String.valueOf(heronCorePackagePath) : null);

    server.setHandler(contextHandler);

    final ServletHolder apiServlet = new ServletHolder(new ServletContainer(config));

    contextHandler.addServlet(apiServlet, API_BASE_PATH);

    try {
        server.start();

        LOG.info("Heron apiserver started at {}", server.getURI());

        server.join();
    } catch (Exception ex) {
        final String message = getErrorMessage(server, port, ex);
        LOG.error(message);
        System.err.println(message);
        System.exit(1);
    } finally {
        server.destroy();
    }
}

From source file:eu.fbk.utils.wikipedia.WikipediaPlainTextExtractor.java

public static void main(String args[]) throws IOException {
    String logConfig = System.getProperty("log-config");
    if (logConfig == null) {
        logConfig = "configuration/log-config.txt";
    }/*from  w  ww.  ja v a  2s  . c  o m*/

    PropertyConfigurator.configure(logConfig);

    Options options = new Options();
    try {
        Option wikipediaDumpOpt = OptionBuilder.withArgName("file").hasArg()
                .withDescription("wikipedia xml dump file").isRequired().withLongOpt("wikipedia-dump")
                .create("d");
        Option outputDirOpt = OptionBuilder.withArgName("dir").hasArg()
                .withDescription("output directory in which to store output files").isRequired()
                .withLongOpt("output-dir").create("o");
        Option numThreadOpt = OptionBuilder.withArgName("int").hasArg()
                .withDescription("number of threads (default " + Defaults.DEFAULT_THREADS_NUMBER + ")")
                .withLongOpt("num-threads").create("t");
        Option numPageOpt = OptionBuilder.withArgName("int").hasArg()
                .withDescription("number of pages to process (default all)").withLongOpt("num-pages")
                .create("p");
        Option notificationPointOpt = OptionBuilder.withArgName("int").hasArg()
                .withDescription("receive notification every n pages (default "
                        + Defaults.DEFAULT_NOTIFICATION_POINT + ")")
                .withLongOpt("notification-point").create("b");

        options.addOption(null, "text-only", false, "skipt title in file");

        options.addOption("h", "help", false, "print this message");
        options.addOption("v", "version", false, "output version information and exit");

        options.addOption(wikipediaDumpOpt);
        options.addOption(outputDirOpt);
        options.addOption(numThreadOpt);
        options.addOption(numPageOpt);
        options.addOption(notificationPointOpt);
        CommandLineParser parser = new PosixParser();
        CommandLine line = parser.parse(options, args);
        logger.debug(line);

        if (line.hasOption("help") || line.hasOption("version")) {
            throw new ParseException("");
        }

        int numThreads = Defaults.DEFAULT_THREADS_NUMBER;
        boolean textOnly = line.hasOption("text-only");
        if (line.hasOption("num-threads")) {
            numThreads = Integer.parseInt(line.getOptionValue("num-threads"));
        }

        int numPages = Defaults.DEFAULT_NUM_PAGES;
        if (line.hasOption("num-pages")) {
            numPages = Integer.parseInt(line.getOptionValue("num-pages"));
        }

        int notificationPoint = Defaults.DEFAULT_NOTIFICATION_POINT;
        if (line.hasOption("notification-point")) {
            notificationPoint = Integer.parseInt(line.getOptionValue("notification-point"));
        }

        ExtractorParameters extractorParameters = new ExtractorParameters(line.getOptionValue("wikipedia-dump"),
                line.getOptionValue("output-dir"));
        WikipediaPlainTextExtractor wikipediaPageParser = new WikipediaPlainTextExtractor(numThreads, numPages,
                extractorParameters.getLocale());
        wikipediaPageParser.setNotificationPoint(notificationPoint);
        //            wikipediaPageParser.setSkipTitle(textOnly);
        wikipediaPageParser.start(extractorParameters);

        logger.info("extraction ended " + new Date());

    } catch (ParseException e) {
        // oops, something went wrong
        System.out.println("Parsing failed: " + e.getMessage() + "\n");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(400,
                "java -cp dist/thewikimachine.jar org.fbk.cit.hlt.thewikimachine.xmldump.WikipediaTextExtractor",
                "\n", options, "\n", true);
    }
}

From source file:eu.interedition.collatex.cli.Engine.java

public static void main(String... args) {
    final Engine engine = new Engine();
    try {// w  ww  . j a v  a  2 s. co m
        final CommandLine commandLine = new GnuParser().parse(OPTIONS, args);
        if (commandLine.hasOption("h")) {
            engine.help();
            return;
        }
        engine.configure(commandLine).read().collate().write();
    } catch (ParseException e) {
        engine.error("Error while parsing command line arguments", e);
        engine.log("\n").help();
    } catch (IllegalArgumentException e) {
        engine.error("Illegal argument", e);
    } catch (IOException e) {
        engine.error("I/O error", e);
    } catch (SAXException e) {
        engine.error("XML error", e);
    } catch (XPathExpressionException e) {
        engine.error("XPath error", e);
    } catch (ScriptException | PluginScript.PluginScriptExecutionException e) {
        engine.error("Script error", e);
    } finally {
        try {
            Closeables.close(engine, false);
        } catch (IOException e) {
        }
    }
}

From source file:cc.twittertools.index.ExtractTweetidsFromCollection.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("source collection directory")
            .create(COLLECTION_OPTION));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {//from  w w w  . j a v  a  2s  .  c  o m
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(COLLECTION_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ExtractTweetidsFromCollection.class.getName(), options);
        System.exit(-1);
    }

    String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION);

    File file = new File(collectionPath);
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    StatusStream stream = new JsonStatusCorpusReader(file);

    Status status;
    while ((status = stream.next()) != null) {
        System.out.println(status.getId() + "\t" + status.getScreenname());
    }
}