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.ikanow.infinit.e.core.CoreMain.java

/**
 * @param args//  www.j a  v  a  2s.  c  o  m
 * @throws ParseException 
 * @throws IOException 
 * @throws InterruptedException 
 */
public static void main(String[] args) throws ParseException, IOException, InterruptedException {

    CommandLineParser cliParser = new BasicParser();
    Options allOps = new Options();
    // Common
    allOps.addOption("c", "config", true, "Configuration path");
    allOps.addOption("g", "community", true, "Only run on one community");
    // Harvest specific
    allOps.addOption("h", "harvest", false, "Run harvester");
    allOps.addOption("l", "local", false, "(for debug: use dummy index)");
    allOps.addOption("i", "source", true, "(for debug: use a single source)");
    allOps.addOption("r", "reset", false, "Reset bad sources");
    // Sync specific
    allOps.addOption("s", "sync", false, "Run synchronization");
    allOps.addOption("f", "from", true, "String unix time (secs) from when to sync");
    // Custom specifc
    allOps.addOption("p", "custom", false, "Run custom processing server");
    allOps.addOption("d", "dummy", true, "Use to keep temp unwanted options on the command line");
    allOps.addOption("j", "jobtitle", true, "(for debug: run a single job)");

    CommandLine cliOpts = cliParser.parse(allOps, args);

    Globals.setIdentity(com.ikanow.infinit.e.data_model.Globals.Identity.IDENTITY_SERVICE);

    if (cliOpts.hasOption("config")) {
        String configOverride = (String) cliOpts.getOptionValue("config");
        Globals.overrideConfigLocation(configOverride);
    }
    //Set up logging
    java.io.File file = new java.io.File(
            com.ikanow.infinit.e.data_model.Globals.getLogPropertiesLocation() + ".xml");
    if (file.exists()) {
        DOMConfigurator.configure(com.ikanow.infinit.e.data_model.Globals.getLogPropertiesLocation() + ".xml");
    } else {
        PropertyConfigurator.configure(Globals.getLogPropertiesLocation());
    }

    if (cliOpts.hasOption("harvest")) {
        if (SourceUtils.checkDbSyncLock()) {
            Thread.sleep(10000); // (wait 10s and then try again)
            System.exit(0);
        }
        String communityOverride = null;
        String sourceDebug = null;
        if (cliOpts.hasOption("local")) {
            ElasticSearchManager.setLocalMode(true);
        }
        if (cliOpts.hasOption("reset")) {
            SourceUtils.resetBadSources();
        }
        if (cliOpts.hasOption("community")) {
            communityOverride = (String) cliOpts.getOptionValue("community");
        }
        if (cliOpts.hasOption("source")) {
            sourceDebug = (String) cliOpts.getOptionValue("source");
        }
        new HarvestThenProcessController()
                .startService(SourceUtils.getSourcesToWorkOn(communityOverride, sourceDebug, false, true));
    } //TESTED
    else if (cliOpts.hasOption("sync")) {
        if (SourceUtils.checkDbSyncLock()) {
            Thread.sleep(10000); // (wait 10s and then try again)
            System.exit(0);
        }
        // Sync command line options:
        long nTimeOfLastCleanse_secs = 0; // (default)
        if (cliOpts.hasOption("from")) {
            try {
                nTimeOfLastCleanse_secs = Long.parseLong((String) cliOpts.getOptionValue("from"));
            } catch (NumberFormatException e) {
                System.out.println("From date is incorrect");
                System.exit(-1);
            }
        }
        String communityOverride = null;
        String sourceDebug = null;
        if (cliOpts.hasOption("community")) {
            communityOverride = (String) cliOpts.getOptionValue("community");
        } else if (cliOpts.hasOption("source")) {
            sourceDebug = (String) cliOpts.getOptionValue("source");
        }
        SourceUtils.checkSourcesHaveHashes(communityOverride, sourceDebug);
        // (infrequently ie as part of sync, check all the sources have hashes, which the harvester depends on)

        new SynchronizationController().startService(nTimeOfLastCleanse_secs,
                SourceUtils.getSourcesToWorkOn(communityOverride, sourceDebug, true, true));
    } //TESTED
    else if (cliOpts.hasOption("custom")) {
        String jobOverride = null;
        if (cliOpts.hasOption("jobtitle")) {
            jobOverride = (String) cliOpts.getOptionValue("jobtitle");
        }
        CustomProcessingController customPxController = new CustomProcessingController();
        customPxController.checkScheduledJobs(jobOverride);
        customPxController.checkRunningJobs();
        customPxController.runThroughSavedQueues();
    } else {
        //Test code for distribution:
        //         boolean bSync = true;
        //         LinkedList<SourcePojo> testSources = null;
        //         LinkedList<SourcePojo> batchOfSources = null;
        //         testSources = getSourcesToWorkOn(null, null, bSync, true);
        //         System.out.println("Sources considered = " + testSources.size());
        //         // Grab a batch of sources
        //         batchOfSources = getDistributedSourceList(testSources, null, false);
        //         System.out.println("Sources left = " + testSources.size());
        //         System.out.println("Sources extracted = " + new com.google.gson.Gson().toJson(batchOfSources));

        System.out.println(
                "com.ikanow.infinit.e.core.server [--config <config-dir>] [--harvest [<other options>]|--sync [<other options>]|--custom [<other options>]]");
        System.exit(-1);
    }
    MongoApplicationLock.registerAppShutdown(); // (in case the saved queries are running, for some reason built in startup hook not running)
}

From source file:com.divinesoft.boynas.Boynas.java

public static void main(String args[]) {
    //TODO: Move Options to a different method
    Options options = new Options();

    //Create options
    Option list = OptionBuilder.withDescription("List all config entries in database").create("list");

    Option clean = OptionBuilder.withDescription("Remove all config entries in database").create("clean");

    Option importCSV = OptionBuilder.withArgName("file").hasArg()
            .withDescription("Import config entries from a CSV file").create("importCSV");

    Option exportXML = OptionBuilder.withDescription("Export all config entries to XML CFG files")
            .create("exportXML");

    Option exportTemplate = OptionBuilder.withArgName("templates folder").hasArgs()
            .withDescription("Export all config entries from a set of template files").create("exportTemplate");

    Option version = OptionBuilder.withDescription("Print the version number").create("version");

    Option quickGen = OptionBuilder.withArgName("import file,templates folder")
            .withDescription("Use a one-shot template based config generator").hasArgs(2)
            .withValueSeparator(' ').create("quickExport");

    //Add options
    options.addOption(list);/*from ww w . ja  v a 2s .  c  om*/
    options.addOption(clean);
    options.addOption(importCSV);
    options.addOption(exportXML);
    options.addOption(exportTemplate);
    options.addOption(quickGen);
    options.addOption(version);

    CommandLineParser parser = new GnuParser();

    //The main Boynas object
    Boynas boynas;

    //Start dealing with application context
    XmlBeanFactory appContext = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));

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

        if (cmd.hasOption("list")) {
            boynas = (Boynas) appContext.getBean("boynasList");
            boynas.getAllConfigEntries();
        } else if (cmd.hasOption("clean")) {
            boynas = (Boynas) appContext.getBean("boynasList");
            boynas.clean();
        } else if (cmd.hasOption("importCSV")) {
            Boynas.filePath = cmd.getOptionValue("importCSV");
            boynas = (Boynas) appContext.getBean("bynImportCSV");
            boynas.importCSV();
        } else if (cmd.hasOption("exportXML")) {
            boynas = (Boynas) appContext.getBean("bynExportXML");
            boynas.exportXML();
        } else if (cmd.hasOption("version")) {
            boynas = (Boynas) appContext.getBean("boynasList");
            boynas.printVersion();
        } else if (cmd.hasOption("exportTemplate")) {
            Boynas.templatePath = cmd.getOptionValue("exportTemplate");
            boynas = (Boynas) appContext.getBean("bynExportTemplate");
            boynas.exportTemplate();
        } else if (cmd.hasOption("quickExport")) {
            String[] paths = cmd.getOptionValues("quickExport");

            if (paths.length < 2) {
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("boynas", options);
            }

            Boynas.filePath = paths[0];
            Boynas.templatePath = paths[1];
            boynas = (Boynas) appContext.getBean("bynQuickExport");
            boynas.quickExport();
        }

        else {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("boynas", options);
        }

    } catch (ParseException e) {
        System.err.println("Parsing failed. Reason: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("boynas", options);
    }
}

From source file:Inmemantlr.java

public static void main(String[] args) {
    LOGGER.info("Inmemantlr tool");

    HelpFormatter hformatter = new HelpFormatter();

    Options options = new Options();

    // Binary arguments
    options.addOption("h", "print this message");

    Option grmr = Option.builder().longOpt("grmrfiles").hasArgs().desc("comma-separated list of ANTLR files")
            .required(true).argName("grmrfiles").type(String.class).valueSeparator(',').build();

    Option infiles = Option.builder().longOpt("infiles").hasArgs()
            .desc("comma-separated list of files to parse").required(true).argName("infiles").type(String.class)
            .valueSeparator(',').build();

    Option utilfiles = Option.builder().longOpt("utilfiles").hasArgs()
            .desc("comma-separated list of utility files to be added for " + "compilation").required(false)
            .argName("utilfiles").type(String.class).valueSeparator(',').build();

    Option odir = Option.builder().longOpt("outdir")
            .desc("output directory in which the dot files will be " + "created").required(false).hasArg(true)
            .argName("outdir").type(String.class).build();

    options.addOption(infiles);//from  www.j  av  a2s  .  com
    options.addOption(grmr);
    options.addOption(utilfiles);
    options.addOption(odir);

    CommandLineParser parser = new DefaultParser();

    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption('h')) {
            hformatter.printHelp("java -jar inmemantlr.jar", options);
            System.exit(0);
        }
    } catch (ParseException e) {
        hformatter.printHelp("java -jar inmemantlr.jar", options);
        LOGGER.error(e.getMessage());
        System.exit(-1);
    }

    // input files
    Set<File> ins = getFilesForOption(cmd, "infiles");
    // grammar files
    Set<File> gs = getFilesForOption(cmd, "grmrfiles");
    // utility files
    Set<File> uf = getFilesForOption(cmd, "utilfiles");
    // output dir
    Set<File> od = getFilesForOption(cmd, "outdir");

    if (od.size() > 1) {
        LOGGER.error("output directories must be less than or equal to 1");
        System.exit(-1);
    }

    if (ins.size() <= 0) {
        LOGGER.error("no input files were specified");
        System.exit(-1);
    }

    if (gs.size() <= 0) {
        LOGGER.error("no grammar files were specified");
        System.exit(-1);
    }

    LOGGER.info("create generic parser");
    GenericParser gp = null;
    try {
        gp = new GenericParser(gs.toArray(new File[gs.size()]));
    } catch (FileNotFoundException e) {
        LOGGER.error(e.getMessage());
        System.exit(-1);
    }

    if (!uf.isEmpty()) {
        try {
            gp.addUtilityJavaFiles(uf.toArray(new String[uf.size()]));
        } catch (FileNotFoundException e) {
            LOGGER.error(e.getMessage());
            System.exit(-1);
        }
    }

    LOGGER.info("create and add parse tree listener");
    DefaultTreeListener dt = new DefaultTreeListener();
    gp.setListener(dt);

    LOGGER.info("compile generic parser");
    try {
        gp.compile();
    } catch (CompilationException e) {
        LOGGER.error("cannot compile generic parser: {}", e.getMessage());
        System.exit(-1);
    }

    String fpfx = "";
    for (File of : od) {
        if (!of.exists() || !of.isDirectory()) {
            LOGGER.error("output directory does not exist or is not a " + "directory");
            System.exit(-1);
        }
        fpfx = of.getAbsolutePath();
    }

    Ast ast;
    for (File f : ins) {
        try {
            gp.parse(f);
        } catch (IllegalWorkflowException | FileNotFoundException e) {
            LOGGER.error(e.getMessage());
            System.exit(-1);
        }
        ast = dt.getAst();

        if (!fpfx.isEmpty()) {
            String of = fpfx + "/" + FilenameUtils.removeExtension(f.getName()) + ".dot";

            LOGGER.info("write file {}", of);

            try {
                FileUtils.writeStringToFile(new File(of), ast.toDot(), "UTF-8");
            } catch (IOException e) {
                LOGGER.error(e.getMessage());
                System.exit(-1);
            }
        } else {
            LOGGER.info("Tree for {} \n {}", f.getName(), ast.toDot());
        }
    }

    System.exit(0);
}

From source file:jparser.JParser.java

/**
 * @param args the command line arguments
 *//* w w  w  .  j a v a2  s .c  o m*/
public static void main(String[] args) {

    Options options = new Options();
    CommandLineParser parser = new DefaultParser();

    options.addOption(
            Option.builder().longOpt("to").desc("Indica el tipo de archivo al que debera convertir: JSON / XML")
                    .hasArg().argName("tipo").build());

    options.addOption(Option.builder().longOpt("path")
            .desc("Indica la ruta donde se encuentra el archivo origen").hasArg().argName("origen").build());

    options.addOption(
            Option.builder().longOpt("target").desc("Indica la ruta donde se guardara el archivo resultante")
                    .hasArg().argName("destino").build());

    options.addOption("h", "help", false, "Muestra la guia de como usar la aplicacion");

    try {
        CommandLine command = parser.parse(options, args);
        Path source = null;
        Path target = null;
        FactoryFileParse.TypeParce type = FactoryFileParse.TypeParce.NULL;
        Optional<Customer> customer = Optional.empty();

        if (command.hasOption("h")) {
            HelpFormatter helper = new HelpFormatter();
            helper.printHelp("JParser", options);

            System.exit(0);
        }

        if (command.hasOption("to"))
            type = FactoryFileParse.TypeParce.fromValue(command.getOptionValue("to", ""));

        if (command.hasOption("path"))
            source = Paths.get(command.getOptionValue("path", ""));

        if (command.hasOption("target"))
            target = Paths.get(command.getOptionValue("target", ""));

        switch (type) {
        case JSON:
            customer = FactoryFileParse.createNewInstance(FactoryFileParse.TypeParce.XML).read(source);

            break;

        case XML:
            customer = FactoryFileParse.createNewInstance(FactoryFileParse.TypeParce.JSON).read(source);

            break;
        }

        if (customer.isPresent()) {
            Customer c = customer.get();

            boolean success = FactoryFileParse.createNewInstance(type).write(c, target);

            System.out.println(String.format("Operatation was: %s", success ? "success" : "fails"));
        }

    } catch (ParseException ex) {
        Logger.getLogger(JParser.class.getSimpleName()).log(Level.SEVERE, ex.getMessage(), ex);

        System.exit(-1);
    }
}

From source file:net.orzo.App.java

/**
 *
 *///  w ww  .  j  a v a2 s  .  c o m
public static void main(final String[] args) {
    final App app = new App();
    Logger log = null;
    CommandLine cmd;

    try {
        cmd = app.init(args);

        if (cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(
                    "orzo [options] user_script [user_arg1 [user_arg2 [...]]]\n(to generate a template: orzo -t [file path])",
                    app.cliOptions);

        } else if (cmd.hasOption("v")) {
            System.out.printf("Orzo.js version %s\n", app.props.get("orzo.version"));

        } else if (cmd.hasOption("t")) {
            String templateSrc = new ResourceLoader().getResourceAsString("net/orzo/template1.js");

            File tplFile = new File(cmd.getOptionValue("t"));
            FileWriter tplWriter = new FileWriter(tplFile);
            tplWriter.write(templateSrc);
            tplWriter.close();

            File dtsFile = new File(
                    String.format("%s/orzojs.d.ts", new File(tplFile.getAbsolutePath()).getParent()));
            FileWriter dtsWriter = new FileWriter(dtsFile);
            String dtsSrc = new ResourceLoader().getResourceAsString("net/orzo/orzojs.d.ts");
            dtsWriter.write(dtsSrc);
            dtsWriter.close();

        } else if (cmd.hasOption("T")) {
            String templateSrc = new ResourceLoader().getResourceAsString("net/orzo/template1.js");
            System.out.println(templateSrc);

        } else {

            // Logger initialization
            if (cmd.hasOption("g")) {
                System.setProperty("logback.configurationFile", cmd.getOptionValue("g"));

            } else {
                System.setProperty("logback.configurationFile", "./logback.xml");
            }
            log = LoggerFactory.getLogger(App.class);
            if (cmd.hasOption("s")) { // Orzo.js as a REST and AMQP service
                FullServiceConfig conf = new Gson().fromJson(new FileReader(cmd.getOptionValue("s")),
                        FullServiceConfig.class);
                Injector injector = Guice.createInjector(new CoreModule(conf), new RestServletModule());
                HttpServer httpServer = new HttpServer(conf, new JerseyGuiceServletConfig(injector));
                app.services.add(httpServer);

                if (conf.getAmqpResponseConfig() != null) {
                    // response AMQP service must be initialized before receiving one
                    app.services.add(injector.getInstance(AmqpResponseConnection.class));
                }

                if (conf.getAmqpConfig() != null) {
                    app.services.add(injector.getInstance(AmqpConnection.class));
                    app.services.add(injector.getInstance(AmqpService.class));
                }

                if (conf.getRedisConf() != null) {
                    app.services.add(injector.getInstance(RedisStorage.class));
                }

                Runtime.getRuntime().addShutdownHook(new ShutdownHook(app));
                app.startServices();

            } else if (cmd.hasOption("d")) { // Demo mode
                final String scriptId = "demo";
                final SourceCode demoScript = SourceCode.fromResource(DEMO_SCRIPT);
                System.err.printf("Running demo script %s.", demoScript.getName());
                CmdConfig conf = new CmdConfig(scriptId, demoScript, null, cmd.getOptionValue("p", null));
                TaskManager tm = new TaskManager(conf);
                tm.startTaskSync(tm.registerTask(scriptId, new String[0]));

            } else if (cmd.getArgs().length > 0) { // Command line mode
                File userScriptFile = new File(cmd.getArgs()[0]);
                String optionalModulesPath = null;
                String[] inputValues;
                SourceCode userScript;

                // custom CommonJS modules path
                if (cmd.hasOption("m")) {
                    optionalModulesPath = cmd.getOptionValue("m");
                }

                if (cmd.getArgs().length > 0) {
                    inputValues = Arrays.copyOfRange(cmd.getArgs(), 1, cmd.getArgs().length);
                } else {
                    inputValues = new String[0];
                }

                userScript = SourceCode.fromFile(userScriptFile);
                CmdConfig conf = new CmdConfig(userScript.getName(), userScript, optionalModulesPath,
                        cmd.getOptionValue("p", null));
                TaskManager tm = new TaskManager(conf);
                String taskId = tm.registerTask(userScript.getName(), inputValues);
                tm.startTaskSync(taskId);
                if (tm.getTask(taskId).getStatus() == TaskStatus.ERROR) {
                    tm.getTask(taskId).getFirstError().getErrors().stream().forEach(System.err::println);
                }

            } else {
                System.err.println("Invalid parameters. Try -h for more information.");
                System.exit(1);
            }
        }

    } catch (Exception ex) {
        System.err.printf("Orzo.js crashed with error: %s\nSee the log for details.\n", ex.getMessage());
        if (log != null) {
            log.error(ex.getMessage(), ex);

        } else {
            ex.printStackTrace();
        }
    }
}

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

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

    options.addOption(/*from w  w  w. j a v a2 s .c o  m*/
            OptionBuilder.withArgName("dir").hasArg().withDescription("index location").create(INDEX_OPTION));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

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

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

    IndexReader reader = DirectoryReader.open(FSDirectory.open(indexLocation));
    PrintStream out = new PrintStream(System.out, true, "UTF-8");
    for (int i = 0; i < reader.maxDoc(); i++) {
        Document doc = reader.document(i);
        out.println(doc.getField(StatusField.ID.name).stringValue() + "\t"
                + doc.getField(StatusField.SCREEN_NAME.name).stringValue());
    }
    out.close();
    reader.close();
}

From source file:com.datascience.gal.scripts.MainClient.java

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

    DawidSkeneClient dsclient = new DawidSkeneClient();

    String categoriesfile = null;
    String inputfile = null;/*from   w w  w  .  j  av a  2s. c  om*/
    String correctfile = null;
    String costfile = null;
    int iterations = 1;
    boolean incremental = false;

    CommandLineParser parser = new GnuParser();
    CommandLine line = parser.parse(cli_options, args);

    if (!line.hasOption("c") || !line.hasOption("l") || !line.hasOption("g") || !line.hasOption("C")) {
        printHelp();
        System.exit(1);
    }

    categoriesfile = line.getOptionValue("c");
    inputfile = line.getOptionValue("l");

    if (line.hasOption("g"))
        correctfile = line.getOptionValue("g");
    if (line.hasOption("C"))
        costfile = line.getOptionValue("C");
    if (line.hasOption("i"))
        iterations = Integer.parseInt(line.getOptionValue("i"));
    if (line.hasOption("I"))
        incremental = true;

    // see if the thing is awake
    System.out.println(dsclient.isAlive() ? "pinged alive" : "problem with dsclient");
    // hard reset
    System.out.println(dsclient.deleteDS(0) ? "deleted ds 0" : "failed to delete ds 0");

    Collection<Category> categories = loadCategoriesFromFile(categoriesfile);
    if (categories.size() < 2) {
        System.err.println("invalid category input");
        System.exit(1);
    }

    System.out.println("sending to service: " + JSONUtils.toJson(categories));

    System.out.println(
            "response: " + (dsclient.initializeDS(0, categories, incremental) ? "success" : "failure"));

    // check the serialization of the json ds object
    DawidSkene ds = dsclient.getDawidSkene(0);
    System.out.println(ds);

    Collection<MisclassificationCost> costs = loadMisclassificationCosts(costfile);

    System.out.println("response: " + (dsclient.addMisclassificationCosts(0, costs) ? "successfully added costs"
            : "unable to add costs") + " - " + JSONUtils.toJson(costs));

    Collection<AssignedLabel> labels = loadAssignedLabels(inputfile);

    System.out.println("response: "
            + (dsclient.addAssignedLabels(0, labels) ? "successfully added labels" : "unable to add labels")
            + " - " + JSONUtils.toJson(labels));

    Collection<CorrectLabel> gold = loadGoldLabels(correctfile);
    System.out.println("response: "
            + (dsclient.addCorrectLabels(0, gold) ? "successfully added labels" : "unable to add labels")
            + " - " + JSONUtils.toJson(gold));

    Map<String, String> preVotes = dsclient.computeMajorityVotes(0);

    ds = dsclient.getDawidSkene(0);

    System.out.println(ds);
    if (!incremental)
        System.out.println(
                dsclient.iterateBlocking(0, iterations) ? "successfully iterated" : "failed ds iterations");

    ds = dsclient.getDawidSkene(0);
    System.out.println(ds);

    System.out.println(ds.printAllWorkerScores(false));
    System.out.println(ds.printObjectClassProbabilities(0));
    System.out.println(ds.printPriors());

    Map<String, String> postVotes = dsclient.computeMajorityVotes(0);

    System.out.println("note- diff doesnt work with incremental\n" + printDiffVote(preVotes, postVotes));

    System.out.println(JSONUtils.toJson(ds.getMajorityVote()));
    System.out.println(JSONUtils.toJson(ds.getObjectProbs()));

    Collection<String> objectNames = new HashSet<String>();
    String name = null;
    for (AssignedLabel label : labels) {
        objectNames.add(label.getObjectName());
        name = label.getObjectName();
    }

    System.out.println(JSONUtils.toJson(ds.getMajorityVote(objectNames)));
    System.out.println(JSONUtils.toJson(ds.getObjectProbs(objectNames)));

    System.out.println(JSONUtils.toJson(ds.getMajorityVote(name)));
    System.out.println(JSONUtils.toJson(ds.getObjectProbs(name)));

    boolean contains;
    contains = dsclient.hasDSObject(0);
    System.out.println(contains ? "has 0" : "dont have 0");
    contains = dsclient.hasDSObject(1);
    System.out.println(contains ? "has 1" : "dont have 1");
    System.out.println("deleting 0");
    dsclient.deleteDS(0);
    contains = dsclient.hasDSObject(0);
    System.out.println(contains ? "has 0" : "dont have 0");
}

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

/**
 * @param args// w w w.  ja  v a 2 s .c om
 */
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 Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_MAX_CONFS, true, "Maximum number of conformations per input.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_TORSION_FILE, true, "Optional: to overwrite torsion definition file.");
    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);
    String smartsFile = cmd.getOptionValue(OPT_TORSION_FILE);
    long maxConfs = Long.parseLong(cmd.getOptionValue(OPT_MAX_CONFS));

    SDFConformerSampler scanner = new SDFConformerSampler(smartsFile, outFile, maxConfs);

    scanner.run(inFile);
    scanner.close();
}

From source file:com.betfair.cougar.test.socket.app.SocketCompatibilityTestingApp.java

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

    Parser parser = new PosixParser();
    Options options = new Options();
    options.addOption("r", "repo", true, "Repository type to search: local|central");
    options.addOption("c", "client-concurrency", true,
            "Max threads to allow each client tester to run tests, defaults to 10");
    options.addOption("t", "test-concurrency", true, "Max client testers to run concurrently, defaults to 5");
    options.addOption("m", "max-time", true,
            "Max time (in minutes) to allow tests to complete, defaults to 10");
    options.addOption("v", "version", false, "Print version and exit");
    options.addOption("h", "help", false, "This help text");
    CommandLine commandLine = parser.parse(options, args);
    if (commandLine.hasOption("h")) {
        System.out.println(options);
        System.exit(0);//from w w w  .j a v a 2 s  . co m
    }
    if (commandLine.hasOption("v")) {
        System.out.println("How the hell should I know?");
        System.exit(0);
    }
    // 1. Find all testers in given repos
    List<RepoSearcher> repoSearchers = new ArrayList<>();
    for (String repo : commandLine.getOptionValues("r")) {
        if ("local".equals(repo.toLowerCase())) {
            repoSearchers.add(new LocalRepoSearcher());
        } else if ("central".equals(repo.toLowerCase())) {
            repoSearchers.add(new CentralRepoSearcher());
        } else {
            System.err.println("Unrecognized repo: " + repo);
            System.err.println(options);
            System.exit(1);
        }
    }
    int clientConcurrency = 10;
    if (commandLine.hasOption("c")) {
        try {
            clientConcurrency = Integer.parseInt(commandLine.getOptionValue("c"));
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "client-concurrency is not a valid integer: '" + commandLine.getOptionValue("c") + "'");
            System.exit(1);
        }
    }
    int testConcurrency = 5;
    if (commandLine.hasOption("t")) {
        try {
            testConcurrency = Integer.parseInt(commandLine.getOptionValue("t"));
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "test-concurrency is not a valid integer: '" + commandLine.getOptionValue("t") + "'");
            System.exit(1);
        }
    }
    int maxMinutes = 10;
    if (commandLine.hasOption("m")) {
        try {
            maxMinutes = Integer.parseInt(commandLine.getOptionValue("m"));
        } catch (NumberFormatException nfe) {
            System.err.println("max-time is not a valid integer: '" + commandLine.getOptionValue("m") + "'");
            System.exit(1);
        }
    }

    Properties clientProps = new Properties();
    clientProps.setProperty("client.concurrency", String.valueOf(clientConcurrency));

    File baseRunDir = new File(System.getProperty("user.dir") + "/run");
    baseRunDir.mkdirs();

    File tmpDir = new File(baseRunDir, "jars");
    tmpDir.mkdirs();

    List<ServerRunner> serverRunners = new ArrayList<>();
    List<ClientRunner> clientRunners = new ArrayList<>();
    for (RepoSearcher searcher : repoSearchers) {
        List<File> jars = searcher.findAndCache(tmpDir);
        for (File f : jars) {
            ServerRunner serverRunner = new ServerRunner(f, baseRunDir);
            System.out.println("Found tester: " + serverRunner.getVersion());
            serverRunners.add(serverRunner);
            clientRunners.add(new ClientRunner(f, baseRunDir, clientProps));
        }
    }

    // 2. Start servers and collect ports
    System.out.println();
    System.out.println("Starting " + serverRunners.size() + " servers...");
    for (ServerRunner server : serverRunners) {
        server.startServer();
    }
    System.out.println();

    List<TestCombo> tests = new ArrayList<>(serverRunners.size() * clientRunners.size());
    for (ServerRunner server : serverRunners) {
        for (ClientRunner client : clientRunners) {
            tests.add(new TestCombo(server, client));
        }
    }

    System.out.println("Enqueued " + tests.size() + " test combos to run...");

    long startTime = System.currentTimeMillis();
    // 3. Run every client against every server, collecting results
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(serverRunners.size() * clientRunners.size());
    ThreadPoolExecutor service = new ThreadPoolExecutor(testConcurrency, testConcurrency, 5000,
            TimeUnit.MILLISECONDS, workQueue);
    service.prestartAllCoreThreads();
    workQueue.addAll(tests);
    while (!workQueue.isEmpty()) {
        Thread.sleep(1000);
    }
    service.shutdown();
    service.awaitTermination(maxMinutes, TimeUnit.MINUTES);
    long endTime = System.currentTimeMillis();
    long totalTimeSecs = Math.round((endTime - startTime) / 1000.0);
    for (ServerRunner server : serverRunners) {
        server.shutdownServer();
    }

    System.out.println();
    System.out.println("=======");
    System.out.println("Results");
    System.out.println("-------");
    // print a summary
    int totalTests = 0;
    int totalSuccess = 0;
    for (TestCombo combo : tests) {
        String clientVer = combo.getClientVersion();
        String serverVer = combo.getServerVersion();
        String results = combo.getClientResults();
        ObjectMapper mapper = new ObjectMapper(new JsonFactory());
        JsonNode node = mapper.reader().readTree(results);
        JsonNode resultsArray = node.get("results");
        int numTests = resultsArray.size();
        int numSuccess = 0;
        for (int i = 0; i < numTests; i++) {
            if ("success".equals(resultsArray.get(i).get("result").asText())) {
                numSuccess++;
            }
        }
        totalSuccess += numSuccess;
        totalTests += numTests;
        System.out.println(clientVer + "/" + serverVer + ": " + numSuccess + "/" + numTests
                + " succeeded - took " + String.format("%2f", combo.getRunningTime()) + " seconds");
    }
    System.out.println("-------");
    System.out.println(
            "Overall: " + totalSuccess + "/" + totalTests + " succeeded - took " + totalTimeSecs + " seconds");

    FileWriter out = new FileWriter("results.json");
    PrintWriter pw = new PrintWriter(out);

    // 4. Output full results
    pw.println("{\n  \"results\": [");
    for (TestCombo combo : tests) {
        combo.emitResults(pw, "    ");
    }
    pw.println("  ],");
    pw.println("  \"servers\": [");
    for (ServerRunner server : serverRunners) {
        server.emitInfo(pw, "    ");
    }
    pw.println("  ],");
    pw.close();
}

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

/**
 * @param args//from   w ww.  j av a  2s.c o m
 */
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 Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    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);
    SDFMolSeparator separator = new SDFMolSeparator(outFile);

    try {
        separator.run(inFile);

    } catch (IndexOutOfBoundsException iie) {
        System.err.println(iie.toString());
        exitWithHelp(options);
    } finally {
        separator.close();
    }

}