Example usage for org.apache.commons.cli PosixParser PosixParser

List of usage examples for org.apache.commons.cli PosixParser PosixParser

Introduction

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

Prototype

PosixParser

Source Link

Usage

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

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

    PropertyConfigurator.configure(logConfig);

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

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

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

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

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

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

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

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

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

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

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

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

/**
 * @param args/*  w  w w  .j  av a  2 s  . co m*/
 */
public static void main(String... args) throws IOException {
    // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "Output filename.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_STARTTorsion, true,
            "The torsion in your inMol will be rotated by this value for the first job");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_TORSIONIncrement, true, "Incremnt each subsequent conformation by this step size");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_NSTEPS, true, "Number of conformations to create");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_BONDFILE, true, "The file containing the bond atoms that define the torsion.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_MINIMIZE, false,
            "Minimize conformer at each step using MMFFs.  If maxConfsPerStep is > 1, "
                    + "all confs will be mimimized and the lowest E will be output.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_CONSTRIANT, true,
            "One of strong (90), medium (45), weak(20), none or a floating point number"
                    + " to specify the tethered constraint strength for -minimize (def=strong)");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_MAXCONFS_PER_STEP, true,
            "While holding the torsion fixed, maximum number of conformations of free atoms to generat.  default=1");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_COREFILE, true, "Outputfile to store guessed core.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_TORSIONS_ATOM_TAG, true,
            "Name of sdf tag which will contain the indices of atoms that define the torsion.");
    opt.setRequired(true);
    options.addOption(opt);

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

    if (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 bondFile = cmd.getOptionValue(OPT_BONDFILE);
    String coreFilename = cmd.getOptionValue(OPT_COREFILE);
    String torsionAtomsTag = cmd.getOptionValue(OPT_TORSIONS_ATOM_TAG);

    int nSteps = Integer.parseInt(cmd.getOptionValue(OPT_NSTEPS));
    int nStartTor = Integer.parseInt(cmd.getOptionValue(OPT_STARTTorsion));
    int nTorIncr = Integer.parseInt(cmd.getOptionValue(OPT_TORSIONIncrement));

    int nMaxConfsPerStep = 1;
    if (cmd.hasOption(OPT_MAXCONFS_PER_STEP)) {
        nMaxConfsPerStep = Integer.parseInt(cmd.getOptionValue(OPT_MAXCONFS_PER_STEP));
    }

    String constraintStrength = cmd.getOptionValue(OPT_CONSTRIANT);

    boolean doMinimize = cmd.hasOption(OPT_MINIMIZE);

    SDFTorsionScanner torGenerator = new SDFTorsionScanner(bondFile, coreFilename, torsionAtomsTag, nSteps,
            nStartTor, nTorIncr, nMaxConfsPerStep, doMinimize, constraintStrength);

    torGenerator.run(inFile, outFile, coreFilename);
}

From source file:com.abiquo.vsm.migration.Migrator.java

public static void main(String[] args) throws UnknownHostException, IOException {
    String host = getProperty("abiquo.redis.host", "localhost");
    int port = Integer.valueOf(getProperty("abiquo.redis.port", "6379"));

    CommandLine command = null;//w ww  .  java  2 s . c  om
    String filename = null;

    try {
        // Parse the command line arguments
        command = new PosixParser().parse(buildOptions(), args);

        if (command.hasOption("help")) {
            printUsage();
            System.exit(0);
        }

        if (command.hasOption("f")) {
            filename = command.getOptionValue("f");
        }

        if (command.hasOption("h")) {
            host = command.getOptionValue("h");
        }

        if (command.hasOption("p")) {
            port = Integer.parseInt(command.getOptionValue("p"));
        }
    } catch (Exception e) {
        logger.error("Error while parsing arguments. " + e.getMessage());
        printUsage();
        System.exit(-1);
    }

    // Start migration
    Migrator migrator = new Migrator(host, port, 0);
    logger.info("Migrating from 1.6.8 to 1.7 data model on redis located at {}:{}", host, port);

    if (filename == null) {
        migrator.migrateNonPersistedModelFromRedis();
    } else {
        File file = new File(filename);
        migrator.migrateNonPersistedModelFromFile(file);
    }

    migrator.migratePersistedModel();

    logger.info("Number of migrated physical machines: {}", migrator.getMachinesCount());
    logger.info("Number of migrated subscriptions: {}", migrator.getSubscriptionsCount());

    System.exit(0);
}

From source file:com.github.andreax79.meca.Main.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    // create the command line parser
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();
    options.addOption("X", "suppress-output", false, "don't create the output file");

    OptionGroup boundariesOptions = new OptionGroup();
    boundariesOptions.addOption(new Option("P", "periodic", false, "periodic boundaries (default)"));
    boundariesOptions.addOption(new Option("F", "fixed", false, "fixed-value boundaries"));
    boundariesOptions.addOption(new Option("A", "adiabatic", false, "adiabatic boundaries"));
    boundariesOptions.addOption(new Option("R", "reflective", false, "reflective boundaries"));
    options.addOptionGroup(boundariesOptions);

    OptionGroup colorOptions = new OptionGroup();
    colorOptions.addOption(new Option("bn", "black-white", false, "black and white color scheme (default)"));
    colorOptions.addOption(new Option("ca", "activation-color", false, "activation color scheme"));
    colorOptions.addOption(new Option("co", "omega-color", false, "omega color scheme"));
    options.addOptionGroup(colorOptions);

    options.addOption(OptionBuilder.withLongOpt("rule").withDescription("rule number (required)").hasArg()
            .withArgName("rule").create());

    options.addOption(OptionBuilder.withLongOpt("width").withDescription("space width (required)").hasArg()
            .withArgName("width").create());

    options.addOption(OptionBuilder.withLongOpt("steps").withDescription("number of steps (required)").hasArg()
            .withArgName("steps").create());

    options.addOption(OptionBuilder.withLongOpt("alpha").withDescription("memory factor (default 0)").hasArg()
            .withArgName("alpha").create());

    options.addOption(OptionBuilder.withLongOpt("pattern").withDescription("inititial pattern").hasArg()
            .withArgName("pattern").create());

    options.addOption("s", "single-seed", false, "single cell seed");
    options.addOption("si", "single-seed-inverse", false, "all 1 except one cell");

    options.addOption(OptionBuilder.withLongOpt("update-patter")
            .withDescription("update patter (valid values are " + UpdatePattern.validValues() + ")").hasArg()
            .withArgName("updatepatter").create());

    // test/*from   w w  w  .  j av  a2  s  .com*/
    // args = new String[]{ "--rule=10", "--steps=500" , "--width=60", "-P" , "-s" };

    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (!line.hasOption("rule"))
            throw new ParseException("no rule number (use --rule=XX)");
        int rule;
        try {
            rule = Integer.parseInt(line.getOptionValue("rule"));
            if (rule < 0 || rule > 15)
                throw new ParseException("invalid rule number");
        } catch (NumberFormatException ex) {
            throw new ParseException("invalid rule number");
        }

        if (!line.hasOption("width"))
            throw new ParseException("no space width (use --width=XX)");
        int width;
        try {
            width = Integer.parseInt(line.getOptionValue("width"));
            if (width < 1)
                throw new ParseException("invalid width");
        } catch (NumberFormatException ex) {
            throw new ParseException("invalid width");
        }

        if (!line.hasOption("steps"))
            throw new ParseException("no number of steps (use --steps=XX)");
        int steps;
        try {
            steps = Integer.parseInt(line.getOptionValue("steps"));
            if (width < 1)
                throw new ParseException("invalid number of steps");
        } catch (NumberFormatException ex) {
            throw new ParseException("invalid number of steps");
        }

        double alpha = 0;
        if (line.hasOption("alpha")) {
            try {
                alpha = Double.parseDouble(line.getOptionValue("alpha"));
                if (alpha < 0 || alpha > 1)
                    throw new ParseException("invalid alpha");
            } catch (NumberFormatException ex) {
                throw new ParseException("invalid alpha");
            }
        }

        String pattern = null;
        if (line.hasOption("pattern")) {
            pattern = line.getOptionValue("pattern");
            if (pattern != null)
                pattern = pattern.trim();
        }

        if (line.hasOption("single-seed"))
            pattern = "S";
        else if (line.hasOption("single-seed-inverse"))
            pattern = "SI";

        UpdatePattern updatePatter = UpdatePattern.synchronous;
        if (line.hasOption("update-patter")) {
            try {
                updatePatter = UpdatePattern.getUpdatePattern(line.getOptionValue("update-patter"));
            } catch (IllegalArgumentException ex) {
                throw new ParseException(ex.getMessage());
            }
        }

        Boundaries boundaries = Boundaries.periodic;
        if (line.hasOption("periodic"))
            boundaries = Boundaries.periodic;
        else if (line.hasOption("fixed"))
            boundaries = Boundaries.fixed;
        else if (line.hasOption("adiabatic"))
            boundaries = Boundaries.adiabatic;
        else if (line.hasOption("reflective"))
            boundaries = Boundaries.reflective;

        ColorScheme colorScheme = ColorScheme.noColor;
        if (line.hasOption("black-white"))
            colorScheme = ColorScheme.noColor;
        else if (line.hasOption("activation-color"))
            colorScheme = ColorScheme.activationColor;
        else if (line.hasOption("omega-color"))
            colorScheme = ColorScheme.omegaColor;

        Output output = Output.all;
        if (line.hasOption("suppress-output"))
            output = Output.noOutput;

        Main.drawRule(rule, width, boundaries, updatePatter, steps, alpha, pattern, output, colorScheme);

    } catch (ParseException ex) {
        System.err.println("Copyright (C) 2009 Andrea Bonomi - <andrea.bonomi@gmail.com>");
        System.err.println();
        System.err.println("https://github.com/andreax79/one-neighbor-binary-cellular-automata");
        System.err.println();
        System.err.println("This program is free software; you can redistribute it and/or modify it");
        System.err.println("under the terms of the GNU General Public License as published by the");
        System.err.println("Free Software Foundation; either version 2 of the License, or (at your");
        System.err.println("option) any later version.");
        System.err.println();
        System.err.println("This program is distributed in the hope that it will be useful, but");
        System.err.println("WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY");
        System.err.println("or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License");
        System.err.println("for more details.");
        System.err.println();
        System.err.println("You should have received a copy of the GNU General Public License along");
        System.err.println("with this program; if not, write to the Free Software Foundation, Inc.,");
        System.err.println("59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.)");
        System.err.println();
        System.err.println(ex.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("main", options);

    } catch (IOException ex) {
        System.err.println("IO exception:" + ex.getMessage());
    }

}

From source file:de.mfo.jsurf.grid.RotationGrid.java

public static void main(String args[]) {
    size = 100;//from  w ww  .ja  va2 s.c o  m
    int xAngleMin = -90;
    int xAngleMax = 90;
    int xSteps = 11;
    int yAngleMin = -90;
    int yAngleMax = 90;
    int ySteps = 11;
    String jsurf_filename = "";
    String output_filename = null;

    Options options = new Options();

    options.addOption("s", "size", true, "width (and height) of a tile image (default: " + size + ")");
    options.addOption("minXAngle", true, "minimum rotation in x direction (default: " + xAngleMin + ")");
    options.addOption("maxXAngle", true, "maximum rotation in x direction (default: " + xAngleMax + ")");
    options.addOption("stepsX", true, "number of steps in x range of rotation (default: " + ySteps + ")");
    options.addOption("minYAngle", true, "minimum rotation in y direction (default: " + yAngleMin + ")");
    options.addOption("maxYAngle", true, "maximum rotation in y direction (default: " + yAngleMax + ")");
    options.addOption("stepsY", true, "number of steps in y range of rotation (default: " + ySteps + ")");
    options.addOption("q", "quality", true,
            "quality of the rendering: 0 (low), 1 (medium, default), 2 (high), 3 (extreme)");
    options.addOption("o", "output", true, "output PNG into this file (otherwise STDOUT)");

    CommandLineParser parser = new PosixParser();
    HelpFormatter formatter = new HelpFormatter();
    String help_header = "RotationGrid [options] jsurf_file";
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.getArgs().length > 0)
            jsurf_filename = cmd.getArgs()[0];
        else {
            formatter.printHelp(help_header, options);
            return;
        }

        if (cmd.hasOption("output"))
            output_filename = cmd.getOptionValue("output");

        if (cmd.hasOption("size"))
            size = Integer.parseInt(cmd.getOptionValue("size"));

        if (cmd.hasOption("minXAngle"))
            xAngleMin = Integer.parseInt(cmd.getOptionValue("minXAngle"));

        if (cmd.hasOption("maxXAngle"))
            xAngleMax = Integer.parseInt(cmd.getOptionValue("maxXAngle"));

        if (cmd.hasOption("stepsX"))
            xSteps = Integer.parseInt(cmd.getOptionValue("stepsX"));

        if (cmd.hasOption("minYAngle"))
            yAngleMin = Integer.parseInt(cmd.getOptionValue("minYAngle"));

        if (cmd.hasOption("maxYAngle"))
            yAngleMax = Integer.parseInt(cmd.getOptionValue("maxYAngle"));

        if (cmd.hasOption("stepsY"))
            ySteps = Integer.parseInt(cmd.getOptionValue("stepsY"));

        if (cmd.hasOption("stepsY"))
            ySteps = Integer.parseInt(cmd.getOptionValue("stepsY"));

        int quality = 1;
        if (cmd.hasOption("quality"))
            quality = Integer.parseInt(cmd.getOptionValue("quality"));
        switch (quality) {
        case 0:
            aam = AntiAliasingMode.ADAPTIVE_SUPERSAMPLING;
            aap = AntiAliasingPattern.OG_1x1;
            break;
        case 2:
            aam = AntiAliasingMode.ADAPTIVE_SUPERSAMPLING;
            aap = AntiAliasingPattern.OG_4x4;
            break;
        case 3:
            aam = AntiAliasingMode.SUPERSAMPLING;
            aap = AntiAliasingPattern.OG_4x4;
            break;
        case 1:
            aam = AntiAliasingMode.ADAPTIVE_SUPERSAMPLING;
            aap = AntiAliasingPattern.QUINCUNX;
        }
    } catch (ParseException exp) {
        System.out.println("Unexpected exception:" + exp.getMessage());
    } catch (NumberFormatException nfe) {
        formatter.printHelp("RotationGrid", options);
    }

    asr = new CPUAlgebraicSurfaceRenderer();

    scale = new Matrix4d();
    scale.setIdentity();
    setScale(0.0);

    basic_rotation = new Matrix4d();
    basic_rotation.setIdentity();

    additional_rotation = new Matrix4d();
    additional_rotation.setIdentity();

    try {
        loadFromFile(new File(jsurf_filename).toURI().toURL());
    } catch (Exception e) {
        e.printStackTrace();
    }
    setOptimalCameraDistance(asr.getCamera());
    try {
        BufferedImage bi = renderAnimGrid(xAngleMin, xAngleMax, xSteps, yAngleMin, yAngleMax, ySteps);
        if (output_filename == null)
            saveToPNG(System.out, bi);
        else
            saveToPNG(new FileOutputStream(new File("test.png")), bi);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.msu.cme.rdp.classifier.train.validation.distance.PairwiseSeqDistance.java

/**
* This program does the pairwise alignment between each pair of sequences, 
* reports a summary of the average distances and the stdev at each rank.
* @param args// ww w  .  ja  va 2  s .  co  m
* @throws Exception 
*/
public static void main(String[] args) throws Exception {

    String trainseqFile = null;
    String taxFile = null;
    PrintStream outStream = null;
    AlignmentMode mode = AlignmentMode.overlap;
    boolean show_alignment = false;

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

        if (line.hasOption("show_alignment")) {
            show_alignment = true;
        }
        if (line.hasOption("alignment-mode")) {
            String m = line.getOptionValue("alignment-mode").toLowerCase();
            mode = AlignmentMode.valueOf(m);

        }

        if (args.length != 3) {
            throw new Exception("wrong arguments");
        }
        args = line.getArgs();
        trainseqFile = args[0];
        taxFile = args[1];
        outStream = new PrintStream(new File(args[2]));
    } catch (Exception e) {
        System.err.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(80, " [options] trainseqFile taxonFile outFile", "", options, "");
        return;
    }

    PairwiseSeqDistance theObj = new PairwiseSeqDistance(trainseqFile, taxFile, mode, show_alignment);

    theObj.printSummary(outStream);
}

From source file:com.google.flightmap.parsing.faa.afd.AfdCommParser.java

public static void main(String args[]) {
    CommandLine line = null;/*from w ww .j  a  va 2 s .  c o  m*/
    try {
        final CommandLineParser parser = new PosixParser();
        line = parser.parse(OPTIONS, args);
    } catch (ParseException pEx) {
        System.err.println(pEx.getMessage());
        printHelp(line);
        System.exit(1);
    }

    if (line.hasOption(HELP_OPTION)) {
        printHelp(line);
        System.exit(0);
    }

    final String afdFile = line.getOptionValue(AFD_OPTION);
    final String iataToIcaoFile = line.getOptionValue(IATA_TO_ICAO_OPTION);
    final String dbFile = line.getOptionValue(AVIATION_DB_OPTION);

    (new AfdCommParser(afdFile, iataToIcaoFile, dbFile)).execute();
}

From source file:at.ac.tuwien.inso.subcat.miner.MinerRunner.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("h", "help", false, "Show this options");
    options.addOption("m", "miner-help", false, "Show miner specific options");
    options.addOption("d", "db", true, "The database to process (required)");
    options.addOption("p", "project", true, "The project ID to process");
    options.addOption("P", "list-projects", false, "List all registered projects");
    options.addOption("v", "verbose", false, "Show details");

    options.addOption(null, "bug-repo", true, "Bug Repository URL");
    options.addOption(null, "bug-product", true, "Bug Product Name");
    options.addOption(null, "bug-tracker", true, "Bug Tracker name (e.g. bugzilla)");
    options.addOption(null, "bug-account", true, "Bug account name");
    options.addOption(null, "bug-passwd", true, "Bug account password");
    options.addOption(null, "bug-enable-untrusted", false, "Accept untrusted certificates");
    options.addOption(null, "bug-threads", true, "Thread count used in bug miners");
    options.addOption(null, "bug-cooldown-time", true, "Bug cooldown time");
    options.addOption(null, "bug-miner-option", true, "Bug miner specific option. Format: <option-name>:value");
    options.addOption(null, "bug-update", false, "Mine all changes since the last run");
    options.getOption("bug-miner-option").setArgs(Option.UNLIMITED_VALUES);

    options.addOption(null, "src-path", true, "Local source repository path");
    options.addOption(null, "src-remote", true, "Remote address");
    options.addOption(null, "src-passwd", true, "Source repository account password");
    options.addOption(null, "src-account", true, "Source repository account name");
    options.addOption(null, "src-miner-option", true,
            "Source miner specific option. Format: <option-name>:value");
    options.getOption("src-miner-option").setArgs(Option.UNLIMITED_VALUES);

    final Reporter reporter = new Reporter(true);
    reporter.startTimer();//  ww w  .  j  av  a 2 s .  co  m

    boolean printTraces = false;
    Settings settings = new Settings();
    ModelPool pool = null;

    CommandLineParser parser = new PosixParser();

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

        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("postprocessor", options);
            return;
        }

        if (cmd.hasOption("miner-help")) {
            init();
            for (MetaData meta : registeredMiner) {
                System.out.println(meta.name());
                for (Entry<String, ParamType> opt : meta.getSpecificParams().entrySet()) {
                    System.out.println("  - " + opt.getKey() + " (" + opt.getValue() + ")");
                }
            }
            return;
        }

        if (cmd.hasOption("db") == false) {
            reporter.error("miner", "Option --db is required");
            reporter.printSummary();
            return;
        }

        printTraces = cmd.hasOption("verbose");
        pool = new ModelPool(cmd.getOptionValue("db"), 2);

        if (cmd.hasOption("list-projects")) {
            Model model = pool.getModel();

            for (Project proj : model.getProjects()) {
                System.out.println("  " + proj.getId() + ": " + proj.getDate());
            }

            model.close();
            return;
        }

        Project project;
        Model model = pool.getModel();
        boolean hasSrcInfos = false;
        boolean hasBugInfos = false;
        if (cmd.hasOption("project")) {
            try {
                int projId = Integer.parseInt(cmd.getOptionValue("project"));
                project = model.getProject(projId);
            } catch (NumberFormatException e) {
                reporter.error("post-processor", "Invalid project ID");
                reporter.printSummary();
                return;
            }

            if (project == null) {
                reporter.error("post-processor", "Invalid project ID");
                reporter.printSummary();
                return;
            }

            List<String> flags = model.getFlags(project);
            hasBugInfos = flags.contains(Model.FLAG_BUG_INFO);
            hasSrcInfos = flags.contains(Model.FLAG_SRC_INFO);
        } else {
            project = model.addProject(new Date(), null, settings.bugTrackerName, settings.bugRepository,
                    settings.bugProductName, null);
        }
        model.close();

        //
        // Source Repository Mining:
        //

        settings.srcLocalPath = cmd.getOptionValue("src-path");
        settings.srcRemote = cmd.getOptionValue("src-remote");
        settings.srcRemotePw = cmd.getOptionValue("src-passwd");
        settings.srcRemoteUser = cmd.getOptionValue("src-account");

        if (settings.srcRemotePw == null || settings.srcRemoteUser == null) {
            if (settings.srcRemotePw != null) {
                reporter.error("miner", "--src-passwd should only be used in combination with --src-account");
                reporter.printSummary();
                return;
            } else if (settings.srcRemoteUser != null) {
                reporter.error("miner", "--src-account should only be used in combination with --src-passwd");
                reporter.printSummary();
                return;
            }
        }

        if (settings.srcRemoteUser != null && settings.srcRemote == null) {
            reporter.error("miner", "--src-account should only be used in combination with --src-remote");
            reporter.printSummary();
            return;
        }

        if (settings.srcLocalPath != null && hasSrcInfos) {
            reporter.error("miner", "Source repository updates are not supported yet.");
            reporter.printSummary(true);
            return;
        }

        //
        // Bug Repository Mining:
        //

        settings.bugRepository = cmd.getOptionValue("bug-repo");
        settings.bugProductName = cmd.getOptionValue("bug-product");
        settings.bugTrackerName = cmd.getOptionValue("bug-tracker");
        settings.bugEnableUntrustedCertificates = cmd.hasOption("bug-enable-untrusted");
        settings.bugLoginUser = cmd.getOptionValue("bug-account");
        settings.bugLoginPw = cmd.getOptionValue("bug-passwd");

        settings.bugUpdate = cmd.hasOption("bug-update");
        boolean includeBugs = false;
        if (settings.bugUpdate) {
            if (project.getBugTracker() == null || project.getDomain() == null) {
                reporter.error("miner",
                        "flag --bug-update is requires previously mined bugs. Use --bug-repository, --bug-product and --bug-tracker.");
                reporter.printSummary(true);
                return;
            }
            if (settings.bugTrackerName != null) {
                reporter.warning("miner", "flag --bug-tracker without effect");
            }
            if (settings.bugProductName != null) {
                reporter.warning("miner", "flag --bug-product without effect");
            }
            if (settings.bugRepository != null) {
                reporter.warning("miner", "flag --bug-repository without effect");
            }

            settings.bugTrackerName = project.getBugTracker();
            settings.bugProductName = project.getProduct();
            settings.bugRepository = project.getDomain();
            includeBugs = true;
        } else if (settings.bugRepository != null && settings.bugProductName != null
                && settings.bugTrackerName != null) {
            if (hasBugInfos == false) {
                // The user is trying to append bug tracker information to a existing project.
            } else if (!settings.bugTrackerName.equalsIgnoreCase(project.getBugTracker())
                    || !settings.bugProductName.equalsIgnoreCase(project.getProduct())
                    || !settings.bugRepository.equalsIgnoreCase(project.getDomain())) {
                reporter.error("miner",
                        "There are already previously mined bugs for this project. Use --bug-update to update the database.");
                reporter.printSummary(true);
                return;
            }
            if (settings.bugRepository == null) {
                reporter.error("miner", "flag --bug-repository is required");
                reporter.printSummary(true);
                return;
            }
            if (settings.bugProductName == null) {
                reporter.error("miner", "flag --bug-product is required");
                reporter.printSummary(true);
                return;
            }
            includeBugs = true;
        }

        if (includeBugs) {
            if (settings.bugLoginPw == null || settings.bugLoginUser == null) {
                if (settings.bugLoginPw != null) {
                    reporter.error("miner",
                            "--bug-passwd should only be used in combination with --bug-account");
                    reporter.printSummary();
                    return;
                } else if (settings.bugLoginUser != null) {
                    reporter.error("miner",
                            "--bug-account should only be used in combination with --bug-passwd");
                    reporter.printSummary();
                    return;
                }
            }

            if (cmd.hasOption("bug-threads")) {
                try {
                    settings.bugThreads = Integer.parseInt(cmd.getOptionValue("bug-threads"));
                } catch (Exception e) {
                    reporter.error("miner", "--bug-threads: Invalid parameter type");
                    reporter.printSummary();
                    return;
                }
            }

            if (cmd.hasOption("bug-cooldown-time")) {
                try {
                    settings.bugCooldownTime = Integer.parseInt(cmd.getOptionValue("bug-cooldown-time"));
                } catch (Exception e) {
                    reporter.error("miner", "--bug-cooldown-time: Invalid parameter type");
                    reporter.printSummary();
                    return;
                }
            }

            if (cmd.hasOption("bug-miner-option")) {
                for (String str : cmd.getOptionValues("bug-miner-option")) {
                    addSpecificParameter(settings.bugSpecificParams, str);
                }
            }

            if (cmd.hasOption("src-miner-option")) {
                for (String str : cmd.getOptionValues("src-miner-option")) {
                    addSpecificParameter(settings.srcSpecificParams, str);
                }
            }
        } else {
            if (settings.bugLoginPw != null) {
                reporter.error("miner", "--bug-passwd should only be used in combination with --bug-account");
                reporter.printSummary();
                return;
            }
            if (settings.bugLoginUser != null) {
                reporter.error("miner", "--bug-account should only be used in combination with --bug-account");
                reporter.printSummary();
                return;
            }
            if (settings.bugRepository != null) {
                reporter.error("miner",
                        "--bug-repo should only be used in combination with --bug-product and --bug-tracker");
                reporter.printSummary();
                return;
            }
            if (settings.bugProductName != null) {
                reporter.error("miner",
                        "--bug-product should only be used in combination with --bug-repo and --bug-tracker");
                reporter.printSummary();
                return;
            }
            if (settings.bugTrackerName != null) {
                reporter.error("miner",
                        "--bug-tracker should only be used in combination with --bug-repo and --bug-product");
                reporter.printSummary();
                return;
            }
            if (settings.bugEnableUntrustedCertificates) {
                reporter.error("miner",
                        "--bug-enable-untrusted should only be used in combination with --bug-repo, --bug-tracker and --bug-product");
                reporter.printSummary();
                return;
            }
            if (settings.bugUpdate) {
                reporter.error("miner",
                        "--bug-update should only be used in combination with --bug-repo, --bug-tracker and --bug-product");
                reporter.printSummary();
                return;
            }
            if (cmd.hasOption("bug-threads")) {
                reporter.error("miner",
                        "--bug-threads should only be used in combination with --bug-repo, --bug-tracker and --bug-product");
                reporter.printSummary();
                return;
            }
            if (cmd.hasOption("bug-cooldown-time")) {
                reporter.error("miner",
                        "--bug-cooldown-time should only be used in combination with --bug-repo, --bug-tracker and --bug-product");
                reporter.printSummary();
                return;
            }
            if (cmd.hasOption("bug-miner-option")) {
                reporter.error("miner",
                        "--bug-miner-option should only be used in combination with --bug-repo, --bug-tracker and --bug-product");
                reporter.printSummary();
                return;
            }
        }

        //
        // Run:
        //

        MinerRunner runner = new MinerRunner(pool, project, settings, reporter);
        if (cmd.hasOption("verbose")) {
            runner.addListener(new MinerListener() {
                private Map<Miner, Integer> totals = new HashMap<Miner, Integer>();

                @Override
                public void start(Miner miner) {
                }

                @Override
                public void end(Miner miner) {
                }

                @Override
                public void stop(Miner miner) {
                }

                @Override
                public void tasksTotal(Miner miner, int count) {
                    totals.put(miner, count);
                }

                @Override
                public void tasksProcessed(Miner miner, int processed) {
                    Integer total = totals.get(miner);
                    reporter.note(miner.getName(),
                            "status: " + processed + "/" + ((total == null) ? "0" : total));
                }
            });
        }

        runner.run();
    } catch (ParameterException e) {
        reporter.error(e.getMiner().getName(), e.getMessage());
    } catch (ParseException e) {
        reporter.error("miner", "Parsing failed: " + e.getMessage());
        if (printTraces == true) {
            e.printStackTrace();
        }
    } catch (ClassNotFoundException e) {
        reporter.error("miner", "Failed to create a database connection: " + e.getMessage());
        if (printTraces == true) {
            e.printStackTrace();
        }
    } catch (SQLException e) {
        reporter.error("miner", "Failed to create a database connection: " + e.getMessage());
        if (printTraces == true) {
            e.printStackTrace();
        }
    } catch (MinerException e) {
        reporter.error("miner", "Mining Error: " + e.getMessage());
        if (printTraces == true) {
            e.printStackTrace();
        }
    } finally {
        if (pool != null) {
            pool.close();
        }
    }

    reporter.printSummary(true);
}

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

/**
 * @param args//www.j a  v a 2  s.co  m
 */
public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

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

    opt = new Option(OPT_REFFILE, true,
            "Reference file of molecules which define pre-existign exclusion spheres.");
    options.addOption(opt);

    opt = new Option(OPT_RADIUS, true, "Radius of exclusion spehre in A2.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_GROUPBY, true,
            "Group by fieldname, run sphere exclusion for consecutive groups of records with same value for this field.");
    options.addOption(opt);

    opt = new Option(OPT_DONotOpt, false,
            "If specified the RMSD is computed without trying to optimize the alignment.");
    options.addOption(opt);

    opt = new Option(OPT_PRINT_All, false, "print all molecule, check includeIdx tag");
    options.addOption(opt);

    opt = new Option(OPT_MIRROR, false, "For non-chiral molecules also try mirror image");
    options.addOption(opt);

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

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

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    String refFile = cmd.getOptionValue(OPT_REFFILE);
    String groupBy = cmd.getOptionValue(OPT_GROUPBY);
    boolean doOptimize = !cmd.hasOption(OPT_DONotOpt);
    double radius = Double.parseDouble(cmd.getOptionValue(OPT_RADIUS));
    boolean printAll = cmd.hasOption(OPT_PRINT_All);
    boolean doMirror = cmd.hasOption(OPT_MIRROR);

    SdfRMSDSphereExclusion sphereExclusion = new SdfRMSDSphereExclusion(refFile, outFile, radius, printAll,
            doMirror, doOptimize, groupBy);

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

From source file:com.cyberway.issue.crawler.extractor.ExtractorTool.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(new Option("h", "help", false, "Prints this message and exits."));
    StringBuffer defaultExtractors = new StringBuffer();
    for (int i = 0; i < DEFAULT_EXTRACTORS.length; i++) {
        if (i > 0) {
            defaultExtractors.append(", ");
        }/*from   ww  w.j  ava2 s. c  o  m*/
        defaultExtractors.append(DEFAULT_EXTRACTORS[i]);
    }
    options.addOption(new Option("e", "extractor", true,
            "List of comma-separated extractor class names. " + "Run in order listed. "
                    + "If no extractors listed, runs following: " + defaultExtractors.toString() + "."));
    options.addOption(
            new Option("s", "scratch", true, "Directory to write scratch files to. Default: '/tmp'."));
    PosixParser parser = new PosixParser();
    CommandLine cmdline = parser.parse(options, args, false);
    List cmdlineArgs = cmdline.getArgList();
    Option[] cmdlineOptions = cmdline.getOptions();
    HelpFormatter formatter = new HelpFormatter();
    // If no args, print help.
    if (cmdlineArgs.size() <= 0) {
        usage(formatter, options, 0);
    }

    // Now look at options passed.
    String[] extractors = DEFAULT_EXTRACTORS;
    String scratch = null;
    for (int i = 0; i < cmdlineOptions.length; i++) {
        switch (cmdlineOptions[i].getId()) {
        case 'h':
            usage(formatter, options, 0);
            break;

        case 'e':
            String value = cmdlineOptions[i].getValue();
            if (value == null || value.length() <= 0) {
                // Allow saying NO extractors so we can see
                // how much it costs just reading through
                // ARCs.
                extractors = new String[0];
            } else {
                extractors = value.split(",");
            }
            break;

        case 's':
            scratch = cmdlineOptions[i].getValue();
            break;

        default:
            throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId());
        }
    }

    ExtractorTool tool = new ExtractorTool(extractors, scratch);
    for (Iterator i = cmdlineArgs.iterator(); i.hasNext();) {
        tool.extract((String) i.next());
    }
}