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

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

Introduction

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

Prototype

public void setArgs(int num) 

Source Link

Document

Sets the number of argument values this Option can take.

Usage

From source file:pt.ua.tm.gimli.writer.JNLPBAWriter.java

/**
 * Main program annotate a corpus using one or several models, and save the
 * result in the JNLPBA format./*  w w  w  . java 2 s.com*/
 * @param args Command line arguments.
 */
public static void main(String[] args) {
    // Start stopwatch
    StopWatch watch = new StopWatch();
    watch.start();

    CommandLineParser parser = new GnuParser();
    Options options = new Options();
    options.addOption("h", "help", false, "Print this usage information.");

    options.addOption("c", "corpus", true, "File with the corpus in the CoNNL format.");

    Option o = new Option("m", "model", true, MODEL_HELP);
    o.setArgs(Integer.MAX_VALUE);

    options.addOption(o);

    options.addOption("o", "output", true, "File to save the annotated corpus.");
    CommandLine commandLine = null;
    try {
        // Parse the program arguments
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        logger.error("There was a problem processing the input arguments.", ex);
        return;
    }

    // Show help text
    if (commandLine.hasOption('h')) {
        printHelp(options, "");
        return;
    }

    // Get corpus
    String corpus = null;
    if (commandLine.hasOption('c')) {
        corpus = commandLine.getOptionValue('c');
    } else {
        printHelp(options, "Please specify the corpus file.");
        return;
    }

    // Get models
    String[] input = null;
    if (commandLine.hasOption('m')) {
        input = commandLine.getOptionValues('m');
    } else {
        printHelp(options, "Please specify the models.");
        return;
    }

    // Parse models characteristics
    String[] models = new String[input.length];
    EntityType[] entities = new EntityType[input.length];
    String[] features = new String[input.length];
    Parsing[] parsing = new Parsing[input.length];

    String[] strs;
    for (int i = 0; i < input.length; i++) {
        strs = input[i].split(",");

        if (strs.length != 4) {
            printHelp(options, "Wrong input format for models.");
            return;
        }

        models[i] = strs[0].trim();
        entities[i] = EntityType.valueOf(strs[1].trim());
        parsing[i] = Parsing.valueOf(strs[2].trim().toUpperCase());
        features[i] = strs[3].trim();
    }

    // Get output
    String output = null;
    if (commandLine.hasOption('o')) {
        output = commandLine.getOptionValue('o');
    } else {
        printHelp(options, "Please specify the output file.");
        return;
    }

    // Check length consistency
    if ((features.length != models.length) || (features.length != entities.length)
            || (features.length != parsing.length)) {
        logger.error(
                "The number of feature files, parsing, entities and models are different from each other.");
        return;
    }

    // Give feedback
    logger.info("Corpus: {}", corpus);
    logger.info("Models:");
    for (int i = 0; i < models.length; i++) {
        logger.info("\t{}: {}, {}, {}, {}",
                new Object[] { i + 1, models[i], entities[i], features[i], parsing[i] });
    }
    logger.info("Output: {}", output);

    // Load model configurations
    ModelConfig[] mc = new ModelConfig[features.length];
    for (int i = 0; i < features.length; i++) {
        mc[i] = new ModelConfig(features[i]);
    }

    // Get unique entities
    ArrayList<EntityType> uniqueEntities = new ArrayList<EntityType>();
    for (int i = 0; i < entities.length; i++) {
        if (!uniqueEntities.contains(entities[i])) {
            uniqueEntities.add(entities[i]);
        }
    }

    // Load Corpus
    Corpus[] c = new Corpus[uniqueEntities.size()];
    try {
        for (int i = 0; i < uniqueEntities.size(); i++) {
            c[i] = new Corpus(LabelFormat.BIO, uniqueEntities.get(i), corpus);
        }
    } catch (GimliException ex) {
        logger.error("There was a problem loading the corpus.", ex);
        return;
    }

    // Combine models of the same entity
    for (int j = 0; j < uniqueEntities.size(); j++) {
        ArrayList<CRFModel> crfmodels = new ArrayList<CRFModel>();

        try {
            for (int i = 0; i < entities.length; i++) {
                if (entities[i].equals(uniqueEntities.get(j))) {
                    crfmodels.add(new CRFModel(mc[i], parsing[i], models[i]));
                }
            }
        } catch (GimliException ex) {
            logger.error("There was a problem loading a model.", ex);
            return;
        }

        Annotator a = new Annotator(c[j]);
        if (crfmodels.size() > 1) {

            logger.info("Annotating the corpus by combining {} models for {}...", crfmodels.size(),
                    uniqueEntities.get(j));
            a.annotate(crfmodels.toArray(new CRFModel[0]));
        } else {
            logger.info("Annotating the corpus using 1 model for {}...", uniqueEntities.get(j));
            a.annotate(crfmodels.get(0));
        }
    }

    // Post-processing
    for (int i = 0; i < c.length; i++) {
        Parentheses.processRemoving(c[i]);
        Abbreviation.process(c[i]);
    }

    // Write annotations to file
    logger.info("Writing the corpus in the JNLPBA format...");
    JNLPBAWriter writer = new JNLPBAWriter();

    try {
        if (c.length > 1) {
            //Annotator.writeJNLPBACombined(c, output);
            writer.write(c, output);
        } else {
            writer.write(c[0], output);
            //Annotator.writeJNLPBA(c[0], output);
        }
    } catch (GimliException ex) {
        logger.error("There was a problem writing the corpus to file.", ex);
        return;
    }

    // Time feedback
    watch.stop();
    logger.info("Done!");
    logger.info("Total time: {}", watch.toString());

    double time = (double) watch.getTime();
    double size = (double) c[0].size();

    double perSentence = time / size;
    double perAbstract = time / (size / 10.0);
    double perHundred = time / (size / 100.0);

    logger.info("Per sentence: {} seconds", String.format("%2.4f", perSentence / 1000.0));
    logger.info("Per abstract: {} seconds", String.format("%2.4f", perAbstract / 1000.0));
    logger.info("10 abstracts: {} seconds", String.format("%2.4f", perHundred / 1000.0));
}

From source file:pt.ua.tm.neji.cli.Main.java

public static void main(String[] args) {
    //        installUncaughtExceptionHandler();

    int NUM_THREADS = Runtime.getRuntime().availableProcessors() - 1;
    NUM_THREADS = NUM_THREADS > 0 ? NUM_THREADS : 1;

    CommandLineParser parser = new GnuParser();
    Options options = new Options();
    options.addOption("h", "help", false, "Print this usage information.");

    options.addOption("i", "input", true, "Folder with corpus files.");
    options.addOption("o", "output", true, "Folder to save the annotated corpus files.");
    options.addOption("f", "input-filter", true, "Wildcard to filter files in input folder");

    options.addOption("p", "parser", true, "Folder that contains the parsing tool.");

    Option o = new Option("m", "models", true, "Folder that contains the ML models.");
    o.setArgs(Integer.MAX_VALUE);
    options.addOption(o);/*from   w  w w . j  a v a2s .  co  m*/

    options.addOption("d", "dictionaires", true, "Folder that contains the dictionaries.");

    options.addOption("if", "input-format", true, "BIOC, RAW or XML");
    o = new Option("of", "output-formats", true, "A1, B64, BIOC, CONLL, JSON, NEJI or XML");
    o.setArgs(Integer.MAX_VALUE);
    options.addOption(o);

    options.addOption("ptool", "parsing-tool", true, "GDEP or OPENNLP (GDEP is set by default)");

    options.addOption("plang", "parsing-language", true,
            "DANISH, DUTCH, ENGLISH, FRENCH, GERMAN, PORTUGUESE or SWEDISH (ENGLISH is set by default)");

    options.addOption("plvl", "parsing-level", true,
            "TOKENIZATION, POS, LEMMATIZATION, CHUNKING or DEPENDENCY (TOKENIZATION is set by default)");

    options.addOption("pcls", "processor-class", true, "Full name of pipeline processor class.");

    options.addOption("custom", "custom-modules", true,
            "Names of custom modules to be used in order, separated by pipes. If a specified module are not a reader or a writer, it will be executed after dictionary and model processing.");

    options.addOption("x", "xml-tags", true, "XML tags to be considered, separated by commas.");

    options.addOption("v", "verbose", false, "Verbose mode.");
    options.addOption("s", "server", false, "Generate server.");
    options.addOption("c", "compressed", false, "If files are compressed using GZip.");
    options.addOption("noids", "include-no-ids", false, "If annotations without IDs should be included.");
    options.addOption("t", "threads", true,
            "Number of threads. By default, if more than one core is available, it is the number of cores minus 1.");

    options.addOption("fp", "false-positives-filter", true, "File that contains the false positive terms.");
    options.addOption("gn", "semantic-groups-normalization", true,
            "File that contains the semantic groups normalization terms.");

    CommandLine commandLine = null;
    try {
        // Parse the program arguments
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        logger.error("There was a problem processing the input arguments.", ex);
        return;
    }

    // Show help text
    if (commandLine.hasOption('h')) {
        printHelp(options, "");
        return;
    }

    // No options
    if (commandLine.getOptions().length == 0) {
        printHelp(options, "");
        return;
    }

    // Generate server from dictionary, model and parser parameters
    boolean generateServer = false;
    if (commandLine.hasOption('s')) {
        generateServer = true;
    }

    // Get corpus folder for input
    String folderCorpusIn = null;
    if (commandLine.hasOption('i')) {
        folderCorpusIn = commandLine.getOptionValue('i');
        File test = new File(folderCorpusIn);
        if (!test.isDirectory() || !test.canRead()) {
            logger.error("The specified path is not a folder or is not readable.");
            return;
        }
        folderCorpusIn = test.getAbsolutePath();
        folderCorpusIn += File.separator;
    } else {
        printHelp(options, "Please specify the input corpus folder.");
        return;
    }

    String inputFolderWildcard = null;
    if (commandLine.hasOption("f")) {
        inputFolderWildcard = commandLine.getOptionValue("f");
    }

    // Get Input format
    InputFormat inputFormat;
    if (commandLine.hasOption("if")) {
        inputFormat = InputFormat.valueOf(commandLine.getOptionValue("if"));
    } else {
        printHelp(options, "Please specify the input format.");
        return;
    }

    // Get corpus folder for output
    String folderCorpusOut = null;
    if (commandLine.hasOption('o')) {
        folderCorpusOut = commandLine.getOptionValue('o');
        File test = new File(folderCorpusOut);
        if (!test.isDirectory() || !test.canWrite()) {
            logger.error("The specified path is not a folder or is not writable.");
            return;
        }
        folderCorpusOut = test.getAbsolutePath();
        folderCorpusOut += File.separator;
    } else {
        printHelp(options, "Please specify the output corpus folder.");
        return;
    }

    // Get Output format
    List<OutputFormat> outputFormats = new ArrayList<>();
    if (commandLine.hasOption("of")) {
        String[] command = commandLine.getOptionValues("of");
        for (String s : command) {
            OutputFormat f = OutputFormat.valueOf(s);
            if (f.equals(OutputFormat.A1) || f.equals(OutputFormat.JSON) || f.equals(OutputFormat.NEJI)) {
                if (inputFormat.equals(InputFormat.XML)) {
                    logger.error("XML input format only supports XML and CoNLL output formats, "
                            + "since other formats are based on character positions.");
                    return;
                }
            }
            outputFormats.add(f);
        }
    } else {
        printHelp(options, "Please specify the output formats (in case of multiple formats, "
                + "separate them with a \"\\|\").");
        return;
    }

    // Get XML tags
    String[] xmlTags = null;
    if (inputFormat.equals(InputFormat.XML)) {
        if (commandLine.hasOption("x")) {
            xmlTags = commandLine.getOptionValue("x").split(",");
        } else {
            printHelp(options, "Please specify XML tags to be used.");
            return;
        }
    }

    // Get models folder
    String modelsFolder = null;
    if (commandLine.hasOption('m')) {
        modelsFolder = commandLine.getOptionValue('m');

        File test = new File(modelsFolder);
        if (!test.isDirectory() || !test.canRead()) {
            logger.error("The specified models path is not a folder or is not readable.");
            return;
        }
        modelsFolder = test.getAbsolutePath();
        modelsFolder += File.separator;
    }

    // Get dictionaries folder
    String dictionariesFolder = null;
    if (commandLine.hasOption('d')) {
        dictionariesFolder = commandLine.getOptionValue('d');

        File test = new File(dictionariesFolder);
        if (!test.isDirectory() || !test.canRead()) {
            logger.error("The specified dictionaries path is not a folder or is not readable.");
            return;
        }
        dictionariesFolder = test.getAbsolutePath();
        dictionariesFolder += File.separator;
    }

    // Get parser folder
    String parserFolder = null;
    if (commandLine.hasOption("p")) {
        parserFolder = commandLine.getOptionValue("p");

        File test = new File(parserFolder);
        if (!test.isDirectory() || !test.canRead()) {
            logger.error("The specified parser path is not a folder or is not readable.");
            return;
        }
        parserFolder = test.getAbsolutePath();
        parserFolder += File.separator;
    }

    // Get processing modules
    String modulesCommandLine = "";
    if (commandLine.hasOption("custom")) {
        modulesCommandLine = commandLine.getOptionValue("custom");
    }

    // Get verbose mode
    boolean verbose = commandLine.hasOption('v');
    Constants.verbose = verbose;

    if (Constants.verbose) {
        MalletLogger.getGlobal().setLevel(Level.INFO);
        // Redirect sout
        LoggingOutputStream los = new LoggingOutputStream(LoggerFactory.getLogger("stdout"), false);
        System.setOut(new PrintStream(los, true));

        // Redirect serr
        los = new LoggingOutputStream(LoggerFactory.getLogger("sterr"), true);
        System.setErr(new PrintStream(los, true));
    } else {
        MalletLogger.getGlobal().setLevel(Level.OFF);
    }

    // Redirect JUL to SLF4
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();

    // Get compressed mode
    boolean compressed = false;
    if (commandLine.hasOption('c')) {
        compressed = true;
    }

    // Get threads
    String threadsText = null;
    if (commandLine.hasOption('t')) {
        threadsText = commandLine.getOptionValue('t');
        NUM_THREADS = Integer.parseInt(threadsText);
        if (NUM_THREADS <= 0 || NUM_THREADS > 32) {
            logger.error("Illegal number of threads. Must be between 1 and 32.");
            return;
        }
    }

    // Load pipeline processor
    Class processor = FileProcessor.class;
    if (commandLine.hasOption("pcls")) {
        String processorName = commandLine.getOptionValue("pcls");
        try {
            processor = Class.forName(processorName);
        } catch (ClassNotFoundException ex) {
            logger.error("Could not load pipeline processor \"" + processorName + "\"");
            return;
        }
    }

    // Load parsing tool
    ParserTool parsingTool = ParserTool.GDEP;
    if (commandLine.hasOption("ptool")) {
        String parsingToolName = commandLine.getOptionValue("ptool");
        try {
            parsingTool = ParserTool.valueOf(parsingToolName);
        } catch (IllegalArgumentException ex) {
            logger.error("Invalid parsing tool \"" + parsingToolName + "\". " + "Must be one of "
                    + StringUtils.join(ParserTool.values(), ", "));
            return;
        }
    }

    // Load parsing language
    ParserLanguage parsingLanguage = ParserLanguage.ENGLISH;
    if (commandLine.hasOption("plang")) {
        String parsingLanguageName = commandLine.getOptionValue("plang");
        try {
            parsingLanguage = ParserLanguage.valueOf(parsingLanguageName);
        } catch (IllegalArgumentException ex) {
            logger.error("Invalid parsing language \"" + parsingLanguageName + "\". " + "Must be one of "
                    + StringUtils.join(ParserLanguage.values(), ", "));
            return;
        }
    }

    // Load parsing level
    ParserLevel parsingLevel = ParserLevel.TOKENIZATION;
    if (commandLine.hasOption("plvl")) {
        String parsingLevelName = commandLine.getOptionValue("plvl");
        try {
            parsingLevel = ParserLevel.valueOf(parsingLevelName);
        } catch (IllegalArgumentException ex) {
            logger.error("Invalid parsing level \"" + parsingLevelName + "\". " + "Must be one of "
                    + StringUtils.join(ParserLevel.values(), ", "));
            return;
        }
    } else {
        // Set model parsing level if ML will be used to annotate and no parsing level has been setted
        if (modelsFolder != null) {
            try {
                parsingLevel = getModelsParsingLevel(modelsFolder);
            } catch (NejiException ex) {
                logger.error("Could not load models parsing level.");
                return;
            }
        }
    }

    // Get if annotations without ids should be included
    boolean includeAnnotationsWithoutIDs = false;
    if (commandLine.hasOption("noids")) {
        includeAnnotationsWithoutIDs = true;
    }

    // Get false positives filter
    byte[] fpByteArray = null;
    if (commandLine.hasOption("fp")) {
        String fpPath = commandLine.getOptionValue("fp");

        File test = new File(fpPath);
        if (!test.isFile() || !test.canRead()) {
            logger.error("The specified false positives path is not a file or is not readable.");
            return;
        }

        fpPath = test.getAbsolutePath();
        fpPath += File.separator;
        try {
            fpByteArray = IOUtils.toByteArray(new FileInputStream(new File(fpPath)));
        } catch (IOException ex) {
            logger.error("There was a problem loading the false positives " + "file.", ex);
            return;
        }
    }

    // Get semantic groups normalization
    byte[] groupsNormByteArray = null;
    if (commandLine.hasOption("gn")) {
        String gnPath = commandLine.getOptionValue("gn");

        File test = new File(gnPath);
        if (!test.isFile() || !test.canRead()) {
            logger.error(
                    "The specified semantic groups normalization path " + "is not a file or is not readable.");
            return;
        }

        gnPath = test.getAbsolutePath();
        gnPath += File.separator;
        try {
            groupsNormByteArray = IOUtils.toByteArray(new FileInputStream(new File(gnPath)));
        } catch (IOException ex) {
            logger.error("There was a problem loading the semantic groups " + "normalization file.", ex);
            return;
        }
    }

    // Context is built through a descriptor first, so that the pipeline can be validated before any processing
    ContextConfiguration descriptor = null;
    try {
        descriptor = new ContextConfiguration.Builder().withInputFormat(inputFormat)
                .withOutputFormats(outputFormats).withParserTool(parsingTool)
                .withParserLanguage(parsingLanguage).withParserLevel(parsingLevel).parseCLI(modulesCommandLine)
                .build();

        descriptor.setFalsePositives(fpByteArray);
        descriptor.setSemanticGroupsNormalization(groupsNormByteArray);
    } catch (NejiException ex) {
        ex.printStackTrace();
        System.exit(1);
    }

    if (generateServer) {
        try {
            generateServer(descriptor, modelsFolder, dictionariesFolder, includeAnnotationsWithoutIDs);

        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(1);
        }
    } else {
        boolean storeDocuments = false;

        Context context = new Context(descriptor, modelsFolder, // Models
                dictionariesFolder, // Dictionaries folder
                parserFolder // Parser folder
        );

        try {
            BatchExecutor batchExecutor = new FileBatchExecutor(folderCorpusIn, folderCorpusOut, compressed,
                    NUM_THREADS, inputFolderWildcard, storeDocuments, includeAnnotationsWithoutIDs);

            if (xmlTags == null) {
                batchExecutor.run(processor, context);
            } else {
                batchExecutor.run(processor, context, new Object[] { xmlTags });
            }

        } catch (Exception ex) {
            logger.error("There was a problem running the batch.", ex);
        }
    }
}

From source file:pt.ua.tm.neji.evaluation.EvaluateMain.java

public static void main(String... args) {
    boolean performExactChunks = false, performLeftChunks = false, performRightChunks = false,
            performSharedChunks = false, performOverlapChunks = false, performExactAnn = false,
            performLeftAnn = false, performRightAnn = false, performSharedAnn = false,
            performOverlapAnn = false;// w  w w  . j a v a2  s  .  com

    CommandLineParser parser = new GnuParser();
    Options mainOptions = new Options();
    mainOptions.addOption("h", "help", false, "Print this usage information.");

    mainOptions.addOption("g", "gold", true, "Folder with gold files.");
    mainOptions.addOption("s", "silver", true, "Folder with silver files.");
    mainOptions.addOption("gf", "gold-filter", true, "Wildcard to filter files in gold folder");
    mainOptions.addOption("sf", "silver-filter", true, "Wildcard to filter files in silver folder");
    mainOptions.addOption("m", "mappers", true, "Folder with mapper files.");

    int numOfAvailableTests = TestType.values().length;
    Option o = new Option("tnorm", "test-normalization", true, "Set identifiers evaluations.");
    o.setArgs(numOfAvailableTests);
    mainOptions.addOption(o);
    o = new Option("tner", "test-ner", true, "Set chunk evaluations.");
    o.setArgs(numOfAvailableTests);
    mainOptions.addOption(o);

    CommandLine commandLine;
    try {
        // Parse the program arguments
        commandLine = parser.parse(mainOptions, args);
    } catch (ParseException ex) {
        logger.error("There was a problem processing the input arguments.", ex);
        return;
    }

    // Show help text
    if (commandLine.hasOption('h') || commandLine.getOptions().length == 0) {
        printHelp(mainOptions, "");
        return;
    }

    // Get gold folder
    String goldFolderPath;
    if (commandLine.hasOption('g')) {
        goldFolderPath = commandLine.getOptionValue('g');
    } else {
        printHelp(mainOptions, "Please specify the gold folder.");
        return;
    }

    File goldFolder = new File(goldFolderPath);
    if (!goldFolder.isDirectory() || !goldFolder.canRead()) {
        logger.error("The specified path is not a folder or is not readable.");
        return;
    }

    // Get gold folder filter
    String goldFolderWildcard = null;
    if (commandLine.hasOption("gf")) {
        goldFolderWildcard = commandLine.getOptionValue("gf");
    }

    // Get silver folder
    String silverFolderPath;
    if (commandLine.hasOption('s')) {
        silverFolderPath = commandLine.getOptionValue('s');
    } else {
        printHelp(mainOptions, "Please specify the silver folder.");
        return;
    }

    File silverFolder = new File(silverFolderPath);
    if (!silverFolder.isDirectory() || !silverFolder.canRead()) {
        logger.error("The specified path is not a folder or is not readable.");
        return;
    }

    // Get silver folder filter
    String silverFolderWildcard = null;
    if (commandLine.hasOption("sf")) {
        silverFolderWildcard = commandLine.getOptionValue("sf");
    }

    // Get mappers folder
    mappersFolderPath = null;
    if (commandLine.hasOption('m')) {
        mappersFolderPath = commandLine.getOptionValue('m');
        File mappersFolder = new File(mappersFolderPath);
        if (!mappersFolder.isDirectory() || !mappersFolder.canRead()) {
            logger.error("The specified path is not a folder or is not readable.");
            return;
        }
        mappersFolderPath = mappersFolder.getAbsolutePath() + File.separator;
    }

    // Get what evaluation tests to perform
    if (commandLine.hasOption("tnorm")) {
        for (String arg : commandLine.getOptionValues("tnorm")) {
            try {
                TestType type = TestType.valueOf(arg.toLowerCase());
                switch (type) {
                case all:
                    performExactAnn = true;
                    performLeftAnn = true;
                    performRightAnn = true;
                    performSharedAnn = true;
                    performOverlapAnn = true;
                    break;
                case exact:
                    performExactAnn = true;
                    break;
                case left:
                    performLeftAnn = true;
                    break;
                case right:
                    performRightAnn = true;
                    break;
                case shared:
                    performSharedAnn = true;
                    break;
                case overlap:
                    performOverlapAnn = true;
                    break;
                }
            } catch (Exception ex) {
                logger.error("Invalid test name \"" + arg + "\" at \"-tnorm\" command.");
                return;
            }
        }
    }

    if (commandLine.hasOption("tner")) {
        for (String arg : commandLine.getOptionValues("tner")) {
            try {
                TestType type = TestType.valueOf(arg.toLowerCase());
                switch (type) {
                case all:
                    performExactChunks = true;
                    performLeftChunks = true;
                    performRightChunks = true;
                    performSharedChunks = true;
                    performOverlapChunks = true;
                    break;
                case exact:
                    performExactChunks = true;
                    break;
                case left:
                    performLeftChunks = true;
                    break;
                case right:
                    performRightChunks = true;
                    break;
                case shared:
                    performSharedChunks = true;
                    break;
                case overlap:
                    performOverlapChunks = true;
                    break;
                }
            } catch (Exception ex) {
                logger.error("Invalid test name \"" + arg + "\" at \"-tner\" command.");
                return;
            }
        }
    }

    if (!performExactChunks && !performLeftChunks && !performRightChunks && !performSharedChunks
            && !performOverlapChunks && !performExactAnn && !performLeftAnn && !performRightAnn
            && !performSharedAnn && !performOverlapAnn) {
        logger.error("Please specify at least one evaluation test to perform.");
        return;
    }

    //        String goldFolderPath = "resources/corpus/bionlp2011/dev/";
    //        String silverFolderPath = "resources/corpus/bionlp2011/dev/silver/dictionaries/";
    //        String silverFolderPath = "resources/corpus/bionlp2011/dev/silver/ml/";

    // CRAFT
    //        String goldFolderPath = "/Volumes/data/Dropbox/PhD/work/platform/code/neji/resources/corpus/craft/gold/";
    //        String silverFolderPath = "/Volumes/data/Dropbox/PhD/work/platform/code/neji/resources/corpus/craft/silver/";

    //        args = new String[]{"resources/corpus/craft2/silver/","resources/corpus/craft2/silver/"};
    //        args = new String[]{"resources/corpus/craft2/gold/","resources/corpus/craft2/silver/"};
    //        args = new String[]{"resources/corpus/craft2/gold/","resources/temp/whatizit/craft/silver/a1/"};

    // CRAFT2
    //        String goldFolderPath = args[0];
    //        String silverFolderPath = "/Volumes/data/Dropbox/PhD/work/platform/code/neji/resources/corpus/craft2/silver/";
    //        String silverFolderPath = "/Volumes/data/Backups/2013-04-11_desktop/Downloads/whatizit/craft/ukpmc/a1/";
    //        String silverFolderPath = args[1];
    //String silverFolderPath = "resources/temp/whatizit/craft/silver/a1/";
    //        String silverFolderPath = "/Users/david/Downloads/whatizit/craft/ukpmc/a1";
    //        String silverFolderPath = "/Users/david/Downloads/Craft1.0Annotations/";

    // ANEM COCOA
    //        String goldFolderPath = "/Volumes/data/Dropbox/PhD/work/platform/code/neji/resources/corpus/anem/test/gold/";
    //        String silverFolderPath = "/Users/david/Downloads/anem_craft/test/";

    // MLEE
    //        String goldFolderPath = "/Volumes/data/Dropbox/PhD/work/platform/code/neji/resources/corpus/mlee/gold/";
    //        String silverFolderPath = "/Volumes/data/Dropbox/PhD/work/platform/code/neji/resources/corpus/mlee/silver/";

    // CellFinder
    //        String goldFolderPath = "/Volumes/data/Dropbox/PhD/work/platform/code/neji/resources/corpus/cellfinder/gold/";
    //        String silverFolderPath = "/Volumes/data/Dropbox/PhD/work/platform/code/neji/resources/corpus/cellfinder/silver/";

    // Arizona
    //        String goldFolderPath = "/Volumes/data/Dropbox/PhD/work/platform/code/neji/resources/corpus/arizona/gold/";
    //        String silverFolderPath = "/Volumes/data/Dropbox/PhD/work/platform/code/neji/resources/corpus/arizona/silver/";

    // NCBI Disease
    //        String silverFolderPath = "/Volumes/data/Dropbox/PhD/work/platform/code/neji/resources/corpus/ncbi/silver/";
    //        String goldFolderPath = "/Volumes/data/Dropbox/PhD/work/platform/code/neji/resources/corpus/ncbi/gold/";
    //        String silverFolderPath = "/Users/david/Downloads/whatizit/ncbi/whatizitDiseaseUMLSDict/a1/";

    // ANEM
    //        String goldFolderPath = "/Volumes/data/Dropbox/PhD/work/platform/code/neji/resources/corpus/anem/test/gold/";
    //        String silverFolderPath = "/Volumes/data/Dropbox/PhD/work/platform/code/neji/resources/corpus/anem/test/silver/";

    // SCAI
    //        String goldFolderPath = "/Volumes/data/Dropbox/PhD/work/platform/code/neji/resources/corpus/scai/test/gold/";
    //        String silverFolderPath = "/Volumes/data/Dropbox/PhD/work/platform/code/neji/resources/corpus/scai/test/silver/";

    // Get a lists of gold and silver files
    File[] goldFiles;
    if (goldFolderWildcard == null)
        goldFiles = goldFolder.listFiles();
    else
        goldFiles = goldFolder.listFiles(new FileUtil.Filter(new String[] { goldFolderWildcard }));

    File[] silverFiles;
    if (silverFolderWildcard == null)
        silverFiles = silverFolder.listFiles();
    else
        silverFiles = silverFolder.listFiles(new FileUtil.Filter(new String[] { silverFolderWildcard }));

    List<File> goldFilesList = Arrays.asList(goldFiles);
    List<File> goldFilesList2 = new ArrayList<>();
    for (File f : goldFilesList) {
        if (!f.isDirectory())
            goldFilesList2.add(f);
    }
    Collections.sort(goldFilesList2);
    goldFiles = goldFilesList2.toArray(new File[goldFilesList2.size()]);

    List<File> silverFilesList = Arrays.asList(silverFiles);
    List<File> silverFilesList2 = new ArrayList<>();
    for (File f : silverFilesList) {
        if (!f.isDirectory())
            silverFilesList2.add(f);
    }
    Collections.sort(silverFilesList2);
    silverFiles = silverFilesList2.toArray(new File[silverFilesList2.size()]);

    if (goldFiles.length != silverFiles.length) {
        throw new RuntimeException("Folders are not compatible (the number of files is not equal).");
    }

    // Perform tests
    if (performExactChunks || performExactAnn) {
        logger.info("#####################");
        logger.info("EXACT");
        logger.info("#####################");
    }
    if (performExactChunks) {
        logger.info("\tIdentifier matching: NONE");
        getCompleteEvaluator(goldFiles, silverFiles, CompleteEvaluator.EvaluationType.Exact,
                IdentifierMatch.NONE);
    }
    if (performExactAnn) {
        logger.info("\tIdentifier matching: EXACT");
        getCompleteEvaluator(goldFiles, silverFiles, CompleteEvaluator.EvaluationType.Exact,
                IdentifierMatch.EXACT);
        logger.info("\tIdentifier matching: CONTAINS");
        getCompleteEvaluator(goldFiles, silverFiles, CompleteEvaluator.EvaluationType.Exact,
                IdentifierMatch.CONTAIN);
    }

    if (performLeftChunks || performLeftAnn) {
        logger.info("#####################");
        logger.info("LEFT");
        logger.info("#####################");
    }
    if (performLeftChunks) {
        logger.info("\tIdentifier matching: NONE");
        getCompleteEvaluator(goldFiles, silverFiles, CompleteEvaluator.EvaluationType.Left,
                IdentifierMatch.NONE);
    }
    if (performLeftAnn) {
        logger.info("\tIdentifier matching: EXACT");
        getCompleteEvaluator(goldFiles, silverFiles, CompleteEvaluator.EvaluationType.Left,
                IdentifierMatch.EXACT);
        logger.info("\tIdentifier matching: CONTAINS");
        getCompleteEvaluator(goldFiles, silverFiles, CompleteEvaluator.EvaluationType.Left,
                IdentifierMatch.CONTAIN);
    }

    if (performRightChunks || performRightAnn) {
        logger.info("#####################");
        logger.info("RIGHT");
        logger.info("#####################");
    }
    if (performRightChunks) {
        logger.info("\tIdentifier matching: NONE");
        getCompleteEvaluator(goldFiles, silverFiles, CompleteEvaluator.EvaluationType.Right,
                IdentifierMatch.NONE);
    }
    if (performRightAnn) {
        logger.info("\tIdentifier matching: EXACT");
        getCompleteEvaluator(goldFiles, silverFiles, CompleteEvaluator.EvaluationType.Right,
                IdentifierMatch.EXACT);
        logger.info("\tIdentifier matching: CONTAINS");
        getCompleteEvaluator(goldFiles, silverFiles, CompleteEvaluator.EvaluationType.Right,
                IdentifierMatch.CONTAIN);
    }

    if (performSharedChunks || performSharedAnn) {
        logger.info("#####################");
        logger.info("SHARED");
        logger.info("#####################");
    }
    if (performSharedChunks) {
        logger.info("\tIdentifier matching: NONE");
        getCompleteEvaluator(goldFiles, silverFiles, CompleteEvaluator.EvaluationType.Shared,
                IdentifierMatch.NONE);
    }
    if (performSharedAnn) {
        logger.info("\tIdentifier matching: EXACT");
        getCompleteEvaluator(goldFiles, silverFiles, CompleteEvaluator.EvaluationType.Shared,
                IdentifierMatch.EXACT);
        logger.info("\tIdentifier matching: CONTAINS");
        getCompleteEvaluator(goldFiles, silverFiles, CompleteEvaluator.EvaluationType.Shared,
                IdentifierMatch.CONTAIN);
    }

    if (performOverlapChunks || performOverlapAnn) {
        logger.info("#####################");
        logger.info("OVERLAP");
        logger.info("#####################");
    }
    if (performOverlapChunks) {
        logger.info("\tIdentifier matching: NONE");
        getCompleteEvaluator(goldFiles, silverFiles, CompleteEvaluator.EvaluationType.Overlap,
                IdentifierMatch.NONE);
    }
    if (performOverlapAnn) {
        logger.info("\tIdentifier matching: EXACT");
        getCompleteEvaluator(goldFiles, silverFiles, CompleteEvaluator.EvaluationType.Overlap,
                IdentifierMatch.EXACT);
        logger.info("\tIdentifier matching: CONTAINS");
        getCompleteEvaluator(goldFiles, silverFiles, CompleteEvaluator.EvaluationType.Overlap,
                IdentifierMatch.CONTAIN);
    }

    /*
    logger.info("Num. UNIPROTS: {}", CompleteEvaluator.numUNIPROTS);
    logger.info("Num. Uniprots mapped: {}", CompleteEvaluator.numUNIPROTSmapped);
    logger.info("Ratio: {}%", ((double)CompleteEvaluator.numUNIPROTSmapped/(double)CompleteEvaluator.numUNIPROTS)*100);
    logger.info("");
    logger.info("Num. PRGE concept names: {}", CompleteEvaluator.numPRGEnames);
    logger.info("Num. PRGE mapped: {}", CompleteEvaluator.numPRGEmapped);
    logger.info("Ratio: {}%", ((double)CompleteEvaluator.numPRGEmapped/(double)CompleteEvaluator.numPRGEnames)*100);
            
    logger.info("");
    logger.info("");
    logger.info("Num. Cell UMLS IDs: {}", CompleteEvaluator.numUMLSCL);
    logger.info("Num. Cell UMLS IDs mapped: {}", CompleteEvaluator.numUMLSCLmapped);
    logger.info("Ratio: {}%", ((double)CompleteEvaluator.numUMLSCLmapped/(double)CompleteEvaluator.numUMLSCL)*100);
    logger.info("");
    logger.info("Num. Cell concept names: {}", CompleteEvaluator.numCellNames);
    logger.info("Num. Cell concept names mapped: {}", CompleteEvaluator.numCellMapped);
    logger.info("Ratio: {}%", ((double)CompleteEvaluator.numCellMapped/(double)CompleteEvaluator.numCellNames)*100);
            
    logger.info("");
    logger.info("");
    logger.info("Total PROC_FUNC: {}", CompleteEvaluator.numPROCFUNC);
    logger.info("Total PROC_FUNC with IDs: {}", CompleteEvaluator.numPROCFUNCwithIDs);
    logger.info("Ratio: {}%", ((double)CompleteEvaluator.numPROCFUNCwithIDs/(double)CompleteEvaluator.numPROCFUNC)*100);
    logger.info("");
    logger.info("Num. PROC_FUNC UMLS IDs: {}", CompleteEvaluator.numUMLSPROCFUNC);
    logger.info("Num. PROC_FUNC UMLS IDs mapped: {}", CompleteEvaluator.numUMLSPROCFUNCmapped);
    logger.info("Ratio: {}%", ((double)CompleteEvaluator.numUMLSPROCFUNCmapped/(double)CompleteEvaluator.numUMLSPROCFUNC)*100);
    logger.info("");
    logger.info("Num. Cell concept names: {}", CompleteEvaluator.numPROCFUNCNames);
    logger.info("Num. Cell concept names mapped: {}", CompleteEvaluator.numPROCFUNCMapped);
    logger.info("Ratio: {}%", ((double)CompleteEvaluator.numPROCFUNCMapped/(double)CompleteEvaluator.numPROCFUNCNames)*100);
    */
}

From source file:qpid.MulticastMain.java

private static Options getOptions() {
    Options options = new Options();
    options.addOption(new Option("?", "help", false, "show usage"));
    options.addOption(new Option("h", "uri", true, "AMQP URI"));
    options.addOption(new Option("t", "type", true, "exchange type"));
    options.addOption(new Option("e", "exchange", true, "exchange name"));
    options.addOption(new Option("u", "queue", true, "queue name"));
    options.addOption(new Option("i", "interval", true, "sampling interval"));
    options.addOption(new Option("r", "rate", true, "rate limit"));
    options.addOption(new Option("x", "producers", true, "producer count"));
    options.addOption(new Option("y", "consumers", true, "consumer count"));
    options.addOption(new Option("m", "ptxsize", true, "producer tx size"));
    options.addOption(new Option("n", "ctxsize", true, "consumer tx size"));
    options.addOption(new Option("c", "confirm", true, "max unconfirmed publishes"));
    options.addOption(new Option("a", "autoack", false, "auto ack"));
    options.addOption(new Option("A", "multiAckEvery", true, "multi ack every"));
    options.addOption(new Option("q", "qos", true, "qos prefetch count"));
    options.addOption(new Option("s", "size", true, "message size"));
    options.addOption(new Option("z", "time", true, "time limit"));
    Option flag = new Option("f", "flag", true, "message flag");
    flag.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(flag);/*from  w w w  . j av  a2 s .c  o  m*/
    options.addOption(new Option("M", "framemax", true, "frame max"));
    options.addOption(new Option("b", "heartbeat", true, "heartbeat interval"));
    return options;
}

From source file:ru.taximaxim.dbreplicator2.cli.AbstractCommandLineParser.java

/**
 * ? //from   w w  w  .  j a v  a  2  s.  c o  m
 *
 * @param opt
 *            - ? ?  
 *
 * @param longOpt
 *            -  ?  
 *
 * @param hasArg
 *            -  
 *
 * @param description
 *            - ?
 *
 * @param num
 *            <code>Integer</code> - ? 
 *
 * @param optionalArg
 *            -   <code>boolean</code>
 *
 * @param argName
 *            - ? 
 *
 */
protected void setOption(String opt, String longOpt, boolean hasArg, String description, Integer num,
        boolean optionalArg, String argName) {
    Option option = new Option(opt, longOpt, hasArg, description);

    if (num != null) {
        option.setArgs(num);
    }
    option.setOptionalArg(optionalArg);
    option.setArgName(argName);
    posixOptions.addOption(option);
}

From source file:scalabilityTests.scenarios.SchedulerJobSubmission.java

private static void addCommandLineOptions(Options options) {

    Option help = new Option("h", "help", false, "Display this help");
    help.setRequired(false);/*from   w w w.  ja va 2s.com*/
    options.addOption(help);

    Option xmlDescriptor = new Option("ad", "gcmad", true, "path to the GCM Aplication Descriptor to be used");
    xmlDescriptor.setArgName("GCMA_xml");
    xmlDescriptor.setArgs(1);
    xmlDescriptor.setRequired(true);
    options.addOption(xmlDescriptor);

    Option vnode = new Option("vn", "virtualNode", true,
            "the name of the virtual node which identifies the nodes onto which the Active Object Actors will be deployed");
    vnode.setArgName("AO_nodes");
    vnode.setArgs(1);
    vnode.setRequired(true);
    options.addOption(vnode);

    Option schedulerUrl = new Option("u", "schedulerUrl", true, "the URL of the Scheduler");
    schedulerUrl.setArgName("schedulerURL");
    schedulerUrl.setArgs(1);
    schedulerUrl.setRequired(true);
    options.addOption(schedulerUrl);

    Option username = new Option("l", "login", true, "The username to join the Scheduler");
    username.setArgName("login");
    username.setArgs(1);
    username.setRequired(false);
    options.addOption(username);

    Option password = new Option("p", "password", true, "The password to join the Scheduler");
    password.setArgName("pwd");
    password.setArgs(1);
    password.setRequired(false);
    options.addOption(password);

    Option loginFile = new Option("lf", "loginFile", true,
            "The path to a file containing valid username:password combinations for the Scheduler");
    loginFile.setArgName("login_cfg");
    loginFile.setArgs(1);
    loginFile.setRequired(false);
    options.addOption(loginFile);

    Option jobDescriptor = new Option("j", "jobDesc", true, "The path to the XML job descriptor");
    jobDescriptor.setArgName("XML_Job_Descriptor");
    jobDescriptor.setArgs(1);
    jobDescriptor.setRequired(true);
    options.addOption(jobDescriptor);

    Option registerListeners = new Option("rl", "listener", false,
            "Register the specified Scheduler listener for each user. If no listener is specified, then a 'simple' scheduler listener will be registered");
    registerListeners.setRequired(false);
    registerListeners.setOptionalArg(true);
    registerListeners.setArgs(1);
    registerListeners.setArgName("listenerClassName");
    options.addOption(registerListeners);

    Option jobRepetition = new Option("rp", "repeats", true,
            "The number of times the job will be submitted(optional parameter; by default it will be set to 1)");
    jobRepetition.setRequired(false);
    jobRepetition.setArgName("jobRepeats");
    jobRepetition.setArgs(1);
    options.addOption(jobRepetition);

    Option jobResult = new Option("jr", "jobResult", false,
            "Fetch the result for the submitted jobs. Optional parameter, defaults to false");
    jobResult.setRequired(false);
    options.addOption(jobResult);

    OptionGroup initialStateGroup = new OptionGroup();
    initialStateGroup.setRequired(false);

    Option gui = new Option("gu", "gui", false,
            "Simulate an user which interacts with the Scheduler using a GUI(all scheduler state will be downloaded at login)");
    gui.setRequired(false);
    initialStateGroup.addOption(gui);

    Option cli = new Option("cu", "cli", false,
            "Simulate an user which interacts with the Scheduler using a CLI(the scheduler state will NOT be downloaded at login)");
    cli.setRequired(false);
    initialStateGroup.addOption(cli);

    options.addOptionGroup(initialStateGroup);

    Option myEventsOnly = new Option("me", "myEvsOnly", false,
            "While registering a listener, get only the events which concern me");
    myEventsOnly.setRequired(false);
    options.addOption(myEventsOnly);
}

From source file:scoutdoc.main.Main.java

/**
 * @param args/*from  w w  w  .  java  2 s .  c o  m*/
 */
public static void main(String[] args) {
    Option optHelp = new Option(HELP_ID, "help", false, "print this message");

    Option optProp = new Option(PROP_ID, "config", true, "configuration file");
    optProp.setArgName("file");

    //source
    Option optTask = new Option(SOURCE_TASKS_ID, "task", true, "(source) one or many task files");
    optTask.setArgName("files");
    optTask.setArgs(Option.UNLIMITED_VALUES);

    Option optAllPages = new Option(SOURCE_ALL_PAGES_ID, "pages", false,
            "(source) use the pages contained in the source folder");

    Option optListPages = new Option(SOURCE_LIST_ID, "list", true,
            "(source) list of pages contained in the file");
    optListPages.setArgName("file");

    Option optRecentChange = new Option(SOURCE_RECENT_CHANGES_ID, "recent-changes", false,
            "(source) use the pages from the wiki recent changes");

    Option optRss = new Option(SOURCE_RSS_ID, "rss", false,
            "(source) use the pages from the rss feed of the wiki");

    OptionGroup sourceGroup = new OptionGroup();
    sourceGroup.setRequired(true);
    sourceGroup.addOption(optTask);
    sourceGroup.addOption(optAllPages);
    sourceGroup.addOption(optListPages);
    sourceGroup.addOption(optRecentChange);
    sourceGroup.addOption(optRss);

    Option optfilter = new Option(SOURCE_FILTER_ID, "filter", true, "Filter for list of pages used as source");
    optfilter.setArgName("class");

    List<String> values = Lists.newArrayList();
    for (Operation o : Operation.values()) {
        values.add(o.name());
    }
    Option optOperation = new Option(OPERATION_ID, "operation", true,
            "operation: " + Joiner.on(", ").join(values));
    optOperation.setArgName("operations");
    optOperation.setArgs(Option.UNLIMITED_VALUES);
    optOperation.setRequired(true);

    Option optOutputCheckstyle = new Option(OUTPUT_CHECKSTYLE_ID, "output-checkstyle", true,
            "(CHECK output) create a xml checkstyle file (<filename> is optional. Default: "
                    + DEFAULT_CHECKSTYLE_NAME + ")");
    optOutputCheckstyle.setArgName("filename");
    optOutputCheckstyle.setOptionalArg(true);

    Option optOutputDashboard = new Option(OUTPUT_DASHBOARD_ID, "output-dashboard", true,
            "(CHECK output) create an html dashboard (<folder> is optional. Default: " + DEFAULT_DASHBOARD_NAME
                    + ")");
    optOutputDashboard.setArgName("folder");
    optOutputDashboard.setOptionalArg(true);

    Options options = new Options();
    options.addOption(optHelp);
    options.addOption(optProp);
    options.addOptionGroup(sourceGroup);
    options.addOption(optfilter);
    options.addOption(optOperation);
    options.addOption(optOutputCheckstyle);
    options.addOption(optOutputDashboard);

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

        if (cmd.hasOption(HELP_ID)) {
            printHelpAndExit(options);
        }

        if (cmd.hasOption(PROP_ID)) {
            ProjectProperties.initProperties(cmd.getOptionValue(PROP_ID));
        }
        Pages.initPageList();

        List<Operation> operations = readOptionEnum(cmd, optOperation, Operation.class);
        List<Task> tasks = readTasks(cmd, optTask);

        Collection<Page> pageList;
        if (cmd.hasOption(SOURCE_ALL_PAGES_ID)) {
            pageList = PageUtility.loadPages(ProjectProperties.getFolderWikiSource());
        } else if (cmd.hasOption(SOURCE_LIST_ID)) {
            String name = cmd.getOptionValue(SOURCE_LIST_ID);
            try {
                pageList = PageUtility.readList(name);
            } catch (IOException e) {
                throw new MissingArgumentException("IOException for file <" + name + "> for <"
                        + optListPages.getLongOpt() + "> : " + e.getMessage());
            }
        } else {
            pageList = Collections.emptyList();
        }

        IPageFilter filter;
        if (cmd.hasOption(SOURCE_FILTER_ID)) {
            if (tasks.size() > 0) {
                throw new MissingArgumentException("Filter <" + optfilter.getLongOpt()
                        + "> is not allowed for source <" + optTask.getLongOpt() + ">.");
            }
            filter = newInstance(cmd.getOptionValue(SOURCE_FILTER_ID), IPageFilter.class,
                    new AcceptAllPageFilter());
        } else {
            filter = new AcceptAllPageFilter();
        }
        List<Page> pages = Lists.newArrayList();
        for (Page page : pageList) {
            if (filter.keepPage(page)) {
                pages.add(page);
            }
        }

        if (operations.contains(Operation.FETCH)) {
            if (pages.size() > 0) {
                ScoutDocFetch sdf = new ScoutDocFetch();
                RelatedPagesStrategy strategy;
                if (cmd.hasOption(SOURCE_ALL_PAGES_ID)) {
                    strategy = RelatedPagesStrategy.NO_RELATED_PAGES;
                } else if (cmd.hasOption(SOURCE_LIST_ID)) {
                    strategy = RelatedPagesStrategy.IMAGES_TEMPLATES_AND_LINKS;
                } else {
                    throw new IllegalStateException("Page list comes from an unexpected option");
                }
                sdf.execute(pages, strategy);
            } else if (cmd.hasOption(SOURCE_RECENT_CHANGES_ID)) {
                ScoutDocFetch sdf = new ScoutDocFetch();
                sdf.executeRecentChanges(filter);
            } else if (cmd.hasOption(SOURCE_RSS_ID)) {
                ScoutDocFetch sdf = new ScoutDocFetch();
                sdf.executeRss(filter);
            } else if (tasks.size() > 0) {
                for (Task task : tasks) {
                    ScoutDocFetch sdf = new ScoutDocFetch();
                    sdf.execute(task);
                }
            } else {
                throw new MissingArgumentException("Missing a source");
            }
        }

        if (operations.contains(Operation.CHECK)) {
            ScoutDocCheck sdc = new ScoutDocCheck();
            List<Check> checks = Lists.newArrayList();
            ensureNotSet(cmd, optRecentChange, Operation.CHECK);
            ensureNotSet(cmd, optRss, Operation.CHECK);
            if (pages.size() > 0) {
                checks = sdc.analysePages(pages);
            } else if (tasks.size() > 0) {
                for (Task task : tasks) {
                    ScoutDocCheck sdcForTask = new ScoutDocCheck();
                    checks.addAll(sdcForTask.execute(task));
                }
            } else {
                throw new MissingArgumentException("Missing a source");
            }
            //output:
            if (cmd.hasOption(OUTPUT_CHECKSTYLE_ID)) {
                String fileName = cmd.getOptionValue(OUTPUT_CHECKSTYLE_ID, DEFAULT_CHECKSTYLE_NAME);
                sdc.writeCheckstyleFile(checks, fileName);
            }
            if (cmd.hasOption(OUTPUT_DASHBOARD_ID)) {
                String folderName = cmd.getOptionValue(OUTPUT_DASHBOARD_ID, DEFAULT_DASHBOARD_NAME);
                sdc.writeDashboardFiles(checks, folderName);
            }
        }

        if (operations.contains(Operation.CONVERT)) {
            ensureNotSet(cmd, optAllPages, Operation.CONVERT);
            ensureNotSet(cmd, optListPages, Operation.CONVERT);
            ensureNotSet(cmd, optRecentChange, Operation.CONVERT);
            ensureNotSet(cmd, optRss, Operation.CONVERT);
            if (tasks.size() > 0) {
                for (Task task : tasks) {
                    ScoutDocConverter sdc = new ScoutDocConverter();
                    sdc.execute(task);
                }
            } else {
                throw new MissingArgumentException("Missing a source");
            }
        }

    } catch (MissingOptionException e) {
        // Check if it is an error or if optHelp was selected.
        boolean help = false;
        try {
            Options helpOptions = new Options();
            helpOptions.addOption(optHelp);
            CommandLineParser parser = new PosixParser();
            CommandLine line = parser.parse(helpOptions, args);
            if (line.hasOption(HELP_ID)) {
                help = true;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (!help) {
            System.err.println(e.getMessage());
            System.err.flush();
        }
        printHelpAndExit(options);
    } catch (MissingArgumentException e) {
        System.err.println(e.getMessage());
        printHelpAndExit(options);
    } catch (ParseException e) {
        System.err.println("Error while parsing the command line: " + e.getMessage());
        System.exit(1);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:sorcer.launcher.Sorcer.java

private static Options buildOptions() {
    Options options = new Options();
    Option wait = new Option(WAIT, "wait", true,
            "Wait style, one of:\n" + "'no' - exit immediately, forces forked mode\n"
                    + "'start' - wait until sorcer starts, then exit, forces forked mode\n"
                    + "'end' - wait until sorcer finishes, stopping launcher also stops SORCER");
    wait.setType(WaitMode.class);
    wait.setArgs(1);
    wait.setArgName("wait-mode");
    options.addOption(wait);/*  ww w.  j ava  2  s.  c  o  m*/

    Option logs = new Option(LOGS, true, "Directory for logs");
    logs.setType(File.class);
    logs.setArgs(1);
    logs.setArgName("log-dir");
    options.addOption(logs);

    Option debug = new Option(DEBUG, true, "Add debug option to JVM");
    debug.setType(Boolean.class);
    debug.setArgs(1);
    debug.setArgName("port");
    options.addOption(debug);

    //see sorcer.launcher.Profile
    Option profile = new Option(PROFILE, "profile", true, "Profile, one of [sorcer, rio, mix] or a path");
    profile.setArgs(1);
    profile.setType(String.class);
    profile.setArgName("profile");
    options.addOption(profile);

    String modeDesc = "Select start mode, one of:\n" + Mode.preferDirect.paramValue
            + " - default, prefer current JVM, start in forked if debug is enabled or required environment variable is not set\n"
            + Mode.forceDirect.paramValue + " - try current JVM, exit on failure\n" + Mode.preferFork.paramValue
            + " - prefer new process, try in current JVM if cannot run a process (e.g. insufficient privileges)\n"
            + Mode.forceFork.paramValue + " try new process, exit on failure";
    Option mode = new Option(MODE, "mode", true, modeDesc);
    mode.setType(Boolean.class);
    mode.setArgs(1);
    mode.setArgName("mode");
    options.addOption(mode);
    options.addOption("h", "help", false, "Print this help");

    Option rio = new Option(RIO,
            "List of opstrings to be started by the Rio Monitor (opstring) separated by the system path separator ("
                    + File.pathSeparator + ")");
    rio.setArgs(1);
    rio.setArgName("opstrings");
    rio.setType(String.class);
    options.addOption(rio);

    return options;
}

From source file:sorcer.tools.shell.cmds.BootCmd.java

private Options buildOptions() {
    Options options = new Options();
    Option logs = new Option(LOGS, true, "Directory for logs");
    logs.setType(File.class);
    logs.setArgs(1);
    logs.setArgName("log-dir");
    options.addOption(logs);//from w  w  w  .j  a  v a2  s . c o  m

    //see sorcer.launcher.Profile
    Option profile = new Option(PROFILE, "profile", true, "Profile, one of [sorcer, rio, mix] or a path");
    profile.setArgs(1);
    profile.setType(String.class);
    profile.setArgName("profile");
    options.addOption(profile);

    Option rio = new Option(RIO,
            "List of opstrings to be started by the Rio Monitor (opstring) separated by the system path separator ("
                    + File.pathSeparator + ")");
    rio.setArgs(1);
    rio.setArgName("opstrings");
    rio.setType(String.class);
    options.addOption(rio);

    Option all = new Option(ALL,
            "List of opstrings to be started by the Rio Monitor (opstring) separated by the system path separator ("
                    + File.pathSeparator + ")");
    all.setArgs(1);
    all.setArgName("all");
    all.setType(String.class);
    options.addOption(all);

    return options;
}

From source file:treecmp.commandline.CommandLineParser.java

public Command run(String args[]) {
    Command cmd = null;/* w  w w  .j a va 2 s .  co  m*/
    DefinedMetricsSet DMSet = DefinedMetricsSet.getInstance();

    Option oS = new Option("s", S_DESC);
    Option oW = new Option("w", W_DESC);
    oW.setArgName(W_ARG);
    oW.setArgs(1);
    Option oM = new Option("m", M_DESC);
    Option oR = new Option("r", R_DESC);
    oR.setArgName(R_ARG);
    oR.setArgs(1);

    OptionGroup cmdOpts = new OptionGroup();
    cmdOpts.addOption(oS);
    cmdOpts.addOption(oW);
    cmdOpts.addOption(oM);
    cmdOpts.addOption(oR);

    cmdOpts.setRequired(true);
    //set metric option
    Option oD = new Option("d", D_DESC);
    oD.setArgName(D_ARG);
    oD.setValueSeparator(' ');
    oD.setArgs(DMSet.size());
    oD.setRequired(true);

    Option oI = new Option("i", I_DESC);
    oI.setArgName(I_ARG);
    oI.setArgs(1);
    oI.setRequired(true);

    Option oO = new Option("o", O_DESC);
    oO.setArgs(1);
    oO.setArgName(O_ARG);
    oO.setRequired(true);

    Option oP = new Option("P", P_DESC);
    Option oSS = new Option("N", SS_DESC);
    Option oII = new Option("I", II_DESC);

    Option oOO = new Option("O", OO_DESC);
    Option oA = new Option("A", A_DESC);
    OptionGroup customMOpts = new OptionGroup();
    customMOpts.addOption(oOO);
    customMOpts.addOption(oA);

    Options opts = new Options();

    opts.addOptionGroup(cmdOpts);
    opts.addOption(oD);
    opts.addOption(oI);
    opts.addOption(oO);
    opts.addOption(oP);
    opts.addOption(oSS);
    opts.addOption(oII);
    opts.addOptionGroup(customMOpts);

    //getting version from manifest file
    String version = CommandLineParser.class.getPackage().getImplementationVersion();
    if (version == null) {
        version = "";
    }
    String FOOTER = "";
    String HEADER = " ";
    String APP_NAME = "TreeCmp version " + version + "\n";
    GnuParser parser = new GnuParser();
    HelpFormatter formatter = new HelpFormatter();
    formatter.setOptionComparator(new OptOrder());

    System.out.println(APP_NAME);
    if (args.length == 0) {
        formatter.printHelp(CMD_LINE_SYNTAX, HEADER, opts, FOOTER, false);
        return null;
    }

    try {
        CommandLine commandLine = parser.parse(opts, args);
        if (commandLine != null) {
            // process these values
            //set IO settings
            String inputFileName = (String) commandLine.getOptionValue(oI.getOpt());
            String outputFileName = (String) commandLine.getOptionValue(oO.getOpt());

            if (inputFileName == null) {
                System.out.println("Error: input file not specified!");
                formatter.printHelp(CMD_LINE_SYNTAX, HEADER, opts, FOOTER, false);

                return null;
            }
            if (outputFileName == null) {
                System.out.println("Error: output file not specified!");
                formatter.printHelp(CMD_LINE_SYNTAX, HEADER, opts, FOOTER, false);
                return null;
            }

            //commandLine.
            IOSettings IOset = IOSettings.getIOSettings();
            IOset.setInputFile(inputFileName);
            IOset.setOutputFile(outputFileName);

            //custom additinal options
            ArrayList<Option> custOpts = new ArrayList<Option>();

            if (commandLine.hasOption(oP.getOpt())) {
                IOset.setPruneTrees(true);
                custOpts.add(oP);
            }
            if (commandLine.hasOption(oSS.getOpt())) {
                IOset.setRandomComparison(true);
                custOpts.add(oSS);
            }
            if (commandLine.hasOption(oA.getOpt())) {
                IOset.setGenAlignments(true);
                custOpts.add(oA);
            }
            if (commandLine.hasOption(oOO.getOpt())) {
                IOset.setOptMsMcByRf(true);
                custOpts.add(oOO);
            }
            if (commandLine.hasOption(oII.getOpt())) {
                IOset.setGenSummary(true);
                custOpts.add(oII);
            }
            Collections.sort(custOpts, new OptOrder());

            //set active metrics
            ActiveMetricsSet AMSet = ActiveMetricsSet.getInstance();

            final String[] metrics = commandLine.getOptionValues(oD.getOpt());
            for (int i = 0; i < metrics.length; i++) {

                final DefinedMetric definedMetric = DMSet.getDefinedMetric(metrics[i]);
                if (definedMetric != null) {
                    AMSet.addMetric(definedMetric);
                } else {
                    System.out.print("Error: ");
                    System.out.println("Metric: " + metrics[i] + " is unknown\n.");
                    formatter.printHelp(CMD_LINE_SYNTAX, HEADER, opts, FOOTER, false);
                    return null;
                }

            }

            //set active command
            String analysisType = "";

            if (commandLine.hasOption(oW.getOpt())) {
                String sWindowSize = (String) commandLine.getOptionValue(oW.getOpt());
                int iWindowSize = Integer.parseInt(sWindowSize);
                cmd = new RunWCommand(1, "-w", iWindowSize);
                analysisType = "window comparison mode (-w) with window size: " + iWindowSize;
            } else if (commandLine.hasOption(oM.getOpt())) {
                cmd = new RunMCommand(0, "-m");
                analysisType = "matrix comparison mode (-m)";
            } else if (commandLine.hasOption(oS.getOpt())) {
                cmd = new RunSCommand(0, "-s");
                analysisType = "overlapping pair comparison mode (-s)";
            } else if (commandLine.hasOption(oR.getOpt())) {
                String sRefTreeFile = (String) commandLine.getOptionValue(oR.getOpt());
                cmd = new RunRCommand(0, "-r", sRefTreeFile);
                analysisType = " ref-to-all comparison mode (-r)";
            } else {
                System.out.println("Error: type of the analysis not specified correctly!");
                formatter.printHelp(CMD_LINE_SYNTAX, HEADER, opts, FOOTER, false);
                return null;
            }

            printOptionsInEffect(analysisType, AMSet, inputFileName, outputFileName, custOpts);

            return cmd;
        } else {
            //Error during parsing command line
            return null;
        }
    } catch (ParseException ex) {
        log.log(Level.WARNING, "Could not parse command line arguments.", ex);
        System.out.println(CMD_ERROR);

        formatter.printHelp(CMD_LINE_SYNTAX, HEADER, opts, FOOTER, false);

    } catch (NumberFormatException ex) {
        System.out.print("Error: ");
        System.out.println("window size should be an integer.\n");
        formatter.printHelp(CMD_LINE_SYNTAX, HEADER, opts, FOOTER, false);

    }
    return cmd;
}