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

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

Introduction

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

Prototype

public String[] getArgs() 

Source Link

Document

Retrieve any left-over non-recognized options and arguments

Usage

From source file:ca.ualberta.exemplar.core.Exemplar.java

public static void main(String[] rawArgs) throws FileNotFoundException, UnsupportedEncodingException {

    CommandLineParser cli = new BasicParser();

    Options options = new Options();
    options.addOption("h", "help", false, "shows this message");
    options.addOption("b", "benchmark", true, "expects input to be a benchmark file (type = binary | nary)");
    options.addOption("p", "parser", true, "defines which parser to use (parser = stanford | malt)");

    CommandLine line = null;

    try {/* w w w.j av  a 2  s  .c o  m*/
        line = cli.parse(options, rawArgs);
    } catch (ParseException exp) {
        System.err.println(exp.getMessage());
        System.exit(1);
    }

    String[] args = line.getArgs();
    String parserName = line.getOptionValue("parser", "malt");

    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("sh ./exemplar", options);
        System.exit(0);
    }

    if (args.length != 2) {
        System.out.println("error: exemplar requires an input file and output file.");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("sh ./exemplar <input> <output>", options);
        System.exit(0);
    }

    File input = new File(args[0]);
    File output = new File(args[1]);

    String benchmarkType = line.getOptionValue("benchmark", "");
    if (!benchmarkType.isEmpty()) {
        if (benchmarkType.equals("binary")) {
            BenchmarkBinary evaluation = new BenchmarkBinary(input, output, parserName);
            evaluation.runAndTime();
            System.exit(0);
        } else {
            if (benchmarkType.equals("nary")) {
                BenchmarkNary evaluation = new BenchmarkNary(input, output, parserName);
                evaluation.runAndTime();
                System.exit(0);
            } else {
                System.out.println("error: benchmark option has to be either 'binary' or 'nary'.");
                System.exit(0);
            }
        }
    }

    Parser parser = null;
    if (parserName.equals("stanford")) {
        parser = new ParserStanford();
    } else {
        if (parserName.equals("malt")) {
            parser = new ParserMalt();
        } else {
            System.out.println(parserName + " is not a valid parser.");
            System.exit(0);
        }
    }

    System.out.println("Starting EXEMPLAR...");

    RelationExtraction exemplar = null;
    try {
        exemplar = new RelationExtraction(parser);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    BlockingQueue<String> inputQueue = new ArrayBlockingQueue<String>(QUEUE_SIZE);
    PlainTextReader reader = null;
    reader = new PlainTextReader(inputQueue, input);

    Thread readerThread = new Thread(reader);
    readerThread.start();

    PrintStream statementsOut = null;

    try {
        statementsOut = new PrintStream(output, "UTF-8");
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        System.exit(0);
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
        System.exit(0);
    }

    statementsOut.println("Subjects\tRelation\tObjects\tNormalized Relation\tSentence");

    while (true) {
        String doc = null;
        try {
            doc = inputQueue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (doc.isEmpty()) {
            break;
        }

        List<RelationInstance> instances = exemplar.extractRelations(doc);

        for (RelationInstance instance : instances) {

            // Output SUBJ arguments in a separate field, for clarity
            boolean first = true;
            for (Argument arg : instance.getArguments()) {
                if (arg.argumentType.equals("SUBJ")) {
                    if (first) {
                        first = false;
                    } else {
                        statementsOut.print(",,");
                    }
                    statementsOut.print(arg.argumentType + ":" + arg.entityId);
                }
            }

            // Output the original relation
            statementsOut.print("\t" + instance.getOriginalRelation() + "\t");

            // Output the DOBJ arguments, followed by POBJ
            first = true;
            for (Argument arg : instance.getArguments()) {
                if (arg.argumentType.equals("DOBJ")) {
                    if (first) {
                        first = false;
                    } else {
                        statementsOut.print(",,");
                    }
                    statementsOut.print(arg.argumentType + ":" + arg.entityId);
                }
            }
            for (Argument arg : instance.getArguments()) {
                if (arg.argumentType.startsWith("POBJ")) {
                    if (first) {
                        first = false;
                    } else {
                        statementsOut.print(",,");
                    }
                    statementsOut.print(arg.argumentType + ":" + arg.entityId);
                }
            }
            statementsOut.print("\t" + instance.getNormalizedRelation());
            statementsOut.print("\t" + instance.getSentence());
            statementsOut.println();
        }
    }

    System.out.println("Done!");
    statementsOut.close();

}

From source file:com.ctriposs.rest4j.tools.snapshot.check.Rest4JSnapshotCompatibilityChecker.java

public static void main(String[] args) {
    final Options options = new Options();
    options.addOption("h", "help", false, "Print help");
    options.addOption(OptionBuilder.withArgName("compatibility_level").withLongOpt("compat").hasArg()
            .withDescription("Compatibility level " + listCompatLevelOptions()).create('c'));
    final String cmdLineSyntax = Rest4JSnapshotCompatibilityChecker.class.getCanonicalName()
            + " [pairs of <prevRestspecPath currRestspecPath>]";

    final CommandLineParser parser = new PosixParser();
    final CommandLine cmd;

    try {//from w w  w . j a  v  a 2  s .c  om
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(1);
        return; // to suppress IDE warning
    }

    final String[] targets = cmd.getArgs();
    if (cmd.hasOption('h') || targets.length < 2 || targets.length % 2 != 0) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(1);
    }

    final String compatValue;
    if (cmd.hasOption('c')) {
        compatValue = cmd.getOptionValue('c');
    } else {
        compatValue = CompatibilityLevel.DEFAULT.name();
    }

    final CompatibilityLevel compat;
    try {
        compat = CompatibilityLevel.valueOf(compatValue.toUpperCase());
    } catch (IllegalArgumentException e) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(1);
        return;
    }

    final StringBuilder allSummaries = new StringBuilder();
    boolean result = true;
    final String resolverPath = System.getProperty(AbstractGenerator.GENERATOR_RESOLVER_PATH);
    final Rest4JSnapshotCompatibilityChecker checker = new Rest4JSnapshotCompatibilityChecker();
    checker.setResolverPath(resolverPath);

    for (int i = 1; i < targets.length; i += 2) {
        String prevTarget = targets[i - 1];
        String currTarget = targets[i];
        CompatibilityInfoMap infoMap = checker.check(prevTarget, currTarget, compat);
        result &= infoMap.isCompatible(compat);
        allSummaries.append(infoMap.createSummary(prevTarget, currTarget));

    }

    if (compat != CompatibilityLevel.OFF && allSummaries.length() > 0) {
        System.out.println(allSummaries);
    }

    System.exit(result ? 0 : 1);
}

From source file:com.linkedin.restli.tools.idlcheck.RestLiResourceModelCompatibilityChecker.java

public static void main(String[] args) {
    final Options options = new Options();
    options.addOption("h", "help", false, "Print help");
    options.addOption(OptionBuilder.withArgName("compatibility_level").withLongOpt("compat").hasArg()
            .withDescription("Compatibility level " + listCompatLevelOptions()).create('c'));
    options.addOption(OptionBuilder.withLongOpt("report").withDescription(
            "Prints a report at the end of the execution that can be parsed for reporting to other tools")
            .create("report"));
    final String cmdLineSyntax = RestLiResourceModelCompatibilityChecker.class.getCanonicalName()
            + " [pairs of <prevRestspecPath currRestspecPath>]";

    final CommandLineParser parser = new PosixParser();
    final CommandLine cmd;

    try {// w  ww . j  a  va  2 s. c om
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(255);
        return; // to suppress IDE warning
    }

    final String[] targets = cmd.getArgs();
    if (cmd.hasOption('h') || targets.length < 2 || targets.length % 2 != 0) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(255);
    }

    final String compatValue;
    if (cmd.hasOption('c')) {
        compatValue = cmd.getOptionValue('c');
    } else {
        compatValue = CompatibilityLevel.DEFAULT.name();
    }

    final CompatibilityLevel compat;
    try {
        compat = CompatibilityLevel.valueOf(compatValue.toUpperCase());
    } catch (IllegalArgumentException e) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(255);
        return;
    }

    final StringBuilder allSummaries = new StringBuilder();
    final RestLiResourceModelCompatibilityChecker checker = new RestLiResourceModelCompatibilityChecker();
    for (int i = 1; i < targets.length; i += 2) {
        checker.setResolverPath(System.getProperty(AbstractGenerator.GENERATOR_RESOLVER_PATH));

        String prevTarget = targets[i - 1];
        String currTarget = targets[i];
        checker.check(prevTarget, currTarget, compat);
    }

    allSummaries.append(checker.getInfoMap().createSummary());

    if (compat != CompatibilityLevel.OFF && allSummaries.length() > 0) {
        System.out.println(allSummaries);
    }

    if (cmd.hasOption("report")) {
        System.out.println(new CompatibilityReport(checker.getInfoMap(), compat).createReport());
        System.exit(0);
    }

    System.exit(checker.getInfoMap().isCompatible(compat) ? 0 : 1);
}

From source file:com.genentech.chemistry.openEye.apps.enumerate.SDFEnumerator.java

public static void main(String... args) throws IOException {
    Options options = new Options();
    Option opt = new Option("out", true, "output file oe-supported");
    opt.setRequired(true);//from   w  w  w.ja v  a2  s  .  c  om
    options.addOption(opt);

    opt = new Option("hydrogenExplicit", false, "Use explicit hydrogens");
    options.addOption(opt);

    opt = new Option("correctValences", false, "Correct valences after the enumeration");
    options.addOption(opt);

    opt = new Option("regenerate2D", false, "Regenerate 2D coordinates for the products");
    options.addOption(opt);

    opt = new Option("reactAllSites", false, "Generate a product for each match in a reagent.");
    options.addOption(opt);

    opt = new Option("randomFraction", true, "Only output a fraction of the products.");
    options.addOption(opt);

    opt = new Option("maxAtoms", true, "Only output products with <= maxAtoms.");
    options.addOption(opt);

    opt = new Option("notReacted", true,
            "Output file for reagents that didn't produce at leaste one output molecule, useful for debugging SMIRKS.");
    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 (args.length < 2) {
        exitWithHelp("Transformation and/or reagentFiles missing", options);
    }
    String smirks = args[0];
    if (new File(smirks).canRead())
        smirks = IOUtil.fileToString(smirks).trim();
    if (!smirks.contains(">>"))
        smirks = scaffoldToSmirks(smirks);
    String[] reagentSmiOrFiles = Arrays.copyOfRange(args, 1, args.length);

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

    String outFile = cmd.getOptionValue("out");
    OELibraryGen lg = new OELibraryGen();
    lg.Init(smirks);
    if (!lg.IsValid())
        exitWithHelp("Invalid Transform: " + smirks, options);

    lg.SetExplicitHydrogens(cmd.hasOption("hydrogenExplicit"));
    lg.SetValenceCorrection(cmd.hasOption("correctValences"));
    lg.SetRemoveUnmappedFragments(true);

    boolean regenerate2D = cmd.hasOption("regenerate2D");
    boolean reactAllSites = cmd.hasOption("reactAllSites");
    String unreactedFile = null;
    if (cmd.hasOption("notReacted")) {
        unreactedFile = cmd.getOptionValue("notReacted");
    }

    double randomFract = 2;
    if (cmd.hasOption("randomFraction"))
        randomFract = Double.parseDouble(cmd.getOptionValue("randomFraction"));

    int maxAtoms = 0;
    if (cmd.hasOption("maxAtoms"))
        maxAtoms = Integer.parseInt(cmd.getOptionValue("maxAtoms"));

    SDFEnumerator en = new SDFEnumerator(lg, reactAllSites, reagentSmiOrFiles);
    en.generateLibrary(outFile, maxAtoms, randomFract, regenerate2D, unreactedFile);
    en.delete();
}

From source file:com.genentech.chemistry.tool.mm.SDFMMMinimize.java

/**
 * Main function for running on the command line
 * @param args//from w  ww.j ava  2 s .c  om
 */
public static void main(String... args) throws IOException {
    // Get the available options from the programs
    Map<String, List<String>> allowedProgramsAndForceFields = getAllowedProgramsAndForceFields();
    Map<String, List<String>> allowedProgramsAndSolvents = getAllowedProgramsAndSolvents();

    // 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);

    StringBuilder programOptions = new StringBuilder("Program to use for minimization.  Choices are\n");

    for (String program : allowedProgramsAndForceFields.keySet()) {
        programOptions.append("\n***   -program " + program + "   ***\n");
        String forcefields = "";
        for (String option : allowedProgramsAndForceFields.get(program)) {
            forcefields += option + " ";
        }
        programOptions.append("-forcefield " + forcefields + "\n");

        String solvents = "";
        for (String option : allowedProgramsAndSolvents.get(program)) {
            solvents += option + " ";
        }
        programOptions.append("-solvent " + solvents + "\n");
    }

    opt = new Option(OPT_PROGRAM, true, programOptions.toString());
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_FORCEFIELD, true, "Forcefield options.  See -program for choices");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_SOLVENT, true, "Solvent options.  See -program for choices");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_FIXED_ATOM_TAG, true, "SD tag name which contains the atom numbers to be held fixed.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_FIX_TORSION, true,
            "true/false. if true, the atoms in fixedAtomTag contains 4 indices of atoms defining a torsion angle to be held fixed");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_WORKING_DIR, true, "Working directory to put files.");
    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 (args.length != 0) {
        System.err.println("Unknown arguments" + args);
        exitWithHelp(options);
    }

    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 fixedAtomTag = cmd.getOptionValue(OPT_FIXED_ATOM_TAG);
    boolean fixTorsion = (cmd.getOptionValue(OPT_FIX_TORSION) != null
            && cmd.getOptionValue(OPT_FIX_TORSION).equalsIgnoreCase("true"));
    String programName = cmd.getOptionValue(OPT_PROGRAM);
    String forcefield = cmd.getOptionValue(OPT_FORCEFIELD);
    String solvent = cmd.getOptionValue(OPT_SOLVENT);
    String workDir = cmd.getOptionValue(OPT_WORKING_DIR);

    if (workDir == null || workDir.trim().length() == 0)
        workDir = ".";

    // Create a minimizer 
    SDFMMMinimize minimizer = new SDFMMMinimize();
    minimizer.setMethod(programName, forcefield, solvent);
    minimizer.run(inFile, outFile, fixedAtomTag, fixTorsion, workDir);
    minimizer.close();
    System.err.println("Minimization complete.");
}

From source file:com.akana.demo.freemarker.templatetester.App.java

public static void main(String[] args) {

    final Options options = new Options();

    @SuppressWarnings("static-access")
    Option optionContentType = OptionBuilder.withArgName("content-type").hasArg()
            .withDescription("content type of model").create("content");
    @SuppressWarnings("static-access")
    Option optionUrlPath = OptionBuilder.withArgName("httpRequestLine").hasArg()
            .withDescription("url path and parameters in HTTP Request Line format").create("url");
    @SuppressWarnings("static-access")
    Option optionRootMessageName = OptionBuilder.withArgName("messageName").hasArg()
            .withDescription("root data object name, defaults to 'message'").create("root");
    @SuppressWarnings("static-access")
    Option optionAdditionalMessages = OptionBuilder.withArgName("dataModelPaths")
            .hasArgs(Option.UNLIMITED_VALUES).withDescription("additional message object data sources")
            .create("messages");
    @SuppressWarnings("static-access")
    Option optionDebugMessages = OptionBuilder.hasArg(false)
            .withDescription("Shows debug information about template processing").create("debug");

    Option optionHelp = new Option("help", "print this message");

    options.addOption(optionHelp);/*from  w  ww .j a  va2 s .  com*/
    options.addOption(optionContentType);
    options.addOption(optionUrlPath);
    options.addOption(optionRootMessageName);
    options.addOption(optionAdditionalMessages);
    options.addOption(optionDebugMessages);

    CommandLineParser parser = new DefaultParser();

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

        // Check for help flag
        if (cmd.hasOption("help")) {
            showHelp(options);
            return;
        }

        String[] remainingArguments = cmd.getArgs();
        if (remainingArguments.length < 2) {
            showHelp(options);
            return;
        }
        String ftlPath, dataPath = "none";

        ftlPath = remainingArguments[0];
        dataPath = remainingArguments[1];

        String contentType = "text/xml";
        // Discover content type from file extension
        String ext = FilenameUtils.getExtension(dataPath);
        if (ext.equals("json")) {
            contentType = "json";
        } else if (ext.equals("txt")) {
            contentType = "txt";
        }
        // Override discovered content type
        if (cmd.hasOption("content")) {
            contentType = cmd.getOptionValue("content");
        }
        // Root data model name
        String rootMessageName = "message";
        if (cmd.hasOption("root")) {
            rootMessageName = cmd.getOptionValue("root");
        }
        // Additional data models
        String[] additionalModels = new String[0];
        if (cmd.hasOption("messages")) {
            additionalModels = cmd.getOptionValues("messages");
        }
        // Debug Info
        if (cmd.hasOption("debug")) {
            System.out.println(" Processing ftl   : " + ftlPath);
            System.out.println("   with data model: " + dataPath);
            System.out.println(" with content-type: " + contentType);
            System.out.println(" data model object: " + rootMessageName);
            if (cmd.hasOption("messages")) {
                System.out.println("additional models: " + additionalModels.length);
            }
        }

        Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
        cfg.setDirectoryForTemplateLoading(new File("."));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        /* Create the primary data-model */
        Map<String, Object> message = new HashMap<String, Object>();
        if (contentType.contains("json") || contentType.contains("txt")) {
            message.put("contentAsString",
                    FileUtils.readFileToString(new File(dataPath), StandardCharsets.UTF_8));
        } else {
            message.put("contentAsXml", freemarker.ext.dom.NodeModel.parse(new File(dataPath)));
        }

        if (cmd.hasOption("url")) {
            message.put("getProperty", new AkanaGetProperty(cmd.getOptionValue("url")));
        }

        Map<String, Object> root = new HashMap<String, Object>();
        root.put(rootMessageName, message);
        if (additionalModels.length > 0) {
            for (int i = 0; i < additionalModels.length; i++) {
                Map<String, Object> m = createMessageFromFile(additionalModels[i], contentType);
                root.put("message" + i, m);
            }
        }

        /* Get the template (uses cache internally) */
        Template temp = cfg.getTemplate(ftlPath);

        /* Merge data-model with template */
        Writer out = new OutputStreamWriter(System.out);
        temp.process(root, out);

    } catch (ParseException e) {
        showHelp(options);
        System.exit(1);
    } catch (IOException e) {
        System.out.println("Unable to parse ftl.");
        e.printStackTrace();
    } catch (SAXException e) {
        System.out.println("XML parsing issue.");
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        System.out.println("Unable to configure parser.");
        e.printStackTrace();
    } catch (TemplateException e) {
        System.out.println("Unable to parse template.");
        e.printStackTrace();
    }

}

From source file:com.linkedin.restli.tools.snapshot.check.RestLiSnapshotCompatibilityChecker.java

public static void main(String[] args) {
    final Options options = new Options();
    options.addOption("h", "help", false, "Print help");
    options.addOption(OptionBuilder.withArgName("compatibility_level").withLongOpt("compat").hasArg()
            .withDescription("Compatibility level " + listCompatLevelOptions()).create('c'));
    options.addOption(OptionBuilder.withLongOpt("report").withDescription(
            "Prints a report at the end of the execution that can be parsed for reporting to other tools")
            .create("report"));
    final String cmdLineSyntax = RestLiSnapshotCompatibilityChecker.class.getCanonicalName()
            + " [pairs of <prevRestspecPath currRestspecPath>]";

    final CommandLineParser parser = new PosixParser();
    final CommandLine cmd;

    try {//from  w  w w .ja  v  a2 s . c  o  m
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(255);
        return; // to suppress IDE warning
    }

    final String[] targets = cmd.getArgs();
    if (cmd.hasOption('h') || targets.length < 2 || targets.length % 2 != 0) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(255);
    }

    final String compatValue;
    if (cmd.hasOption('c')) {
        compatValue = cmd.getOptionValue('c');
    } else {
        compatValue = CompatibilityLevel.DEFAULT.name();
    }

    final CompatibilityLevel compat;
    try {
        compat = CompatibilityLevel.valueOf(compatValue.toUpperCase());
    } catch (IllegalArgumentException e) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(255);
        return;
    }

    final String resolverPath = System.getProperty(AbstractGenerator.GENERATOR_RESOLVER_PATH);
    final RestLiSnapshotCompatibilityChecker checker = new RestLiSnapshotCompatibilityChecker();
    checker.setResolverPath(resolverPath);

    for (int i = 1; i < targets.length; i += 2) {
        String prevTarget = targets[i - 1];
        String currTarget = targets[i];
        checker.checkCompatibility(prevTarget, currTarget, compat, prevTarget.endsWith(".restspec.json"));
    }

    String summary = checker.getInfoMap().createSummary();

    if (compat != CompatibilityLevel.OFF && summary.length() > 0) {
        System.out.println(summary);
    }

    if (cmd.hasOption("report")) {
        System.out.println(new CompatibilityReport(checker.getInfoMap(), compat).createReport());
        System.exit(0);
    }

    System.exit(checker.getInfoMap().isCompatible(compat) ? 0 : 1);
}

From source file:com.opengamma.bbg.referencedata.cache.MongoDBReferenceDataCacheRefresher.java

/**
 * Runs the tool./*from   w  w w.  j  a  v  a2 s  .  co  m*/
 * 
 * @param args  empty arguments
 * @throws Exception 
 */
public static void main(final String[] args) throws Exception { // CSIGNORE
    PlatformConfigUtils.configureSystemProperties();
    System.out.println("Starting connections");
    String configLocation = "com/opengamma/bbg/bbg-reference-data-context.xml";

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(configLocation);
    try {
        context.start();
        MongoDBValueCachingReferenceDataProvider mongoProvider = context
                .getBean("bloombergReferenceDataProvider", MongoDBValueCachingReferenceDataProvider.class);
        MongoDBReferenceDataCacheRefresher refresher = new MongoDBReferenceDataCacheRefresher(mongoProvider);

        Options options = createOptions();
        CommandLineParser parser = new PosixParser();
        CommandLine line = null;
        try {
            line = parser.parse(options, args);
        } catch (ParseException e) {
            usage(options);
            return;
        }
        if (line.hasOption(HELP_OPTION)) {
            usage(options);
            return;
        }

        //TODO other options, e.g. explicitly specify security 
        int numberOfSecurities = Integer.parseInt(line.getArgs()[0]);
        int id = Integer.parseInt(line.getArgs()[1]);
        System.out.println("Refreshing " + numberOfSecurities + " securities, id " + id);
        refresher.refreshCaches(numberOfSecurities, id);
        System.out.println("Done refreshing");
    } catch (Exception ex) {
        context.close();
        throw ex;
    }
}

From source file:com.github.trohovsky.just.Main.java

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

    // parsing of command line
    final CommandLineParser parser = new GnuParser();

    final Options options = new Options();
    options.addOption("ai", true, "prefixes of classes from artifacts that will be included");
    options.addOption("ae", true, "prefixes of classes from artifacts that will be excluded");
    options.addOption("di", true, "prefixes of classes from dependencies that will be included");
    options.addOption("de", true, "prefixes of classes from dependencies that will be excluded");
    options.addOption("f", "flatten", false, "flatten report, display only used classes");
    options.addOption("p", "packages", false, "display package names instead of class names");
    options.addOption("u", "unused", false, "display unused classes from dependencies");
    options.addOption("h", "help", false, "print this help");

    CommandLine cmdLine = null;
    try {//w  ww .  j  a v a 2 s . c  o  m
        cmdLine = parser.parse(options, args);
        if (cmdLine.hasOption('h')) {
            final HelpFormatter formatter = new HelpFormatter();
            formatter.setOptionComparator(null);
            formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, HELP_FOOTER);
            return;
        }
        if (cmdLine.getArgs().length == 0) {
            throw new ParseException("Missing ARTIFACT and/or DEPENDENCY.");
        } else if (cmdLine.getArgs().length > 2) {
            throw new ParseException(
                    "More that two arquments found, multiple ARTIFACTs DEPENDENCies should be separated by ','"
                            + " without whitespaces.");
        }

    } catch (ParseException e) {
        System.err.println("Error parsing command line: " + e.getMessage());
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, HELP_FOOTER);
        return;
    }

    // obtaining of values
    final String[] artifactPaths = cmdLine.getArgs()[0].split(",");
    final String[] dependencyPaths = cmdLine.getArgs().length == 2 ? cmdLine.getArgs()[1].split(",") : null;
    final String[] artifactIncludes = splitValues(cmdLine.getOptionValue("ai"));
    final String[] artifactExcludes = splitValues(cmdLine.getOptionValue("ae"));
    final String[] dependencyIncludes = splitValues(cmdLine.getOptionValue("di"));
    final String[] dependencyExcludes = splitValues(cmdLine.getOptionValue("de"));

    // validation of values
    if (dependencyPaths == null) {
        if (dependencyIncludes != null) {
            System.err.println("At least one dependency has to be specified to use option -di");
            return;
        }
        if (dependencyExcludes != null) {
            System.err.println("At least one dependency has to be specified to use option -de");
            return;
        }
        if (cmdLine.hasOption('u')) {
            System.err.println("At least one dependency has to be specified to use option -u");
            return;
        }
    }

    // execution
    Set<String> externalClasses = null;
    if (dependencyPaths != null) {
        externalClasses = Reader.from(dependencyPaths).includes(dependencyIncludes).excludes(dependencyExcludes)
                .listClasses();
    }

    if (cmdLine.hasOption('f') || cmdLine.hasOption('u')) {
        Set<String> dependencies = Reader.from(artifactPaths).includes(artifactIncludes)
                .excludes(artifactExcludes).readDependencies();
        if (externalClasses != null) {
            dependencies = DependencyUtils.intersection(dependencies, externalClasses);
            if (cmdLine.hasOption('u')) {
                dependencies = DependencyUtils.subtract(externalClasses, dependencies);
            }
        }
        if (cmdLine.hasOption('p')) {
            dependencies = DependencyUtils.toPackageNames(dependencies);
        }
        Reporter.report(dependencies);
    } else {
        Map<String, Set<String>> classesWithDependencies = Reader.from(artifactPaths).includes(artifactIncludes)
                .excludes(artifactExcludes).readClassesWithDependencies();
        if (externalClasses != null) {
            classesWithDependencies = DependencyUtils.intersection(classesWithDependencies, externalClasses);
        }
        if (cmdLine.hasOption('p')) {
            classesWithDependencies = DependencyUtils.toPackageNames(classesWithDependencies);
        }
        Reporter.report(classesWithDependencies);
    }
}

From source file:microbiosima.SelectiveMicrobiosima.java

/**
 * @param args// w  ww . ja  v a 2 s . co  m
 *            the command line arguments
 * @throws java.io.FileNotFoundException
 * @throws java.io.UnsupportedEncodingException
 */

public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
    int populationSize = 500;//Integer.parseInt(parameters[1]);
    int microSize = 1000;//Integer.parseInt(parameters[2]);
    int numberOfSpecies = 150;//Integer.parseInt(parameters[3]);
    int numberOfGeneration = 10000;
    int Ngene = 10;
    int numberOfObservation = 100;
    int numberOfReplication = 10;
    double Ngenepm = 5;
    double pctEnv = 0;
    double pctPool = 0;
    double msCoeff = 1;
    double hsCoeff = 1;
    boolean HMS_or_TMS = true;

    Options options = new Options();

    Option help = new Option("h", "help", false, "print this message");
    Option version = new Option("v", "version", false, "print the version information and exit");
    options.addOption(help);
    options.addOption(version);

    options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS")
            .desc("Number generation for observation [default: 100]").build());
    options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP")
            .desc("Number of replication [default: 1]").build());

    Builder C = Option.builder("c").longOpt("config").numberOfArgs(6).argName("Pop Micro Spec Gen")
            .desc("Four Parameters in the following orders: "
                    + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation, (5) number of total traits, (6)number of traits per microbe"
                    + " [default: 500 1000 150 10000 10 5]");
    options.addOption(C.build());

    HelpFormatter formatter = new HelpFormatter();
    String syntax = "microbiosima pctEnv pctPool";
    String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n"
            + "required arguments:\n" + "  pctEnv             Percentage of environmental acquisition\n"
            + "  pctPool            Percentage of pooled environmental component\n"
            + "  msCoeff            Parameter related to microbe selection strength\n"
            + "  hsCoeff            Parameter related to host selection strength\n"
            + "  HMS_or_TMS         String HMS or TMS to specify host-mediated or trait-mediated microbe selection\n"
            + "\noptional arguments:\n";
    String footer = "\n";

    formatter.setWidth(80);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
        String[] pct_config = cmd.getArgs();

        if (cmd.hasOption("h") || args.length == 0) {
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(0);
        }
        if (cmd.hasOption("v")) {
            System.out.println("Microbiosima " + VERSION);
            System.exit(0);
        }
        if (pct_config.length != 5) {
            System.out.println(
                    "ERROR! Required exactly five argumennts for pct_env, pct_pool, msCoeff, hsCoeff and HMS_or_TMS. It got "
                            + pct_config.length + ": " + Arrays.toString(pct_config));
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(3);
        } else {
            pctEnv = Double.parseDouble(pct_config[0]);
            pctPool = Double.parseDouble(pct_config[1]);
            msCoeff = Double.parseDouble(pct_config[2]);
            hsCoeff = Double.parseDouble(pct_config[3]);
            if (pct_config[4].equals("HMS"))
                HMS_or_TMS = true;
            if (pct_config[4].equals("TMS"))
                HMS_or_TMS = false;
            if (pctEnv < 0 || pctEnv > 1) {
                System.out.println(
                        "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv="
                                + pctEnv + ")! EXIT");
                System.exit(3);
            }
            if (pctPool < 0 || pctPool > 1) {
                System.out.println(
                        "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool="
                                + pctPool + ")! EXIT");
                System.exit(3);
            }
            if (msCoeff < 1) {
                System.out.println(
                        "ERROR: msCoeff (parameter related to microbe selection strength) must be not less than 1 (msCoeff="
                                + msCoeff + ")! EXIT");
                System.exit(3);
            }
            if (hsCoeff < 1) {
                System.out.println(
                        "ERROR: hsCoeff (parameter related to host selection strength) must be not less than 1 (hsCoeff="
                                + hsCoeff + ")! EXIT");
                System.exit(3);
            }
            if (!(pct_config[4].equals("HMS") || pct_config[4].equals("TMS"))) {
                System.out.println(
                        "ERROR: HMS_or_TMS (parameter specifying host-mediated or trait-mediated selection) must be either 'HMS' or 'TMS' (HMS_or_TMS="
                                + pct_config[4] + ")! EXIT");
                System.exit(3);
            }

        }
        if (cmd.hasOption("config")) {
            String[] configs = cmd.getOptionValues("config");
            populationSize = Integer.parseInt(configs[0]);
            microSize = Integer.parseInt(configs[1]);
            numberOfSpecies = Integer.parseInt(configs[2]);
            numberOfGeneration = Integer.parseInt(configs[3]);
            Ngene = Integer.parseInt(configs[4]);
            Ngenepm = Double.parseDouble(configs[5]);
            if (Ngenepm > Ngene) {
                System.out.println(
                        "ERROR: number of traits per microbe must not be greater than number of total traits! EXIT");
                System.exit(3);
            }
        }
        if (cmd.hasOption("obs")) {
            numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs"));
        }
        if (cmd.hasOption("rep")) {
            numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep"));
        }

    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(3);
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize)
            .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ")
            .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration)
            .append("\n\tNumber generation for observation: ").append(numberOfObservation)
            .append("\n\tNumber of replication: ").append(numberOfReplication)
            .append("\n\tNumber of total traits: ").append(Ngene).append("\n\tNumber of traits per microbe: ")
            .append(Ngenepm).append("\n");
    System.out.println(sb.toString());

    double[] environment = new double[numberOfSpecies];
    for (int i = 0; i < numberOfSpecies; i++) {
        environment[i] = 1 / (double) numberOfSpecies;
    }
    int[] fitnessToHost = new int[Ngene];
    int[] fitnessToMicrobe = new int[Ngene];

    for (int rep = 0; rep < numberOfReplication; rep++) {
        String prefix = "" + (rep + 1) + "_";
        String sufix;
        if (HMS_or_TMS)
            sufix = "_E" + pctEnv + "_P" + pctPool + "_HS" + hsCoeff + "_HMS" + msCoeff + ".txt";
        else
            sufix = "_E" + pctEnv + "_P" + pctPool + "_HS" + hsCoeff + "_TMS" + msCoeff + ".txt";
        System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix);
        try {
            PrintWriter file1 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix)));
            PrintWriter file2 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix)));
            PrintWriter file3 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix)));
            PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix)));
            PrintWriter file5 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix)));
            PrintWriter file6 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix)));
            PrintWriter file7 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "host_fitness" + sufix)));
            PrintWriter file8 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "cos_theta" + sufix)));
            PrintWriter file9 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "host_fitness_distribution" + sufix)));
            PrintWriter file10 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "microbiome_fitness_distribution" + sufix)));
            PrintWriter file11 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "bacteria_contents" + sufix)));
            PrintWriter file12 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "individual_bacteria_contents" + sufix)));
            for (int i = 0; i < Ngene; i++) {
                fitnessToMicrobe[i] = MathUtil.getNextInt(2) - 1;
                fitnessToHost[i] = MathUtil.getNextInt(2) - 1;
            }
            MathUtil.setSeed(rep % numberOfReplication);
            SelectiveSpeciesRegistry ssr = new SelectiveSpeciesRegistry(numberOfSpecies, Ngene, Ngenepm,
                    msCoeff, fitnessToHost, fitnessToMicrobe);
            MathUtil.setSeed();
            SelectivePopulation population = new SelectivePopulation(microSize, environment, populationSize,
                    pctEnv, pctPool, 0, 0, ssr, hsCoeff, HMS_or_TMS);

            while (population.getNumberOfGeneration() < numberOfGeneration) {
                population.sumSpecies();
                if (population.getNumberOfGeneration() % numberOfObservation == 0) {
                    //file1.print(population.gammaDiversity(false));
                    //file2.print(population.alphaDiversity(false));
                    //file1.print("\t");
                    //file2.print("\t");
                    file1.println(population.gammaDiversity(true));
                    file2.println(population.alphaDiversity(true));
                    //file3.print(population.betaDiversity(true));
                    //file3.print("\t");
                    file3.println(population.BrayCurtis(true));
                    file4.println(population.printOut());
                    file5.println(population.interGenerationDistance());
                    file6.println(population.environmentPopulationDistance());
                    file7.print(population.averageHostFitness());
                    file7.print("\t");
                    file7.println(population.varianceHostFitness());
                    file8.println(population.cosOfMH());
                    file9.println(population.printOutHFitness());
                    file10.println(population.printOutMFitness());
                    file11.println(population.printBacteriaContents());
                }
                population.getNextGen();
            }
            for (SelectiveIndividual host : population.getIndividuals()) {
                file12.println(host.printBacteriaContents());
            }
            file1.close();
            file2.close();
            file3.close();
            file4.close();
            file5.close();
            file6.close();
            file7.close();
            file8.close();
            file9.close();
            file10.close();
            file11.close();
            file12.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}