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

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

Introduction

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

Prototype

public String[] getArgs() 

Source Link

Document

Retrieve any left-over non-recognized options and arguments

Usage

From source file:de.topobyte.livecg.ShowVisualization.java

public static void main(String[] args) {
    EnumNameLookup<Visualization> visualizationSwitch = new EnumNameLookup<Visualization>(Visualization.class,
            true);/*  w  w  w  .  j ava 2s  .  c  o m*/

    // @formatter:off
    Options options = new Options();
    OptionHelper.add(options, OPTION_CONFIG, true, false, "path", "config file");
    OptionHelper.add(options, OPTION_VISUALIZATION, true, true, "type",
            "type of visualization. one of <" + VisualizationUtil.getListOfAvailableVisualizations() + ">");
    OptionHelper.add(options, OPTION_STATUS, true, false,
            "status to " + "set the algorithm to. The format depends on the algorithm");
    // @formatter:on

    Option propertyOption = new Option(OPTION_PROPERTIES, "set a special property");
    propertyOption.setArgName("property=value");
    propertyOption.setArgs(2);
    propertyOption.setValueSeparator('=');
    options.addOption(propertyOption);

    CommandLineParser clp = new GnuParser();

    CommandLine line = null;
    try {
        line = clp.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Parsing command line failed: " + e.getMessage());
        new HelpFormatter().printHelp(HELP_MESSAGE, options);
        System.exit(1);
    }

    String[] extra = line.getArgs();
    if (extra.length == 0) {
        System.out.println("Missing file argument");
        new HelpFormatter().printHelp(HELP_MESSAGE, options);
        System.exit(1);
    }
    String input = extra[0];

    StringOption argConfig = ArgumentHelper.getString(line, OPTION_CONFIG);
    if (argConfig.hasValue()) {
        String configPath = argConfig.getValue();
        LiveConfig.setPath(configPath);
    }

    StringOption argVisualization = ArgumentHelper.getString(line, OPTION_VISUALIZATION);
    StringOption argStatus = ArgumentHelper.getString(line, OPTION_STATUS);

    Visualization visualization = visualizationSwitch.find(argVisualization.getValue());
    if (visualization == null) {
        System.err.println("Unsupported visualization '" + argVisualization.getValue() + "'");
        System.exit(1);
    }

    System.out.println("Visualization: " + visualization);

    ContentReader contentReader = new ContentReader();
    Content content = null;
    try {
        content = contentReader.read(new File(input));
    } catch (Exception e) {
        System.out.println("Error while reading input file '" + input + "'. Exception type: "
                + e.getClass().getSimpleName() + ", message: " + e.getMessage());
        System.exit(1);
    }

    Properties properties = line.getOptionProperties(OPTION_PROPERTIES);

    ContentLauncher launcher = null;

    switch (visualization) {
    case GEOMETRY: {
        launcher = new ContentDisplayLauncher();
        break;
    }
    case DCEL: {
        launcher = new DcelLauncher();
        break;
    }
    case FREESPACE: {
        launcher = new FreeSpaceChainsLauncher();
        break;
    }
    case DISTANCETERRAIN: {
        launcher = new DistanceTerrainChainsLauncher();
        break;
    }
    case CHAN: {
        launcher = new ChanLauncher();
        break;
    }
    case FORTUNE: {
        launcher = new FortunesSweepLauncher();
        break;
    }
    case MONOTONE_PIECES: {
        launcher = new MonotonePiecesLauncher();
        break;
    }
    case MONOTONE_TRIANGULATION: {
        launcher = new MonotoneTriangulationLauncher();
        break;
    }
    case TRIANGULATION: {
        launcher = new MonotonePiecesTriangulationLauncher();
        break;
    }
    case SPIP: {
        launcher = new ShortestPathInPolygonLauncher();
        break;
    }
    case BUFFER: {
        launcher = new PolygonBufferLauncher();
        break;
    }
    }

    try {
        launcher.launch(content, true);
    } catch (LaunchException e) {
        System.err.println("Unable to start visualization");
        System.err.println("Error message: " + e.getMessage());
        System.exit(1);
    }
}

From source file:ca.ualberta.exemplar.evaluation.BenchmarkBinary.java

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

    CommandLineParser parser = new BasicParser();

    Options options = new Options();
    options.addOption("p", "parser", true, "Which parser to use. (stanford | malt)");

    CommandLine line = null;

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

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

    System.out.println("Using " + parserName + " parser");

    File evaluationFile = new File(args[0]);
    File outputFile = new File(args[1]);

    BenchmarkBinary evaluation = new BenchmarkBinary(evaluationFile, outputFile, parserName);

    //read evaluation file with sentences annotated with golden statements
    // and run Exemplar over them.
    evaluation.runAndTime();

}

From source file:io.druid.server.sql.SQLRunner.java

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

    Options options = new Options();
    options.addOption("h", "help", false, "help");
    options.addOption("v", false, "verbose");
    options.addOption("e", "host", true, "endpoint [hostname:port]");

    CommandLine cmd = new GnuParser().parse(options, args);

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("SQLRunner", options);
        System.exit(2);/*  w  w  w .  ja  v  a  2 s  . c  om*/
    }

    String hostname = cmd.getOptionValue("e", "localhost:8080");
    String sql = cmd.getArgs().length > 0 ? cmd.getArgs()[0] : STATEMENT;

    ObjectMapper objectMapper = new DefaultObjectMapper();
    ObjectWriter jsonWriter = objectMapper.writerWithDefaultPrettyPrinter();

    CharStream stream = new ANTLRInputStream(sql);
    DruidSQLLexer lexer = new DruidSQLLexer(stream);
    TokenStream tokenStream = new CommonTokenStream(lexer);
    DruidSQLParser parser = new DruidSQLParser(tokenStream);
    lexer.removeErrorListeners();
    parser.removeErrorListeners();

    lexer.addErrorListener(ConsoleErrorListener.INSTANCE);
    parser.addErrorListener(ConsoleErrorListener.INSTANCE);

    try {
        DruidSQLParser.QueryContext queryContext = parser.query();
        if (parser.getNumberOfSyntaxErrors() > 0)
            throw new IllegalStateException();
        //      parser.setBuildParseTree(true);
        //      System.err.println(q.toStringTree(parser));
    } catch (Exception e) {
        String msg = e.getMessage();
        if (msg != null)
            System.err.println(e);
        System.exit(1);
    }

    final Query query;
    final TypeReference typeRef;
    boolean groupBy = false;
    if (parser.groupByDimensions.isEmpty()) {
        query = Druids.newTimeseriesQueryBuilder().dataSource(parser.getDataSource())
                .aggregators(new ArrayList<AggregatorFactory>(parser.aggregators.values()))
                .postAggregators(parser.postAggregators).intervals(parser.intervals)
                .granularity(parser.granularity).filters(parser.filter).build();

        typeRef = new TypeReference<List<Result<TimeseriesResultValue>>>() {
        };
    } else {
        query = GroupByQuery.builder().setDataSource(parser.getDataSource())
                .setAggregatorSpecs(new ArrayList<AggregatorFactory>(parser.aggregators.values()))
                .setPostAggregatorSpecs(parser.postAggregators).setInterval(parser.intervals)
                .setGranularity(parser.granularity).setDimFilter(parser.filter)
                .setDimensions(new ArrayList<DimensionSpec>(parser.groupByDimensions.values())).build();

        typeRef = new TypeReference<List<Row>>() {
        };
        groupBy = true;
    }

    String queryStr = jsonWriter.writeValueAsString(query);
    if (cmd.hasOption("v"))
        System.err.println(queryStr);

    URL url = new URL(String.format("http://%s/druid/v2/?pretty", hostname));
    final URLConnection urlConnection = url.openConnection();
    urlConnection.addRequestProperty("content-type", MediaType.APPLICATION_JSON);
    urlConnection.getOutputStream().write(StringUtils.toUtf8(queryStr));
    BufferedReader stdInput = new BufferedReader(
            new InputStreamReader(urlConnection.getInputStream(), Charsets.UTF_8));

    Object res = objectMapper.readValue(stdInput, typeRef);

    Joiner tabJoiner = Joiner.on("\t");

    if (groupBy) {
        List<Row> rows = (List<Row>) res;
        Iterable<String> dimensions = Iterables.transform(parser.groupByDimensions.values(),
                new Function<DimensionSpec, String>() {
                    @Override
                    public String apply(@Nullable DimensionSpec input) {
                        return input.getOutputName();
                    }
                });

        System.out.println(
                tabJoiner.join(Iterables.concat(Lists.newArrayList("timestamp"), dimensions, parser.fields)));
        for (final Row r : rows) {
            System.out.println(tabJoiner.join(Iterables.concat(
                    Lists.newArrayList(parser.granularity.toDateTime(r.getTimestampFromEpoch())),
                    Iterables.transform(parser.groupByDimensions.values(),
                            new Function<DimensionSpec, String>() {
                                @Override
                                public String apply(@Nullable DimensionSpec input) {
                                    return Joiner.on(",").join(r.getDimension(input.getOutputName()));
                                }
                            }),
                    Iterables.transform(parser.fields, new Function<String, Object>() {
                        @Override
                        public Object apply(@Nullable String input) {
                            return r.getFloatMetric(input);
                        }
                    }))));
        }
    } else {
        List<Result<TimeseriesResultValue>> rows = (List<Result<TimeseriesResultValue>>) res;
        System.out.println(tabJoiner.join(Iterables.concat(Lists.newArrayList("timestamp"), parser.fields)));
        for (final Result<TimeseriesResultValue> r : rows) {
            System.out.println(tabJoiner.join(Iterables.concat(Lists.newArrayList(r.getTimestamp()),
                    Lists.transform(parser.fields, new Function<String, Object>() {
                        @Override
                        public Object apply(@Nullable String input) {
                            return r.getValue().getMetric(input);
                        }
                    }))));
        }
    }

    CloseQuietly.close(stdInput);
}

From source file:edu.msu.cme.rdp.alignment.errorcheck.CompareErrorType.java

public static void main(String[] args) throws IOException {
    Options options = new Options();
    options.addOption("s", "stem", true, "Output stem (default <query_nucl.fasta>)");

    final SeqReader queryReader;
    final List<Sequence> refSeqList;
    final PrintStream alignOutStream;
    final CompareErrorType errorProcessor;
    Sequence seq;//from  w  w  w  . j  a v  a  2  s .  c o  m
    Map<String, PAObject> matchMap = new HashMap();

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

        String stem;

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

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

        if (line.hasOption("stem")) {
            stem = line.getOptionValue("stem");
        } else {
            stem = queryFile.getName();
        }

        File alignOutFile = new File(stem + "_alignments.txt");
        File mismatchOutFile = new File(stem + "_mismatches.txt");
        File indelOutFile = new File(stem + "_indels.txt");
        File qualOutFile = null;

        refSeqList = SequenceReader.readFully(refFile);
        if (args.length == 3) {
            queryReader = new QSeqReader(queryFile, new File(args[2]));
        } else {
            queryReader = new SequenceReader(queryFile);
        }

        seq = queryReader.readNextSequence();
        if (seq instanceof QSequence) {
            qualOutFile = new File(stem + "_qual.txt");
        }

        errorProcessor = new CompareErrorType(mismatchOutFile, indelOutFile, qualOutFile);
        alignOutStream = new PrintStream(alignOutFile);

        System.err.println("Starting CompareErrorType");
        System.err.println("*  Time:              " + new Date());
        System.err.println("*  Reference File:    " + refFile);
        System.err.println("*  Query File:        " + queryFile);
        if (args.length == 3) {
            System.err.println("*  Qual File:         " + args[2]);
        }
        System.err.println("*  Query format:      " + queryReader.getFormat());
        System.err.println("*  Alignment Output:  " + alignOutFile);
        System.err.println("*  Mismatches Output: " + mismatchOutFile);
        System.err.println("*  Alignment Output:  " + indelOutFile);
        if (qualOutFile != null) {
            System.err.println("*  Quality Output:    " + qualOutFile);
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp(
                "CompareErrorType [options] <ref_nucl> (<query_nucl> | <query_nucl.fasta> <query_nucl.qual>)",
                options);
        System.err.println("ERROR: " + e.getMessage());
        throw new RuntimeException(e);
        //System.exit(1);
        //return;
    }

    //ScoringMatrix scoringMatrix = ScoringMatrix.getDefaultNuclMatrix();
    // use a simple scoring function, match score 0, mismatch -1, gap opening -1, gap extension -1.
    ScoringMatrix scoringMatrix = new ScoringMatrix(
            ScoringMatrix.class.getResourceAsStream("/data/simple_scoringmatrix.txt"), -1, -1);

    do {
        try {
            PairwiseAlignment bestResult = null;
            Sequence bestSeq = null;
            boolean bestReversed = false;
            String querySeqStr = seq.getSeqString().toLowerCase();
            String reversedQuery = IUBUtilities.reverseComplement(querySeqStr);
            PAObject bestMatch = null;

            //checking if sequence has been seen before
            if (matchMap.containsKey(seq.getSeqString())) {
                bestMatch = matchMap.get(seq.getSeqString());
            } else {
                for (Sequence refSeq : refSeqList) {
                    String refSeqStr = refSeq.getSeqString().toLowerCase();
                    PairwiseAlignment result = PairwiseAligner.align(refSeqStr, querySeqStr, scoringMatrix,
                            AlignmentMode.global);
                    PairwiseAlignment reversedResult = PairwiseAligner.align(refSeqStr,
                            IUBUtilities.reverseComplement(querySeqStr), scoringMatrix, AlignmentMode.global);

                    PairwiseAlignment currBest = (result.getScore() > reversedResult.getScore()) ? result
                            : reversedResult;

                    if (bestResult == null || currBest.getScore() > bestResult.getScore()) {
                        bestResult = currBest;
                        bestSeq = refSeq;
                        if (currBest == reversedResult) {
                            bestReversed = true;
                        } else {
                            bestReversed = false;
                        }

                    }

                    //Since this is a new sequence, make a new PAObject to put into the map to compare against later
                    bestMatch = new PAObject(bestResult, bestReversed, bestSeq);
                    matchMap.put(seq.getSeqString(), bestMatch);
                }
            }
            int refStart = bestMatch.getPA().getStarti();
            int refEnd = bestMatch.getPA().getEndi();
            bestSeq = bestMatch.getRefSeq();
            bestReversed = bestMatch.getReversed();
            bestResult = bestMatch.getPA();

            //output information
            alignOutStream.println(">\t" + seq.getSeqName() + "\t" + bestSeq.getSeqName() + "\t"
                    + seq.getSeqString().length() + "\t" + refStart + "\t" + refEnd + "\t"
                    + bestResult.getScore() + "\t" + ((bestReversed) ? "\treversed" : ""));
            alignOutStream.println(bestResult.getAlignedSeqj() + "\n");
            alignOutStream.println(bestResult.getAlignedSeqi() + "\n");

            //seqi is reference seq, seqj is the refseq
            errorProcessor.processSequence(seq, bestResult.getAlignedSeqj(), bestSeq.getSeqName(),
                    bestResult.getAlignedSeqi(), refStart, bestReversed);

        } catch (Exception e) {
            throw new RuntimeException("Failed while processing seq " + seq.getSeqName(), e);
        }
    } while ((seq = queryReader.readNextSequence()) != null);
    queryReader.close();
    alignOutStream.close();
    errorProcessor.close();
}

From source file:es.eucm.ead.exporter.ExporterMain.java

@SuppressWarnings("all")
public static void main(String args[]) {

    Options options = new Options();

    Option help = new Option("h", "help", false, "print this message");
    Option quiet = new Option("q", "quiet", false, "be extra quiet");
    Option verbose = new Option("v", "verbose", false, "be extra verbose");

    Option legacy = OptionBuilder.withArgName("s> <t").hasArgs(3)
            .withDescription(//from   w w  w . jav a 2 s.  c  o  m
                    "source is a version 1.x game; must specify\n" + "<simplify> if 'true', simplifies result\n"
                            + "<translate> if 'true', enables translation")
            .withLongOpt("import").create("i");

    Option war = OptionBuilder.withArgName("web-base").hasArg()
            .withDescription("WAR packaging (web app); " + "must specify\n<web-base> the base WAR directory")
            .withLongOpt("war").create("w");

    Option jar = OptionBuilder.withDescription("JAR packaging (desktop)").withLongOpt("jar").create("j");

    Option apk = OptionBuilder.withArgName("props> <adk> <d").hasArgs(3)
            .withDescription("APK packaging (android); must specify \n" + "<props> (a properties file) \n"
                    + "<adk> (location of the ADK to use) \n" + "<deploy> ('true' to install & deploy)")
            .withLongOpt("apk").create("a");

    // EAD option
    Option ead = OptionBuilder.withDescription("EAD packaging (eAdventure)").withLongOpt("ead").create("e");

    options.addOption(legacy);
    options.addOption(help);
    options.addOption(quiet);
    options.addOption(verbose);
    options.addOption(jar);
    options.addOption(war);
    options.addOption(apk);
    options.addOption(ead);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println("Error parsing command-line: " + pe.getMessage());
        showHelp(options);
        return;
    }

    // general options

    String[] extras = cmd.getArgs();

    if (cmd.hasOption(help.getOpt()) || extras.length < 2) {
        showHelp(options);
        return;
    }
    if (cmd.hasOption(verbose.getOpt())) {
        verbosity = Verbose;
    }
    if (cmd.hasOption(quiet.getOpt())) {
        verbosity = Quiet;
    }

    // import

    String source = extras[0];

    // optional import step
    if (cmd.hasOption(legacy.getOpt())) {
        String[] values = cmd.getOptionValues(legacy.getOpt());

        AdventureConverter converter = new AdventureConverter();
        if (values.length > 0 && values[0].equalsIgnoreCase("true")) {
            converter.setEnableSimplifications(true);
        }
        if (values.length > 1 && values[1].equalsIgnoreCase("true")) {
            converter.setEnableTranslations(true);
        }

        // set source for next steps to import-target
        source = converter.convert(source, null);
    }

    if (cmd.hasOption(jar.getOpt())) {
        if (checkFilesExist(cmd, options, source)) {
            JarExporter e = new JarExporter();
            e.export(source, extras[1], verbosity.equals(Quiet) ? new QuietStream() : System.err);
        }
    } else if (cmd.hasOption(apk.getOpt())) {
        String[] values = cmd.getOptionValues(apk.getOpt());
        if (checkFilesExist(cmd, options, values[0], values[1], source)) {
            AndroidExporter e = new AndroidExporter();
            Properties props = new Properties();
            File propsFile = new File(values[0]);
            try {
                props.load(new FileReader(propsFile));
                props.setProperty(AndroidExporter.SDK_HOME,
                        props.getProperty(AndroidExporter.SDK_HOME, values[1]));
            } catch (IOException ioe) {
                System.err.println("Could not load properties from " + propsFile.getAbsolutePath());
                return;
            }
            e.export(source, extras[1], props, values.length > 2 && values[2].equalsIgnoreCase("true"));
        }
    } else if (cmd.hasOption(war.getOpt())) {
        if (checkFilesExist(cmd, options, extras[0])) {
            WarExporter e = new WarExporter();
            e.setWarPath(cmd.getOptionValue(war.getOpt()));
            e.export(source, extras[1]);
        }
    } else if (cmd.hasOption(ead.getOpt())) {
        String destiny = extras[1];
        if (!destiny.endsWith(".ead")) {
            destiny += ".ead";
        }
        FileUtils.zip(new File(destiny), new File(source));
    } else {
        showHelp(options);
    }
}

From source file:com.genentech.chemistry.tool.SDFSelectivityCalculator.java

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

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

    opt = new Option(OPT_NUMERATOR, true, "Name of the field containing the numerator value.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_NUMERATOR_OP, true,
            "Name of the field containing the numerator operator."
                    + " If this option is not set it is assumed that the operator" + " is included in the "
                    + OPT_NUMERATOR + " field.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_DENOMINATOR, true, "Name of the field containing the denominator value.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_DENOMINATOR_OP, true,
            "Name of the field containing the denominator operator."
                    + " If this option is not set it is assumed that the operator" + " is included in the "
                    + OPT_DENOMINATOR + " field.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_SELECTIVITY, true, "Name of the field containing the output selectivity value."
            + " If this option is not set, the field name of the denominator" + " is used.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_SELECTIVITY_OP, true,
            "Name of the field containing the output selectivity operator."
                    + " If this option is not set it is assumed that the operator" + " is included in the "
                    + OPT_SELECTIVITY + " field.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_OUTPUT_MODE, true,
            "Valid: separate, combine, combine+op;" + " If not specified, default is combine+op."
                    + " (separate=operator and value in separate fields;"
                    + " combine=operator and value in one field;"
                    + " combine+op=one field with the operator and value and"
                    + " plus one field with only the operator)");
    opt.setRequired(false);
    options.addOption(opt);

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

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

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    String outputMode = cmd.getOptionValue(OPT_OUTPUT_MODE);
    String numeratorTag = cmd.getOptionValue(OPT_NUMERATOR);
    String numeratorOPTag = cmd.getOptionValue(OPT_NUMERATOR_OP);
    String denominatorTag = cmd.getOptionValue(OPT_DENOMINATOR);
    String denominatorOPTag = cmd.getOptionValue(OPT_DENOMINATOR_OP);
    String selectivityTag = cmd.getOptionValue(OPT_SELECTIVITY);
    String selectivityOPTag = cmd.getOptionValue(OPT_SELECTIVITY_OP);

    SDFSelectivityCalculator calculator = new SDFSelectivityCalculator(outFile);
    try {
        calculator.setParameters(outputMode, numeratorTag, numeratorOPTag, denominatorTag, denominatorOPTag,
                selectivityTag, selectivityOPTag);
        calculator.run(inFile);
    } catch (IncorrectInputException e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    } finally {
        calculator.close();
    }
}

From source file:edu.msu.cme.rdp.kmer.cli.FastKmerFilter.java

public static void main(String[] args) throws Exception {
    final KmerSet<Set<RefKmer>> kmerSet;
    final SeqReader queryReader;
    final SequenceType querySeqType;
    final File queryFile;
    final KmerStartsWriter out;
    final boolean translQuery;
    final int wordSize;
    final int translTable;
    final boolean alignedSeqs;
    final List<String> refLabels = new ArrayList();
    final int maxThreads;
    final int trieWordSize;

    try {//  w  ww.ja  v a 2 s.  c o m
        CommandLine cmdLine = new PosixParser().parse(options, args);
        args = cmdLine.getArgs();

        if (args.length < 3) {
            throw new Exception("Unexpected number of arguments");
        }

        if (cmdLine.hasOption("out")) {
            out = new KmerStartsWriter(cmdLine.getOptionValue("out"));
        } else {
            out = new KmerStartsWriter(System.out);
        }

        if (cmdLine.hasOption("aligned")) {
            alignedSeqs = true;
        } else {
            alignedSeqs = false;
        }

        if (cmdLine.hasOption("transl-table")) {
            translTable = Integer.valueOf(cmdLine.getOptionValue("transl-table"));
        } else {
            translTable = 11;
        }

        if (cmdLine.hasOption("threads")) {
            maxThreads = Integer.valueOf(cmdLine.getOptionValue("threads"));
        } else {
            maxThreads = Runtime.getRuntime().availableProcessors();
        }

        queryFile = new File(args[1]);
        wordSize = Integer.valueOf(args[0]);
        SequenceType refSeqType = null;

        querySeqType = SeqUtils.guessSequenceType(queryFile);
        queryReader = new SequenceReader(queryFile);

        if (querySeqType == SequenceType.Protein) {
            throw new Exception("Expected nucl query sequences");
        }

        refSeqType = SeqUtils
                .guessSequenceType(new File(args[2].contains("=") ? args[2].split("=")[1] : args[2]));

        translQuery = refSeqType == SequenceType.Protein;

        if (translQuery && wordSize % 3 != 0) {
            throw new Exception("Word size must be a multiple of 3 for nucl ref seqs");
        }

        if (translQuery) {
            trieWordSize = wordSize / 3;
        } else {
            trieWordSize = wordSize;
        }
        kmerSet = new KmerSet<Set<RefKmer>>();//new KmerTrie(trieWordSize, translQuery);

        for (int index = 2; index < args.length; index++) {
            String refName;
            String refFileName = args[index];
            if (refFileName.contains("=")) {
                String[] lexemes = refFileName.split("=");
                refName = lexemes[0];
                refFileName = lexemes[1];
            } else {
                String tmpName = new File(refFileName).getName();
                if (tmpName.contains(".")) {
                    refName = tmpName.substring(0, tmpName.lastIndexOf("."));
                } else {
                    refName = tmpName;
                }
            }

            File refFile = new File(refFileName);

            if (refSeqType != SeqUtils.guessSequenceType(refFile)) {
                throw new Exception(
                        "Reference file " + refFile + " contains " + SeqUtils.guessFileFormat(refFile)
                                + " sequences but expected " + refSeqType + " sequences");
            }

            SequenceReader seqReader = new SequenceReader(refFile);
            Sequence seq;

            while ((seq = seqReader.readNextSequence()) != null) {
                if (seq.getSeqName().startsWith("#")) {
                    continue;
                }

                KmerGenerator kmers;
                try {
                    if (translQuery) { //protein ref
                        kmers = new ProtKmerGenerator(seq.getSeqString(), trieWordSize, alignedSeqs);
                    } else {
                        kmers = new NuclKmerGenerator(seq.getSeqString(), trieWordSize, alignedSeqs);
                    }
                    while (kmers.hasNext()) {
                        Kmer temp = kmers.next();
                        long[] next = temp.getLongKmers();
                        Set<RefKmer> refKmers = kmerSet.get(next);
                        if (refKmers == null) {
                            refKmers = new HashSet();
                            kmerSet.add(next, refKmers);
                        }

                        RefKmer kmerRef = new RefKmer();
                        kmerRef.modelPos = kmers.getPosition();
                        kmerRef.refFileIndex = refLabels.size();
                        kmerRef.refSeqid = seq.getSeqName();
                        refKmers.add(kmerRef);
                    }
                } catch (IllegalArgumentException ex) {
                    //System.err.println(seq.getSeqName()+ " " + ex.getMessage());
                }
            }
            seqReader.close();

            refLabels.add(refName);
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp(
                "KmerSearch <kmerSize> <query_file> [name=]<ref_file> ...\nkmerSize should be multiple of 3, (recommend 45, minimum 30, maximum 63) ",
                options);
        e.printStackTrace();
        System.exit(1);
        throw new RuntimeException("Stupid jvm"); //While this will never get thrown it is required to make sure javac doesn't get confused about uninitialized variables
    }

    long startTime = System.currentTimeMillis();
    long seqCount = 0;
    final int maxTasks = 25000;

    System.err.println("Starting kmer mapping at " + new Date());
    System.err.println("*  Number of threads:       " + maxThreads);
    System.err.println("*  References:              " + refLabels);
    System.err.println("*  Reads file:              " + queryFile);
    System.err.println("*  Kmer length:             " + trieWordSize);
    System.err.println("*  Kmer Refset Size:        " + kmerSet.size());

    final AtomicInteger processed = new AtomicInteger();
    final AtomicInteger outstandingTasks = new AtomicInteger();

    ExecutorService service = Executors.newFixedThreadPool(maxThreads);

    Sequence querySeq;

    while ((querySeq = queryReader.readNextSequence()) != null) {
        seqCount++;

        String seqString = querySeq.getSeqString();

        if ((!translQuery && seqString.length() < wordSize)
                || (translQuery && seqString.length() < wordSize + 2)) {
            //System.err.println(querySeq.getSeqName() + "\t" + seqString.length());
            continue;
        }

        final Sequence threadSeq = querySeq;

        Runnable r = new Runnable() {

            public void run() {
                try {
                    processSeq(threadSeq, refLabels, kmerSet, out, wordSize, translQuery, translTable, false);
                    processSeq(threadSeq, refLabels, kmerSet, out, wordSize, translQuery, translTable, true);

                    processed.incrementAndGet();
                    outstandingTasks.decrementAndGet();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        outstandingTasks.incrementAndGet();
        service.submit(r);

        while (outstandingTasks.get() >= maxTasks)
            ;

        if ((processed.get() + 1) % 1000000 == 0) {
            System.err.println("Processed " + processed + " sequences in "
                    + (System.currentTimeMillis() - startTime) + " ms");
        }
    }

    service.shutdown();
    service.awaitTermination(1, TimeUnit.DAYS);

    System.err.println("Finished Processed " + processed + " sequences in "
            + (System.currentTimeMillis() - startTime) + " ms");

    out.close();
}

From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificatorCommandLineTool.java

/**
 * Main (starting) method of the command line application.
 *
 * @param argv Array of command line arguments that are expected to be
 * filesystem paths to input XML documents with MathML to be unified.
 * @throws ParserConfigurationException If a XML DOM builder cannot be
 * created with the configuration requested.
 *///from  w w  w .j av a2s.c o  m
public static void main(String argv[]) throws ParserConfigurationException {

    final Options options = new Options();
    options.addOption("p", "operator-unification", false, "unify operator in addition to other types of nodes");
    options.addOption("h", "help", false, "print help");

    final CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, argv);
    } catch (ParseException ex) {
        printHelp(options);
        System.exit(1);
    }

    if (line != null) {
        if (line.hasOption('h')) {
            printHelp(options);
            System.exit(0);
        }
        operatorUnification = line.hasOption('p');

        final List<String> arguments = Arrays.asList(line.getArgs());
        if (arguments.size() > 0) {

            Document outerDocument = DOMBuilder.getDocumentBuilder().newDocument();
            Node rootNode = outerDocument.createElementNS(UNIFIED_MATHML_NS,
                    UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ROOT_ELEM);
            outerDocument.appendChild(rootNode);

            for (String filepath : arguments) {
                try {

                    Document doc = DOMBuilder.buildDocFromFilepath(filepath);
                    MathMLUnificator.unifyMathML(doc, operatorUnification);
                    if (arguments.size() == 1) {
                        xmlStdoutSerializer(doc);
                    } else {
                        Node itemNode = rootNode.getOwnerDocument().createElementNS(UNIFIED_MATHML_NS,
                                UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_ELEM);
                        Attr filenameAttr = itemNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS,
                                UNIFIED_MATHML_NS_PREFIX + ":"
                                        + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_FILEPATH_ATTR);
                        filenameAttr.setTextContent(String.valueOf(filepath));
                        ((Element) itemNode).setAttributeNodeNS(filenameAttr);
                        itemNode.appendChild(
                                rootNode.getOwnerDocument().importNode(doc.getDocumentElement(), true));
                        rootNode.appendChild(itemNode);

                    }

                } catch (SAXException | IOException ex) {
                    Logger.getLogger(MathMLUnificatorCommandLineTool.class.getName()).log(Level.SEVERE,
                            "Failed processing of file: " + filepath, ex);
                }
            }

            if (rootNode.getChildNodes().getLength() > 0) {
                xmlStdoutSerializer(rootNode.getOwnerDocument());
            }

        } else {
            printHelp(options);
            System.exit(0);
        }
    }

}

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

public static void main(String... args) throws IOException {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {/* w w  w . ja  va 2  s . co  m*/
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp();
    }

    args = cmd.getArgs();
    if (args.length > 0) {
        exitWithHelp("Unknown param: " + args[0]);
    }

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

    int nCpu = 1;
    int maxNeighbors = 1;
    double minSim = 0D;

    String idTag = cmd.getOptionValue("idTag");
    boolean printAll = cmd.hasOption("printAll");

    String d = cmd.getOptionValue("nCpu");
    if (d != null)
        nCpu = Integer.parseInt(d);

    d = cmd.getOptionValue("maxNeighbors");
    if (d != null)
        maxNeighbors = Integer.parseInt(d);

    d = cmd.getOptionValue("minSimilarity");
    if (d != null)
        minSim = Double.parseDouble(d);

    String countAboveSimilarityStr = cmd.getOptionValue("countSimilarAbove");

    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String refFile = cmd.getOptionValue("ref");

    String tabOutput = cmd.getOptionValue("tabOutput");
    boolean outputDuplicates = cmd.hasOption("outputDuplicates");

    if (outputDuplicates && tabOutput != null)
        exitWithHelp("-outputDuplicates will not work with outputVTab");
    if (outputDuplicates && refFile == null)
        exitWithHelp("-outputDuplicates requires -ref ");
    if ("tab".equalsIgnoreCase(tabOutput) && refFile != null)
        exitWithHelp("-tabOutput tab: does not work with reference file");
    if ("tab".equalsIgnoreCase(tabOutput) && maxNeighbors == 1)
        exitWithHelp("-tabOutput tab: does not make sense with -maxNeighbors = 1");
    if (cmd.hasOption("countSimilarAbove") && tabOutput != null)
        exitWithHelp("-countSimilarAbove not supported for tab or vTab output");
    if (printAll && !(maxNeighbors > 1 || minSim > 0))
        exitWithHelp("printAll only supported if: maxNeighbors > 1 or minSim > 0");

    if (printAll && tabOutput != null)
        System.err.println("WARNING: printAll ignored for tab output!\n");

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

    if (refFile == null) { // no reference file; run all by all comparison
        performMatrixNNSearch(inFile, outFile, tabOutput, compFact, minSim, maxNeighbors, idTag, nCpu,
                countAboveSimilarityStr, printAll);

    } else { // refrence file; compare inFile to refFile
        performReferenceSearch(inFile, refFile, outFile, tabOutput, compFact, minSim, maxNeighbors, idTag, nCpu,
                countAboveSimilarityStr, outputDuplicates, printAll);
    }

}

From source file:jlite.cli.JobCancel.java

public static void main(String[] args) {
    System.out.println(); // extra line
    CommandLineParser parser = new GnuParser();
    Options options = setupOptions();/* www  .  ja  v a2s.  c  o  m*/
    HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.setSyntaxPrefix("Usage: ");
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
        if (line.hasOption("help")) {
            helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER, false);
            System.out.println(); // extra line
            System.exit(0);
        } else {
            if (line.hasOption("xml")) {
                System.out.println("<output>");
            }
            run(line.getArgs(), line);
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage() + "\n");
        helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER, false);
        System.out.println(); // extra line
        System.exit(-1);
    } catch (Exception e) {
        if (line.hasOption("xml")) {
            System.out.println("<error>" + e.getMessage() + "</error>");
        } else {
            System.err.println(e.getMessage());
        }
    } finally {
        if (line.hasOption("xml")) {
            System.out.println("</output>");
        }
    }
    System.out.println(); // extra line
}