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:com.asual.lesscss.LessEngineCli.java

public static void main(String[] args) throws LessException, URISyntaxException {
    Options cmdOptions = new Options();
    cmdOptions.addOption(LessOptions.CHARSET_OPTION, true, "Input file charset encoding. Defaults to UTF-8.");
    cmdOptions.addOption(LessOptions.COMPRESS_OPTION, false, "Flag that enables compressed CSS output.");
    cmdOptions.addOption(LessOptions.CSS_OPTION, false, "Flag that enables compilation of .css files.");
    cmdOptions.addOption(LessOptions.LESS_OPTION, true, "Path to a custom less.js for Rhino version.");
    try {//www.j  a v  a2s  .  c  om
        CommandLineParser cmdParser = new GnuParser();
        CommandLine cmdLine = cmdParser.parse(cmdOptions, args);
        LessOptions options = new LessOptions();
        if (cmdLine.hasOption(LessOptions.CHARSET_OPTION)) {
            options.setCharset(cmdLine.getOptionValue(LessOptions.CHARSET_OPTION));
        }
        if (cmdLine.hasOption(LessOptions.COMPRESS_OPTION)) {
            options.setCompress(true);
        }
        if (cmdLine.hasOption(LessOptions.CSS_OPTION)) {
            options.setCss(true);
        }
        if (cmdLine.hasOption(LessOptions.LESS_OPTION)) {
            options.setLess(new File(cmdLine.getOptionValue(LessOptions.LESS_OPTION)).toURI().toURL());
        }
        LessEngine engine = new LessEngine(options);
        if (System.in.available() != 0) {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            StringWriter sw = new StringWriter();
            char[] buffer = new char[1024];
            int n = 0;
            while (-1 != (n = in.read(buffer))) {
                sw.write(buffer, 0, n);
            }
            String src = sw.toString();
            if (!src.isEmpty()) {
                System.out.println(engine.compile(src, null, options.isCompress()));
                System.exit(0);
            }
        }
        String[] files = cmdLine.getArgs();
        if (files.length == 1) {
            System.out.println(engine.compile(new File(files[0]), options.isCompress()));
            System.exit(0);
        }
        if (files.length == 2) {
            engine.compile(new File(files[0]), new File(files[1]), options.isCompress());
            System.exit(0);
        }

    } catch (IOException ioe) {
        System.err.println("Error opening input file.");
    } catch (ParseException pe) {
        System.err.println("Error parsing arguments.");
    }
    String[] paths = LessEngine.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()
            .split(File.separator);
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("java -jar " + paths[paths.length - 1] + " input [output] [options]", cmdOptions);
    System.exit(1);
}

From source file:com.apkTool.Main.java

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

    /**/*from  w  w w. jav a2  s .  c  o m*/
     * ?apk 
     * ?.apk  
     *  + ExtDataInput.javaskipCheckChunkTypeInt 73
     *
     * .apk 
     * qq.apk  
     *  + ResTypeSpec.javaaddResSpec78
     *
     * .apk 
     * ?.apk
     */

    // ??
    args = new String[] { "d", "-f", "ApkTool/apk/qq.apk", "-o", "ApkTool/out" };

    // 
    // args = new String[]{"b", "out", "-o", "apk/zhifubao_build.apk"};

    // set verbosity default
    Verbosity verbosity = Verbosity.NORMAL;

    // cli parser
    CommandLineParser parser = new PosixParser();
    CommandLine commandLine;

    // load options
    _Options();

    try {
        commandLine = parser.parse(allOptions, args, false);
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        usage();
        return;
    }

    // check for verbose / quiet
    if (commandLine.hasOption("-v") || commandLine.hasOption("--verbose")) {
        verbosity = Verbosity.VERBOSE;
    } else if (commandLine.hasOption("-q") || commandLine.hasOption("--quiet")) {
        verbosity = Verbosity.QUIET;
    }
    setupLogging(verbosity);

    // check for advance mode
    if (commandLine.hasOption("advance") || commandLine.hasOption("advanced")) {
        setAdvanceMode(true);
    }

    // @todo use new ability of apache-commons-cli to check hasOption for non-prefixed items
    boolean cmdFound = false;
    for (String opt : commandLine.getArgs()) {
        if (opt.equalsIgnoreCase("d") || opt.equalsIgnoreCase("decode")) {
            cmdDecode(commandLine);
            cmdFound = true;
        } else if (opt.equalsIgnoreCase("b") || opt.equalsIgnoreCase("build")) {
            cmdBuild(commandLine);
            cmdFound = true;
        } else if (opt.equalsIgnoreCase("if") || opt.equalsIgnoreCase("install-framework")) {
            cmdInstallFramework(commandLine);
            cmdFound = true;
        } else if (opt.equalsIgnoreCase("empty-framework-dir")) {
            cmdEmptyFrameworkDirectory(commandLine);
            cmdFound = true;
        } else if (opt.equalsIgnoreCase("publicize-resources")) {
            cmdPublicizeResources(commandLine);
            cmdFound = true;
        }
    }

    // if no commands ran, run the version / usage check.
    if (!cmdFound) {
        if (commandLine.hasOption("version")) {
            _version();
        } else {
            usage();
        }
    }
}

From source file:com.linkedin.databus2.client.util.DatabusClusterUtil.java

/**
 * @param args/*from   w w  w  . ja  v  a 2  s .  c  om*/
 *            DbusClusterUtil -z <zookeper-server> -c <cluster-name> [-p
 *            <partitionNumber] partitions readSCN writeSCN SCN remove
 *            clients
 */
public static void main(String[] args) {
    try {
        GnuParser cmdLineParser = new GnuParser();
        Options options = new Options();
        options.addOption("z", true, "zk-server").addOption("c", true, "cluster-name ")
                .addOption("p", true, "partition").addOption("l", false, "legacy")
                .addOption("h", false, "help");
        CommandLine cmdLineArgs = cmdLineParser.parse(options, args, false);

        if (cmdLineArgs.hasOption('h')) {
            usage();
            System.exit(0);
        }

        if (!cmdLineArgs.hasOption('c')) {
            usage();
            System.exit(1);
        }
        String clusterName = cmdLineArgs.getOptionValue('c');
        String zkServer = cmdLineArgs.getOptionValue('z');
        boolean isLegacyChkptLocation = cmdLineArgs.hasOption('l');
        if (zkServer == null || zkServer.isEmpty()) {
            zkServer = "localhost:2181";
        }

        String partitionStr = cmdLineArgs.getOptionValue('p');
        String partition = partitionStr;
        if ((partition != null) && partition.equals("all")) {
            partition = "";
        }

        String[] fns = cmdLineArgs.getArgs();
        if (fns.length < 1) {
            usage();
            System.exit(1);
        }

        DatabusClusterUtilHelper clusterState = new DatabusClusterUtilHelper(zkServer, clusterName);

        String function = fns[0];
        String arg1 = (fns.length > 1) ? fns[1] : null;
        String arg2 = (fns.length > 2) ? fns[2] : null;

        boolean clusterExists = clusterState.existsCluster();
        if (function.equals("create")) {
            if (!clusterExists) {
                if (arg1 == null) {
                    throw new DatabusClusterUtilException("create: please provide the number of partitions");
                }
                int part = Integer.parseInt(arg1);
                clusterState.createCluster(part);
                return;
            } else {
                throw new DatabusClusterUtilException("Cluster " + clusterName + " already exists");
            }
        }
        if (!clusterExists) {
            throw new DatabusClusterUtilException("Cluster doesn't exist! ");
        }

        if (function.equals("delete")) {
            clusterState.removeCluster();
        } else if (function.equals("partitions")) {
            int numParts = clusterState.getNumPartitions();
            System.out.println(numParts);
        } else {
            // all these functions require the notion of partition;
            Set<Integer> partitions = getPartitions(partition, clusterState.getNumPartitions());
            if (function.equals("sources")) {
                DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName, null,
                        partitions, isLegacyChkptLocation);
                Set<String> sources = ckptMgr.getSourcesFromCheckpoint();
                if (sources != null) {
                    for (String s : sources) {
                        System.out.println(s);
                    }
                } else {
                    throw new DatabusClusterUtilException(
                            "sources: Sources not found for cluster " + clusterName);
                }
            } else if (function.equals("clients")) {
                clusterState.getClusterInfo();
                for (Integer p : partitions) {
                    String client = clusterState.getInstanceForPartition(p);
                    System.out.println(p + "\t" + client);
                }
            } else if (function.equals("readSCN")) {
                List<String> sources = getSources(arg1);
                if ((sources != null) && !sources.isEmpty()) {
                    DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName,
                            sources, partitions, isLegacyChkptLocation);
                    Map<Integer, Checkpoint> ckpts = ckptMgr.readCheckpoint();
                    char delim = '\t';
                    for (Map.Entry<Integer, Checkpoint> mkPair : ckpts.entrySet()) {
                        StringBuilder output = new StringBuilder(64);
                        output.append(mkPair.getKey());
                        output.append(delim);
                        Checkpoint cp = mkPair.getValue();
                        if (cp == null) {
                            output.append(-1);
                            output.append(delim);
                            output.append(-1);
                        } else {
                            if (cp.getConsumptionMode() == DbusClientMode.ONLINE_CONSUMPTION) {
                                output.append(cp.getWindowScn());
                                output.append(delim);
                                output.append(cp.getWindowOffset());
                            } else if (cp.getConsumptionMode() == DbusClientMode.BOOTSTRAP_CATCHUP) {
                                output.append(cp.getWindowScn());
                                output.append(delim);
                                output.append(cp.getWindowOffset());
                            } else if (cp.getConsumptionMode() == DbusClientMode.BOOTSTRAP_SNAPSHOT) {
                                output.append(cp.getBootstrapSinceScn());
                                output.append(delim);
                                output.append(-1);
                            }
                        }
                        System.out.println(output.toString());
                    }
                } else {
                    throw new DatabusClusterUtilException("readSCN: please specify non-empty sources");
                }
            } else if (function.equals("checkpoint")) {
                List<String> sources = getSources(arg1);
                if ((sources != null) && !sources.isEmpty()) {
                    DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName,
                            sources, partitions, isLegacyChkptLocation);
                    Map<Integer, Checkpoint> ckpts = ckptMgr.readCheckpoint();
                    char delim = '\t';
                    for (Map.Entry<Integer, Checkpoint> mkPair : ckpts.entrySet()) {
                        StringBuilder output = new StringBuilder(64);
                        output.append(mkPair.getKey());
                        output.append(delim);
                        Checkpoint cp = mkPair.getValue();
                        if (cp == null) {
                            output.append("null");
                        } else {
                            output.append(cp.toString());
                        }
                        System.out.println(output.toString());
                    }
                } else {
                    throw new DatabusClusterUtilException("readSCN: please specify non-empty sources");
                }
            } else if (function.equals("writeSCN")) {
                String scnStr = arg1;
                Long scn = Long.parseLong(scnStr);
                if (partitionStr != null) {
                    List<String> sources = getSources(arg2);
                    if ((sources != null) && !sources.isEmpty()) {
                        DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName,
                                sources, partitions, isLegacyChkptLocation);
                        ckptMgr.writeCheckpoint(scn);
                    } else {
                        throw new DatabusClusterUtilException("writeSCN: please specify non-empty sources");
                    }
                } else {
                    throw new DatabusClusterUtilException(
                            "writeSCN: to write the SCN to all partitions please use '-p all'");
                }
            } else if (function.equals("removeSCN")) {
                if (partitionStr != null) {

                    List<String> sources = getSources(arg1);
                    if ((sources != null) && !sources.isEmpty()) {
                        DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName,
                                sources, partitions, isLegacyChkptLocation);
                        ckptMgr.remove();
                    } else {
                        throw new DatabusClusterUtilException("remove: please specify non-empty sources");
                    }
                } else {
                    throw new DatabusClusterUtilException(
                            "remove: to remove SCN from all partitions please use '-p all'");
                }
            } else {
                usage();
                System.exit(1);
            }
        }
    } catch (ParseException e) {
        usage();
        System.exit(1);
    } catch (DatabusClusterUtilException e) {
        System.err.println("Error! " + e.toString());
        System.exit(1);
    }

}

From source file:edu.msu.cme.rdp.readseq.utils.SequenceTrimmer.java

public static void main(String[] args) throws IOException {
    Options options = new Options();
    options.addOption("r", "ref-seq", true,
            "Trim points are given as positions in a reference sequence from this file");
    options.addOption("i", "inclusive", false, "Trim points are inclusive");
    options.addOption("l", "length", true, "Minimum length of sequence after trimming");
    options.addOption("f", "filled-ratio", true,
            "Minimum ratio of filled model positions of sequence after trimming");
    options.addOption("o", "out", true, "Write sequences to directory (default=cwd)");
    options.addOption("s", "stats", true, "Write stats to file");

    PrintWriter statsOut = new PrintWriter(new NullWriter());
    boolean inclusive = false;
    int minLength = 0;
    int minTrimmedLength = 0;
    int maxNs = 0;
    int maxTrimNs = 0;

    int trimStart = 0;
    int trimStop = 0;
    Sequence refSeq = null;/*  w  ww  . j a va  2s  .  c  o m*/
    float minFilledRatio = 0;

    int expectedModelPos = -1;
    String[] inputFiles = null;
    File outdir = new File(".");
    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("ref-seq")) {
            refSeq = readRefSeq(new File(line.getOptionValue("ref-seq")));
        }

        if (line.hasOption("inclusive")) {
            inclusive = true;
        }

        if (line.hasOption("length")) {
            minLength = Integer.valueOf(line.getOptionValue("length"));
        }

        if (line.hasOption("filled-ratio")) {
            minFilledRatio = Float.valueOf(line.getOptionValue("filled-ratio"));
        }

        if (line.hasOption("out")) {
            outdir = new File(line.getOptionValue("out"));
            if (!outdir.isDirectory()) {
                outdir = outdir.getParentFile();
                System.err.println("Output option is not a directory, using " + outdir + " instead");
            }
        }

        if (line.hasOption("stats")) {
            statsOut = new PrintWriter(line.getOptionValue("stats"));
        }

        args = line.getArgs();

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

        trimStart = Integer.parseInt(args[0]);
        trimStop = Integer.parseInt(args[1]);
        inputFiles = Arrays.copyOfRange(args, 2, args.length);

        if (refSeq != null) {
            expectedModelPos = SeqUtils.getMaskedBySeqString(refSeq.getSeqString()).length();
            trimStart = translateCoord(trimStart, refSeq, CoordType.seq, CoordType.model);
            trimStop = translateCoord(trimStop, refSeq, CoordType.seq, CoordType.model);
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp("SequenceTrimmer <trim start> <trim stop> <aligned file> ...", options);
        System.err.println("Error: " + e.getMessage());
    }

    System.err.println("Starting sequence trimmer");
    System.err.println("*  Input files:           " + Arrays.asList(inputFiles));
    System.err.println("*  Minimum Length:        " + minLength);
    System.err.println("*  Trim point inclusive?: " + inclusive);
    System.err.println("*  Trim points:           " + trimStart + "-" + trimStop);
    System.err.println("*  Min filled ratio:      " + minFilledRatio);
    System.err.println("*  refSeq:                "
            + ((refSeq == null) ? "model" : refSeq.getSeqName() + " " + refSeq.getDesc()));

    Sequence seq;
    SeqReader reader;
    TrimStats stats;

    writeStatsHeader(statsOut);

    FastaWriter seqWriter;
    File in;
    for (String infile : inputFiles) {
        in = new File(infile);
        reader = new SequenceReader(in);
        seqWriter = new FastaWriter(new File(outdir, "trimmed_" + in.getName()));

        while ((seq = reader.readNextSequence()) != null) {
            if (seq.getSeqName().startsWith("#")) {
                seqWriter.writeSeq(seq.getSeqName(), "", trimMetaSeq(seq.getSeqString(), trimStart, trimStop));
                continue;
            }

            stats = getStats(seq, trimStart, trimStop);
            boolean passed = didSeqPass(stats, minLength, minTrimmedLength, maxNs, maxTrimNs, minFilledRatio);
            writeStats(statsOut, seq.getSeqName(), stats, passed);
            if (passed) {
                seqWriter.writeSeq(seq.getSeqName(), seq.getDesc(), new String(stats.trimmedBases));
            }
        }

        reader.close();
        seqWriter.close();
    }

    statsOut.close();
}

From source file:com.artofsolving.jodconverter.cli.ConvertDocument.java

public static void main(String[] arguments) throws Exception {
    CommandLineParser commandLineParser = new PosixParser();
    CommandLine commandLine = commandLineParser.parse(OPTIONS, arguments);

    int port = SocketOpenOfficeConnection.DEFAULT_PORT;
    if (commandLine.hasOption(OPTION_PORT.getOpt())) {
        port = Integer.parseInt(commandLine.getOptionValue(OPTION_PORT.getOpt()));
    }/*from  w  w w  .  j a  va  2 s .c om*/

    String outputFormat = null;
    if (commandLine.hasOption(OPTION_OUTPUT_FORMAT.getOpt())) {
        outputFormat = commandLine.getOptionValue(OPTION_OUTPUT_FORMAT.getOpt());
    }

    boolean verbose = false;
    if (commandLine.hasOption(OPTION_VERBOSE.getOpt())) {
        verbose = true;
    }

    DocumentFormatRegistry registry;
    if (commandLine.hasOption(OPTION_XML_REGISTRY.getOpt())) {
        File registryFile = new File(commandLine.getOptionValue(OPTION_XML_REGISTRY.getOpt()));
        if (!registryFile.isFile()) {
            System.err.println("ERROR: specified XML registry file not found: " + registryFile);
            System.exit(EXIT_CODE_XML_REGISTRY_NOT_FOUND);
        }
        registry = new XmlDocumentFormatRegistry(new FileInputStream(registryFile));
        if (verbose) {
            System.out.println("-- loaded document format registry from " + registryFile);
        }
    } else {
        registry = new DefaultDocumentFormatRegistry();
    }

    String[] fileNames = commandLine.getArgs();
    if ((outputFormat == null && fileNames.length != 2) || fileNames.length < 1) {
        String syntax = "convert [options] input-file output-file; or\n"
                + "[options] -f output-format input-file [input-file...]";
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp(syntax, OPTIONS);
        System.exit(EXIT_CODE_TOO_FEW_ARGS);
    }

    OpenOfficeConnection connection = new SocketOpenOfficeConnection(port);
    try {
        if (verbose) {
            System.out.println("-- connecting to OpenOffice.org on port " + port);
        }
        connection.connect();
    } catch (ConnectException officeNotRunning) {
        System.err.println(
                "ERROR: connection failed. Please make sure OpenOffice.org is running and listening on port "
                        + port + ".");
        System.exit(EXIT_CODE_CONNECTION_FAILED);
    }
    try {
        DocumentConverter converter = new OpenOfficeDocumentConverter(connection, registry);
        if (outputFormat == null) {
            File inputFile = new File(fileNames[0]);
            File outputFile = new File(fileNames[1]);
            convertOne(converter, inputFile, outputFile, verbose);
        } else {
            for (int i = 0; i < fileNames.length; i++) {
                File inputFile = new File(fileNames[i]);
                File outputFile = new File(FilenameUtils.getFullPath(fileNames[i])
                        + FilenameUtils.getBaseName(fileNames[i]) + "." + outputFormat);
                convertOne(converter, inputFile, outputFile, verbose);
            }
        }
    } finally {
        if (verbose) {
            System.out.println("-- disconnecting");
        }
        connection.disconnect();
    }
}

From source file:autocorrelator.apps.SDFGroovy.java

public static void main(String[] args) throws Exception {
    long start = System.currentTimeMillis();

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("in", true, "input sd file");
    options.addOption(opt);//from   w w  w .  j  a va  2  s.  c  o m

    opt = new Option("out", true, "output file for return value true or null");
    options.addOption(opt);

    opt = new Option("falseOut", true, "output file for return value false");
    options.addOption(opt);

    opt = new Option("c", true, "groovy script line");
    options.addOption(opt);

    opt = new Option("f", true, "groovy script file");
    options.addOption(opt);

    opt = new Option("exception", true, "exception handling (Default: stop)");
    options.addOption(opt);

    opt = new Option("h", false, "print help message");
    options.addOption(opt);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        exitWithHelp(e.getMessage(), options);
    }
    if (!cmd.hasOption("c") && !cmd.hasOption("f"))
        exitWithHelp("-c or -f must be given!", options);

    if (cmd.hasOption("c") && cmd.hasOption("f"))
        exitWithHelp("Only one of -c or -f may be given!", options);

    String groovyStrg;
    if (cmd.hasOption("c"))
        groovyStrg = cmd.getOptionValue("c");
    else
        groovyStrg = fileToString(cmd.getOptionValue("f"));

    Set<String> inFileds = new HashSet<String>();
    Set<String> outFields = new HashSet<String>();
    Script script = getGroovyScript(groovyStrg, inFileds, outFields);

    if (cmd.hasOption("h")) {
        callScriptHelp(script);
        exitWithHelp("", options);
    }

    if (!cmd.hasOption("in") || !cmd.hasOption("out")) {
        callScriptHelp(script);
        exitWithHelp("-in and -out must be given", options);
    }

    String[] scriptArgs = cmd.getArgs();
    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String falseOutFile = cmd.getOptionValue("falseOut");
    EXCEPTIONHandling eHandling = EXCEPTIONHandling.stop;
    if (cmd.hasOption("exception"))
        eHandling = EXCEPTIONHandling.getByName(cmd.getOptionValue("exception"));

    callScriptInit(script, scriptArgs);

    oemolistream ifs = new oemolistream(inFile);
    oemolostream ofs = new oemolostream(outFile);
    oemolostream falseOFS = null;
    if (falseOutFile != null)
        falseOFS = new oemolostream(falseOutFile);

    OEMolBase mol = new OEGraphMol();

    int iCounter = 0;
    int oCounter = 0;
    int foCounter = 0;
    while (oechem.OEReadMolecule(ifs, mol)) {
        iCounter++;

        Binding binding = getFieldBindings(mol, inFileds, outFields);

        script.setBinding(binding);
        boolean printToTrue = true;
        boolean printToFalse = true;
        try {
            Object ret = script.run();
            if (ret == null || !(ret instanceof Boolean)) {
                printToFalse = false;
            } else if (((Boolean) ret).booleanValue()) {
                printToFalse = false;
            } else // ret = false
            {
                printToTrue = false;
            }

            setOutputFields(mol, binding, outFields);
        } catch (Exception e) {
            switch (eHandling) {
            case stop:
                throw e;
            case printToTrue:
                printToFalse = false;
                System.err.println(e.getMessage());
                break;
            case printToFalse:
                printToTrue = false;
                System.err.println(e.getMessage());
                break;
            case dropRecord:
                printToTrue = false;
                printToFalse = false;
                System.err.println(e.getMessage());
                break;
            default:
                assert false;
                break;
            }
        }

        if (printToTrue) {
            oechem.OEWriteMolecule(ofs, mol);
            oCounter++;
        }
        if (falseOFS != null && printToFalse) {
            oechem.OEWriteMolecule(falseOFS, mol);
            foCounter++;
        }
    }

    System.err.printf("SDFGroovy: Input %d, output %d,%d structures in %dsec\n", iCounter, oCounter, foCounter,
            (System.currentTimeMillis() - start) / 1000);

    if (falseOFS != null)
        falseOFS.close();
    ofs.close();
    ifs.close();
    mol.delete();
}

From source file:edu.cmu.sv.modelinference.runner.Main.java

public static void main(String[] args) {
    Options cmdOpts = createCmdOptions();

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {/*from   w ww . j  a  va2s  .  c o m*/
        cmd = parser.parse(cmdOpts, args, true);
    } catch (ParseException exp) {
        logger.error(exp.getMessage());
        System.err.println(exp.getMessage());
        Util.printHelpAndExit(Main.class, cmdOpts);
    }

    String inputType = cmd.getOptionValue(INPUT_TYPE_ARG);
    String tool = cmd.getOptionValue(TOOL_TYPE_ARG);
    String logFile = cmd.getOptionValue(LOG_FILE_ARG).replaceFirst("^~", System.getProperty("user.home"));

    LogHandler<?> logHandler = null;
    boolean found = false;
    for (LogHandler<?> lh : logHandlers) {
        if (lh.getHandlerName().equals(tool)) {
            logHandler = lh;
            found = true;
            break;
        }
    }
    if (!found) {
        StringBuilder sb = new StringBuilder();
        Iterator<LogHandler<?>> logIter = logHandlers.iterator();
        while (logIter.hasNext()) {
            sb.append(logIter.next().getHandlerName());
            if (logIter.hasNext())
                sb.append(", ");
        }
        logger.error("Did not find tool for arg " + tool);

        System.err.println("Supported tools: " + Util.getSupportedHandlersString(logHandlers));
        Util.printHelpAndExit(Main.class, cmdOpts);
    }
    logger.info("Using loghandler for logtype: " + logHandler.getHandlerName());

    logHandler.process(logFile, inputType, cmd.getArgs());
}

From source file:com.github.pitzcarraldo.dissimilar.Dissimilar.java

/**
 * Main method//from  w ww  . java2  s  .c o m
 * @param args command line arguments
 */
public static void main(String[] args) {

    Properties mavenProps = new Properties();
    try {
        mavenProps.load(Dissimilar.class.getClassLoader()
                .getResourceAsStream("META-INF/maven/uk.bl.dpt.dissimilar/dissimilar/pom.properties"));
        version = mavenProps.getProperty("version");
    } catch (Exception e) {
    }

    boolean calcPSNR = true;
    boolean calcSSIM = true;
    String heatMapImage = null;

    CommandLineParser parser = new PosixParser();
    Options options = new Options();
    options.addOption("m", "heatmap", true, "file to save the ssim heatmap to (png)");
    options.addOption("p", "psnr", false, "calculate just psnr");
    options.addOption("s", "ssim", false, "calculate just ssim");
    options.addOption("h", "help", false, "help text");

    CommandLine com = null;
    try {
        com = parser.parse(options, args);
    } catch (ParseException e) {
        HelpFormatter help = new HelpFormatter();
        help.printHelp("Dissimilar v" + version, options);
        return;
    }

    if (com.hasOption("help")) {
        HelpFormatter help = new HelpFormatter();
        help.printHelp("Dissimilar v" + version, options);
        return;
    }

    if (com.hasOption("psnr") & com.hasOption("ssim")) {
        //do nothing - both on by default
    } else {
        if (com.hasOption("psnr")) {
            calcPSNR = true;
            calcSSIM = false;
        }
        if (com.hasOption("ssim")) {
            calcPSNR = false;
            calcSSIM = true;
        }
    }

    if (com.hasOption("heatmap")) {
        heatMapImage = com.getOptionValue("heatmap");
    }

    File one = new File(com.getArgs()[0]);
    File two = new File(com.getArgs()[1]);

    if (one.exists() && two.exists()) {
        compare(one, two, heatMapImage, calcSSIM, calcPSNR);
    }

}

From source file:de.clusteval.framework.ClustevalBackendServer.java

/**
 * This method can be used to start a backend server. The args parameter can
 * contain options that specify the behaviour of the server:
 * <ul>/*from w  w  w  .j  a  v a 2s .c  om*/
 * <li><b>-absRepositoryPath <absRepoPath></b>: An absolute path to the
 * repository</li>
 * <li><b>-port <port></b>: The port on which this server should listen</li>
 * </ul>
 * 
 * @param args
 *            Arguments to control the behaviour of the server
 * @throws FileNotFoundException
 * @throws InvalidRepositoryException
 * @throws RepositoryAlreadyExistsException
 * @throws RepositoryConfigurationException
 * @throws RepositoryConfigNotFoundException
 * @throws InterruptedException
 */
public static void main(String[] args)
        throws FileNotFoundException, RepositoryAlreadyExistsException, InvalidRepositoryException,
        RepositoryConfigNotFoundException, RepositoryConfigurationException, InterruptedException {

    // bugfix for log4j warning
    org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.OFF);
    org.apache.log4j.Logger.getRootLogger().addAppender(new org.apache.log4j.ConsoleAppender(
            new org.apache.log4j.PatternLayout("%d %-5p %c - %F:%L - %m%n")));

    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(serverCLIOptions, args);

        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("clustevalServer", "clusteval backend server " + VERSION, serverCLIOptions, "");
            System.exit(0);
        }

        if (cmd.hasOption("version")) {
            System.out.println(VERSION);
            System.exit(0);
        }

        if (cmd.getArgList().size() > 0)
            throw new ParseException("Unknown parameters: " + Arrays.toString(cmd.getArgs()));

        if (cmd.hasOption("port"))
            port = Integer.parseInt(cmd.getOptionValue("port"));
        else
            port = 1099;

        initLogging(cmd);

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

        if (cmd.hasOption("checkForRunResults"))
            config.setCheckForRunResults(Boolean.parseBoolean(cmd.getOptionValue("checkForRunResults")));

        if (cmd.hasOption("noDatabase"))
            config.setNoDatabase(true);

        Logger log = LoggerFactory.getLogger(ClustevalBackendServer.class);

        System.out.println("Starting clusteval server");
        System.out.println(VERSION);
        System.out.println("=========================");

        try {
            // try to establish a connection to R
            @SuppressWarnings("unused")
            MyRengine myRengine = new MyRengine("");
            isRAvailable = true;
        } catch (RserveException e) {
            log.error("Connection to Rserve could not be established, "
                    + "please ensure that your Rserve instance is "
                    + "running before starting this framework.");
            log.error(
                    "Functionality that requires R will not be available" + " until Rserve has been started.");
            isRAvailable = false;
        }

        @SuppressWarnings("unused")
        ClustevalBackendServer clusteringEvalFramework;
        if (cmd.hasOption("absRepoPath"))
            clusteringEvalFramework = new ClustevalBackendServer(cmd.getOptionValue("absRepoPath"));
        else
            clusteringEvalFramework = new ClustevalBackendServer(new File("repository").getAbsolutePath());

    } catch (ParseException e1) {
        System.err.println("Parsing failed.  Reason: " + e1.getMessage());

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("clustevalServer", "clusteval backend server " + VERSION, serverCLIOptions, "");
    }
}

From source file:com.cloudera.recordbreaker.schemadict.SchemaSuggest.java

/**
 * SchemaSuggest takes an avro file where schema elements may be anonymous.  It then attempts to 
 * compute good labels for the anonymous elts.  By default, this tool simply prints out the
 * suggested labels, if any.  The user may include a flag to rewrite the input data using
 * the new labels./* w  w  w . j  ava 2s  .  c om*/
 *
 * schemaSuggest avroFile 
 *
 */
public static void main(String argv[]) throws IOException {
    CommandLine cmd = null;
    boolean debug = false;
    Options options = new Options();
    options.addOption("?", false, "Help for command-line");
    options.addOption("f", true, "Accept suggestions and rewrite input to a new Avro file");
    options.addOption("d", false, "Debug mode");
    options.addOption("k", true, "How many matches to emit.");

    try {
        CommandLineParser parser = new PosixParser();
        cmd = parser.parse(options, argv);
    } catch (ParseException e) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("SchemaSuggest", options, true);
        System.err.println("Required inputs: <schemadictionary> <anonymousAvro>");
        System.exit(-1);
    }

    if (cmd.hasOption("?")) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("SchemaSuggest", options, true);
        System.err.println("Required inputs: <schemadictionary> <anonymousAvro>");
        System.exit(0);
    }

    if (cmd.hasOption("d")) {
        debug = true;
    }

    int k = 1;
    if (cmd.hasOption("k")) {
        try {
            k = Integer.parseInt(cmd.getOptionValue("k"));
        } catch (NumberFormatException nfe) {
        }
    }

    String[] argArray = cmd.getArgs();
    if (argArray.length < 2) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("SchemaSuggest", options, true);
        System.err.println("Required inputs: <schemadictionary> <anonymousAvro>");
        System.exit(0);
    }

    File dataDir = new File(argArray[0]).getCanonicalFile();
    File inputData = new File(argArray[1]).getCanonicalFile();
    SchemaSuggest ss = new SchemaSuggest(dataDir);
    List<DictionaryMapping> mappings = ss.inferSchemaMapping(inputData, k);

    if (!cmd.hasOption("f")) {
        System.out.println("Ranking of closest known data types, with match-distance (smaller is better):");
        int counter = 1;
        for (DictionaryMapping mapping : mappings) {
            SchemaMapping sm = mapping.getMapping();
            List<SchemaMappingOp> bestOps = sm.getMapping();

            System.err.println();
            System.err.println();
            System.err.println("-------------------------------------------------------------");
            System.out.println(
                    counter + ".  '" + mapping.getDictEntry().getInfo() + "', with distance: " + sm.getDist());

            List<SchemaMappingOp> renames = new ArrayList<SchemaMappingOp>();
            List<SchemaMappingOp> extraInTarget = new ArrayList<SchemaMappingOp>();
            List<SchemaMappingOp> extraInSource = new ArrayList<SchemaMappingOp>();

            for (SchemaMappingOp op : bestOps) {
                if (op.opcode == SchemaMappingOp.CREATE_OP) {
                    extraInTarget.add(op);
                } else if (op.opcode == SchemaMappingOp.DELETE_OP) {
                    if (op.getS1DatasetLabel().compareTo("input") == 0) {
                        extraInSource.add(op);
                    } else {
                        extraInTarget.add(op);
                    }
                } else if (op.opcode == SchemaMappingOp.TRANSFORM_OP) {
                    renames.add(op);
                }
            }

            System.err.println();
            System.err.println(" DISCOVERED LABELS");
            int counterIn = 1;
            if (renames.size() == 0) {
                System.err.println("  (None)");
            } else {
                for (SchemaMappingOp op : renames) {
                    System.err.println("  " + counterIn + ".  " + "In '" + op.getS1DatasetLabel() + "', label '"
                            + op.getS1FieldLabel() + "' AS " + op.getS2FieldLabel());
                    if (debug) {
                        if (op.getS1DocStr() != null && op.getS1DocStr().length() > 0) {
                            System.err.println(
                                    "         '" + op.getS1DocStr() + "'  ==> '" + op.getS2DocStr() + "'");
                        }
                    }
                    counterIn++;
                }
            }

            System.err.println();
            System.err.println(" UNMATCHED ITEMS IN TARGET DATA TYPE");
            counterIn = 1;
            if (extraInTarget.size() == 0) {
                System.err.println("  (None)");
            } else {
                for (SchemaMappingOp op : extraInTarget) {
                    System.err.println("  " + counterIn + ".  " + op.getS1FieldLabel());
                    if (debug) {
                        if (op.getS1DocStr() != null && op.getS1DocStr().length() > 0) {
                            System.err.println("         " + op.getS1DocStr());
                        }
                    }
                    counterIn++;
                }
            }

            System.err.println();
            System.err.println(" UNMATCHED ITEMS IN SOURCE DATA");
            counterIn = 1;
            if (extraInSource.size() == 0) {
                System.err.println("  (None)");
            } else {
                for (SchemaMappingOp op : extraInSource) {
                    System.err.println("  " + counterIn + ".  " + op.getS1FieldLabel());
                    if (debug) {
                        if (op.getS1DocStr() != null && op.getS1DocStr().length() > 0) {
                            System.err.println("         " + op.getS1DocStr());
                        }
                    }
                    counterIn++;
                }
            }
            counter++;
        }
    }
}