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:edu.msu.cme.rdp.readseq.utils.ResampleSeqFile.java

public static void main(String[] args) throws IOException {
    int numOfSelection = 0;
    int subregion_length = 0;

    try {/*  ww  w. ja v  a  2s. com*/
        CommandLine line = new PosixParser().parse(options, args);
        if (line.hasOption("num-selection")) {
            numOfSelection = Integer.parseInt(line.getOptionValue("num-selection"));
            if (numOfSelection < 1) {
                throw new Exception("num-selection should be at least 1");
            }
        }
        if (line.hasOption("subregion_length")) {
            subregion_length = Integer.parseInt(line.getOptionValue("subregion_length"));
            if (subregion_length < 1) {
                throw new Exception("subregion_length should be at least 1");
            }
        }

        args = line.getArgs();
        if (args.length != 2) {
            throw new Exception("Incorrect number of command line arguments");
        }
        ResampleSeqFile.select(args[0], args[1], numOfSelection, subregion_length);
    } catch (Exception e) {
        new HelpFormatter().printHelp(120, "ResampleSeqFile [options] <infile(dir)> <outdir>", "", options, "");
        System.out.println("ERROR: " + e.getMessage());
        return;
    }
}

From source file:com.bigdata.dastor.tools.SSTableImport.java

/**
 * Converts JSON to an SSTable file. JSON input can either be a file specified
 * using an optional command line argument, or supplied on standard in.
 * /* ww  w.j  a v a 2 s.  co m*/
 * @param args command line arguments
 * @throws IOException on failure to open/read/write files or output streams
 * @throws ParseException on failure to parse JSON input
 */
public static void main(String[] args) throws IOException, ParseException {
    String usage = String.format("Usage: %s -K keyspace -c column_family <json> <sstable>%n",
            SSTableImport.class.getName());

    CommandLineParser parser = new PosixParser();
    try {
        cmd = parser.parse(options, args);
    } catch (org.apache.commons.cli.ParseException e1) {
        System.err.println(e1.getMessage());
        System.err.println(usage);
        System.exit(1);
    }

    if (cmd.getArgs().length != 2) {
        System.err.println(usage);
        System.exit(1);
    }

    String json = cmd.getArgs()[0];
    String ssTable = cmd.getArgs()[1];
    String keyspace = cmd.getOptionValue(KEYSPACE_OPTION);
    String cfamily = cmd.getOptionValue(COLFAM_OPTION);

    importJson(json, keyspace, cfamily, ssTable);

    System.exit(0);
}

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

/**
 * @param args//from  w w  w. j  a  v a2 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);
    opt.setArgName("fn");
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    opt.setArgName("fn");
    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();
    }

    if (args.length == 0) {
        System.err.println("Specify at least one index type");
        exitWithHelp(options);
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    Set<String> selectedIndexes = new HashSet<String>(args.length);
    if (args.length == 1 && "all".equalsIgnoreCase(args[0]))
        selectedIndexes = AVAILIndexes;
    else
        selectedIndexes.addAll(Arrays.asList(args));

    if (!AVAILIndexes.containsAll(selectedIndexes)) {
        selectedIndexes.removeAll(AVAILIndexes);
        StringBuilder err = new StringBuilder("Unknown Index types: ");
        for (String it : selectedIndexes)
            err.append(it).append(" ");
        System.err.println(err);
        exitWithHelp(options);
    }

    SDFTopologicalIndexer sdfIndexer = new SDFTopologicalIndexer(outFile, selectedIndexes);

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

From source file:com.google.flightmap.parsing.faa.nasr.AirspaceParser.java

public static void main(String args[]) {
    CommandLine line = null;//  w  w  w  .j  a v  a  2s .c om
    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[] shapefiles = line.getOptionValues(SHAPEFILES_OPTION);
    final String dbFile = line.getOptionValue(AVIATION_DB_OPTION);

    try {
        for (String shapefile : shapefiles) {
            (new AirspaceParser(shapefile, dbFile)).execute();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(1);
    }
}

From source file:edu.msu.cme.rdp.graph.utils.ContigMerger.java

public static void main(String[] args) throws IOException {
    final BufferedReader hmmgsResultReader;
    final IndexedSeqReader nuclContigReader;
    final double minBits;
    final int minProtLength;
    final Options options = new Options();
    final PrintStream out;
    final ProfileHMM hmm;
    final FastaWriter protSeqOut;
    final FastaWriter nuclSeqOut;
    final boolean prot;
    final boolean all;
    final String shortSampleName;

    options.addOption("a", "all", false,
            "Generate all combinations for multiple paths, instead of just the best");
    options.addOption("b", "min-bits", true, "Minimum bits score");
    options.addOption("l", "min-length", true, "Minimum length");
    options.addOption("s", "short_samplename", true,
            "short sample name, to be used as part of contig identifiers. This allow analyzing contigs together from different samples in downstream analysis ");
    options.addOption("o", "out", true, "Write output to file instead of stdout");

    try {/*  ww w  .  j  a va2s .co  m*/
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("min-bits")) {
            minBits = Double.valueOf(line.getOptionValue("min-bits"));
        } else {
            minBits = Double.NEGATIVE_INFINITY;
        }

        if (line.hasOption("min-length")) {
            minProtLength = Integer.valueOf(line.getOptionValue("min-length"));
        } else {
            minProtLength = 0;
        }

        if (line.hasOption("short_samplename")) {
            shortSampleName = line.getOptionValue("short_samplename") + "_";
        } else {
            shortSampleName = "";
        }

        if (line.hasOption("out")) {
            out = new PrintStream(line.getOptionValue("out"));
        } else {
            out = System.err;
        }

        all = line.hasOption("all");

        args = line.getArgs();

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

        hmmgsResultReader = new BufferedReader(new FileReader(new File(args[1])));
        nuclContigReader = new IndexedSeqReader(new File(args[2]));
        hmm = HMMER3bParser.readModel(new File(args[0]));

        prot = (hmm.getAlphabet() == SequenceType.Protein);

        if (prot) {
            protSeqOut = new FastaWriter(new File("prot_merged.fasta"));
        } else {
            protSeqOut = null;
        }
        nuclSeqOut = new FastaWriter(new File("nucl_merged.fasta"));

    } catch (Exception e) {
        new HelpFormatter().printHelp("USAGE: ContigMerger [options] <hmm> <hmmgs_file> <nucl_contig>",
                options);
        System.err.println("Error: " + e.getMessage());
        System.exit(1);
        throw new RuntimeException("I hate you javac");
    }

    String line;
    SearchDirection lastDir = SearchDirection.left; //So this has an assumption built in
    //It depends on hmmgs always outputting left fragments, then right
    //We can't just use the kmer to figure out if we've switched to another starting point
    //because we allow multiple starting model pos, so two different starting
    //positions can have the same starting kmer

    Map<String, Sequence> leftContigs = new HashMap();
    Map<String, Sequence> rightContigs = new HashMap();

    int contigsMerged = 0;
    int writtenMerges = 0;
    long startTime = System.currentTimeMillis();
    String kmer = null;
    String geneName = null;

    while ((line = hmmgsResultReader.readLine()) != null) {
        if (line.startsWith("#")) {
            continue;
        }

        String[] lexemes = line.trim().split("\t");
        if (lexemes.length != 12 || lexemes[0].equals("-")) {
            System.err.println("Skipping line: " + line);
            continue;
        }
        //contig_53493   nirk   1500:6:35:16409:3561/1   ADV15048   tcggcgctctacacgttcctgcagcccggg   40   210   70   left   -44.692   184   0
        int index = 0;

        String seqid = lexemes[0];
        geneName = lexemes[1];
        String readid = lexemes[2];
        String refid = lexemes[3];
        kmer = lexemes[4];
        int modelStart = Integer.valueOf(lexemes[5]);

        int nuclLength = Integer.valueOf(lexemes[6]);
        int protLength = Integer.valueOf(lexemes[7]);

        SearchDirection dir = SearchDirection.valueOf(lexemes[8]);
        if (dir != lastDir) {
            if (dir == SearchDirection.left) {
                List<MergedContig> mergedContigs = all
                        ? mergeAllContigs(leftContigs, rightContigs, kmer, geneName, hmm)
                        : mergeContigs(leftContigs, rightContigs, kmer, geneName, hmm);

                contigsMerged++;

                for (MergedContig mc : mergedContigs) {
                    String mergedId = shortSampleName + geneName + "_" + mc.leftContig + "_" + mc.rightContig;
                    out.println(mergedId + "\t" + mc.length + "\t" + mc.score);

                    if (mc.score > minBits && mc.length > minProtLength) {
                        if (prot) {
                            protSeqOut.writeSeq(mergedId, mc.protSeq);
                        }
                        nuclSeqOut.writeSeq(mergedId, mc.nuclSeq);

                        writtenMerges++;
                    }
                }
                leftContigs.clear();
                rightContigs.clear();
            }

            lastDir = dir;
        }

        Sequence seq = nuclContigReader.readSeq(seqid);

        if (dir == SearchDirection.left) {
            leftContigs.put(seqid, seq);
        } else if (dir == SearchDirection.right) {
            rightContigs.put(seqid, seq);
        } else {
            throw new IOException("Cannot handle search direction " + dir);
        }
    }

    if (!leftContigs.isEmpty() || !rightContigs.isEmpty()) {
        List<MergedContig> mergedContigs = all ? mergeAllContigs(leftContigs, rightContigs, kmer, geneName, hmm)
                : mergeContigs(leftContigs, rightContigs, kmer, geneName, hmm);

        for (MergedContig mc : mergedContigs) {
            String mergedId = shortSampleName + mc.gene + "_" + mc.leftContig + "_" + mc.rightContig;
            out.println(mergedId + "\t" + mc.length + "\t" + mc.score);
            contigsMerged++;

            if (mc.score > minBits && mc.length > minProtLength) {
                if (prot) {
                    protSeqOut.writeSeq(mergedId, mc.protSeq);
                }
                nuclSeqOut.writeSeq(mergedId, mc.nuclSeq);
                writtenMerges++;
            }
        }
    }

    out.close();
    if (prot) {
        protSeqOut.close();
    }
    nuclSeqOut.close();

    System.err.println("Read in " + contigsMerged + " contigs, wrote out " + writtenMerges
            + " merged contigs in " + ((double) (System.currentTimeMillis() - startTime) / 1000) + "s");
}

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

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

    final String OPT_INFILE = "in";
    final String OPT_OUTFILE = "out";
    final String OPT_TEMPLATEFILE = "templates";
    final String OPT_RESETCOORDS = "reset";
    final String OPT_DEBUG = "debug";

    Options options = new Options();

    Option opt = new Option(OPT_INFILE, true, "Input file (oe-supported). Use .sdf to specify the file type.");
    opt.setRequired(true);//from ww  w .  j ava2 s  . com
    options.addOption(opt);

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

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

    opt = new Option(OPT_RESETCOORDS, false,
            "Reset coordinates in input file when aligning. This will delete original 2D coords and create new ones.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_DEBUG, false, "Print debug statements.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("h", false, "print usage statement");
    opt.setRequired(false);
    options.addOption(opt);

    PosixParser parser = new PosixParser();
    CommandLine cl = null;

    try {
        cl = parser.parse(options, args);
    } catch (Exception exp) {
        System.err.println(exp.getMessage());
        exitWithHelp(options);
    }

    //get command line parameters
    String inFile = cl.getOptionValue(OPT_INFILE);
    String outFile = cl.getOptionValue(OPT_OUTFILE);
    String templateFile = cl.getOptionValue(OPT_TEMPLATEFILE);
    boolean resetCoords = cl.hasOption(OPT_RESETCOORDS);
    boolean debug = cl.hasOption(OPT_DEBUG);

    sdf2DAlign myAlign = new sdf2DAlign(inFile, outFile, templateFile, resetCoords);
    myAlign.setDebug(debug);

    //get templates as subsearches
    List<OESubSearch> templates = myAlign.getTemplates();

    //apply template to input molecules
    myAlign.applyTemplates(templates);

    for (OESubSearch ss : templates)
        ss.delete();
}

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

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

    // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

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

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

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

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

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

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

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

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

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

    opt = new Option(OPT_WORKING_DIR, true, "Working directory to put files.");
    opt.setRequired(false);
    options.addOption(opt);

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

    if (args.length != 0) {
        System.err.println("Unknown arguments" + args);
        exitWithHelp(options);
    }

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

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    String fixedAtomTag = cmd.getOptionValue(OPT_FIXED_ATOM_TAG);
    boolean fixTorsion = (cmd.getOptionValue(OPT_FIX_TORSION) != null
            && cmd.getOptionValue(OPT_FIX_TORSION).equalsIgnoreCase("true"));
    String programName = cmd.getOptionValue(OPT_PROGRAM);
    String forcefield = cmd.getOptionValue(OPT_FORCEFIELD);
    String solvent = cmd.getOptionValue(OPT_SOLVENT);
    String workDir = cmd.getOptionValue(OPT_WORKING_DIR);

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

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

From source file:com.cyberway.issue.io.Warc2Arc.java

/**
 * Command-line interface to Arc2Warc.//from   w w  w  .  j  a  va  2 s . c  om
 *
 * @param args Command-line arguments.
 * @throws ParseException Failed parse of the command line.
 * @throws IOException
 * @throws java.text.ParseException
 */
public static void main(String[] args) throws ParseException, IOException, java.text.ParseException {
    Options options = new Options();
    options.addOption(new Option("h", "help", false, "Prints this message and exits."));
    options.addOption(new Option("f", "force", false, "Force overwrite of target file."));
    options.addOption(
            new Option("p", "prefix", true, "Prefix to use on created ARC files, else uses default."));
    options.addOption(
            new Option("s", "suffix", true, "Suffix to use on created ARC files, else uses default."));
    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.
    boolean force = false;
    String prefix = "WARC2ARC";
    String suffix = null;
    for (int i = 0; i < cmdlineOptions.length; i++) {
        switch (cmdlineOptions[i].getId()) {
        case 'h':
            usage(formatter, options, 0);
            break;

        case 'f':
            force = true;
            break;

        case 'p':
            prefix = cmdlineOptions[i].getValue();
            break;

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

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

    // If no args, print help.
    if (cmdlineArgs.size() != 2) {
        usage(formatter, options, 0);
    }
    (new Warc2Arc()).transform(new File(cmdlineArgs.get(0).toString()), new File(cmdlineArgs.get(1).toString()),
            prefix, suffix, force);
}

From source file:com.aestel.chemistry.openEye.fp.Fingerprinter.java

public static void main(String... args) throws IOException {
    long start = System.currentTimeMillis();
    long iCounter = 0;

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("in", true, "input file [.ism,.sdf,...]");
    opt.setRequired(true);/*from  ww  w . j  a va  2 s  .c  om*/
    options.addOption(opt);

    opt = new Option("out", true, "output file .tsv or oe-supported");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("idTag", true, "field with ID (default title)");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("fpType", true, "fingerPrintType: maccs|linear7|linear7*4|HashLinear7*4\n"
            + "   maccs: generate maccs keys\n"
            + "   linear7 generate 7 bonds long linear fingerprints (210k known rest hashed)\n"
            + "   linear7*4 linear 7 bonds if more than 4 atoms code atoms as * (5.1k known rest hashed)\n"
            + "   HashLinear7*4: as linear7*4 but hashed to 16k");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("format", true,
            "folded512|folded2048|bitList|fragList|none\n" + "   folded512/2048: hex encoded 512/2048 bits\n"
                    + "   bitList: list of bitpositions\n" + "   none: no fp output for use with writeCodeMap");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("writeCodeMap", false, "Overwrite the codeMap file at the end of processing");
    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 idTag = null;
    if (cmd.hasOption("idTag"))
        idTag = cmd.getOptionValue("idTag");

    String outformat = cmd.getOptionValue("format").toLowerCase().intern();
    if (args.length != 0) {
        exitWithHelp(options);
    }

    String type = cmd.getOptionValue("fpType");
    boolean updateDictionaryFile = cmd.hasOption("writeCodeMap");
    boolean hashUnknownFrag = true;
    if (type.equals("HashLinear7*4"))
        hashUnknownFrag = false;
    if (type.equals("maccs"))
        hashUnknownFrag = false;
    if (updateDictionaryFile)
        hashUnknownFrag = false;
    Fingerprinter fprinter = createFingerprinter(type, updateDictionaryFile, hashUnknownFrag);
    OEMolBase mol = new OEGraphMol();

    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    oemolistream ifs = new oemolistream(inFile);

    Runtime rt = Runtime.getRuntime();
    Outputter out;
    if (outFile.endsWith(".txt") || outFile.endsWith(".tab"))
        out = new TabOutputter(fprinter.getMapper(), outFile, outformat);
    else
        out = new OEOutputter(fprinter.getMapper(), outFile, type, outformat);

    while (oechem.OEReadMolecule(ifs, mol)) {
        iCounter++;
        Fingerprint fp = fprinter.getFingerprint(mol);

        String id;
        if (idTag == null)
            id = mol.GetTitle();
        else
            id = oechem.OEGetSDData(mol, idTag);

        if (iCounter % 100 == 0)
            System.err.print(".");
        if (iCounter % 4000 == 0) {
            System.err.printf(" %d %dsec\tt=%d f=%d u=%d m=%d tf=%d\n", iCounter,
                    (System.currentTimeMillis() - start) / 1000, rt.totalMemory() / 1024,
                    rt.freeMemory() / 1024, (rt.totalMemory() - rt.freeMemory()) / 1024, rt.maxMemory() / 1024,
                    (rt.freeMemory() + (rt.maxMemory() - rt.totalMemory())) / 1024);
        }

        out.output(id, mol, fp);
    }

    System.err.printf("Fingerprinter: Read %d structures in %d sec\n", iCounter,
            (System.currentTimeMillis() - start) / 1000);

    if (updateDictionaryFile)
        fprinter.writeDictionary();
    out.close();
    fprinter.close();
}

From source file:com.intuit.s3encrypt.S3Encrypt.java

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

    // create Options object
    Options options = new Options();
    options.addOption(create_bucket);/*from www .j  ava2s .c  om*/
    options.addOption(create_key);
    options.addOption(delete_bucket);
    options.addOption(get);
    options.addOption(help);
    options.addOption(inspect);
    options.addOption(keyfile);
    options.addOption(list_buckets);
    options.addOption(list_objects);
    options.addOption(put);
    options.addOption(remove);
    options.addOption(rotate);
    options.addOption(rotateall);
    options.addOption(rotateKey);

    //      CommandLineParser parser = new GnuParser();
    //       Changed from above GnuParser to below PosixParser because I found code which allows for multiple arguments 
    PosixParser parser = new PosixParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
        Logger.getRootLogger().setLevel(Level.OFF);

        if (cmd.hasOption("help")) {
            HelpFormatter help = new HelpFormatter();
            System.out.println();
            help.printHelp("S3Encrypt", options);
            System.out.println();
            System.exit(1);
        } else if (cmd.hasOption("create_key")) {
            keyname = cmd.getOptionValue("keyfile");
            createKeyFile(keyname);
            key = new File(keyname);
        } else {
            if (cmd.hasOption("keyfile")) {
                keyname = cmd.getOptionValue("keyfile");
            }
            key = new File(keyname);
        }

        if (!(key.exists())) {
            System.out.println("Key does not exist or not provided");
            System.exit(1);
        }

        //         AmazonS3 s3 = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());
        ClasspathPropertiesFileCredentialsProvider credentials = new ClasspathPropertiesFileCredentialsProvider(
                ".s3encrypt");
        EncryptionMaterials encryptionMaterials = new EncryptionMaterials(getKeyFile(keyname));
        AmazonS3EncryptionClient s3 = new AmazonS3EncryptionClient(credentials.getCredentials(),
                encryptionMaterials);
        //          Region usWest2 = Region.getRegion(Regions.US_WEST_2);
        //          s3.setRegion(usWest2);

        if (cmd.hasOption("create_bucket")) {
            String bucket = cmd.getOptionValue("create_bucket");
            System.out.println("Creating bucket " + bucket + "\n");
            s3.createBucket(bucket);
        } else if (cmd.hasOption("delete_bucket")) {
            String bucket = cmd.getOptionValue("delete_bucket");
            System.out.println("Deleting bucket " + bucket + "\n");
            s3.deleteBucket(bucket);
        } else if (cmd.hasOption("get")) {
            String[] searchArgs = cmd.getOptionValues("get");
            String bucket = searchArgs[0];
            String filename = searchArgs[1];
            getS3Object(cmd, s3, bucket, filename);
        } else if (cmd.hasOption("inspect")) {
            String[] searchArgs = cmd.getOptionValues("inspect");
            String bucket = searchArgs[0];
            String filename = searchArgs[1];
            String keyname = "encryption_key";
            String metadata = inspectS3Object(cmd, s3, bucket, filename, keyname);
            System.out.println(metadata);
        } else if (cmd.hasOption("list_buckets")) {
            System.out.println("Listing buckets");
            for (Bucket bucket : s3.listBuckets()) {
                System.out.println(bucket.getName());
            }
            System.out.println();
        } else if (cmd.hasOption("list_objects")) {
            String bucket = cmd.getOptionValue("list_objects");
            System.out.println("Listing objects");
            ObjectListing objectListing = s3.listObjects(new ListObjectsRequest().withBucketName(bucket));
            for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                System.out.println(objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
            }
            System.out.println();
        } else if (cmd.hasOption("put")) {
            String[] searchArgs = cmd.getOptionValues("put");
            String bucket = searchArgs[0];
            String filename = searchArgs[1];
            String metadataKeyname = "encryption_key";
            String key = keyname;
            putS3Object(cmd, s3, bucket, filename, metadataKeyname, key);
        } else if (cmd.hasOption("remove")) {
            String[] searchArgs = cmd.getOptionValues("remove");
            String bucket = searchArgs[0];
            String filename = searchArgs[1];
            System.out.println("Removing object in S3 from BUCKET = " + bucket + " FILENAME = " + filename);
            s3.deleteObject(new DeleteObjectRequest(bucket, filename));
            System.out.println();
        } else if (cmd.hasOption("rotate")) {
            String[] searchArgs = cmd.getOptionValues("rotate");
            String bucket = searchArgs[0];
            String filename = searchArgs[1];
            String key1 = cmd.getOptionValue("keyfile");
            String key2 = cmd.getOptionValue("rotateKey");
            String metadataKeyname = "encryption_key";
            System.out.println("Supposed to get object from here OPTION VALUE = " + bucket + " FILENAME = "
                    + filename + " KEY1 = " + key1 + " KEY2 = " + key2);

            EncryptionMaterials rotateEncryptionMaterials = new EncryptionMaterials(getKeyFile(key2));
            AmazonS3EncryptionClient rotateS3 = new AmazonS3EncryptionClient(credentials.getCredentials(),
                    rotateEncryptionMaterials);

            getS3Object(cmd, s3, bucket, filename);
            putS3Object(cmd, rotateS3, bucket, filename, metadataKeyname, key2);
        } else if (cmd.hasOption("rotateall")) {
            String[] searchArgs = cmd.getOptionValues("rotateall");
            String bucket = searchArgs[0];
            String key1 = searchArgs[1];
            String key2 = searchArgs[2];
            System.out.println("Supposed to rotateall here for BUCKET NAME = " + bucket + " KEY1 = " + key1
                    + " KEY2 = " + key2);
        } else {
            System.out.println("Something went wrong... ");
            System.exit(1);
        }

    } catch (ParseException e) {
        e.printStackTrace();
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which " + "means your request made it "
                + "to Amazon S3, but was rejected with an error response" + " for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which " + "means the client encountered "
                + "an internal error while trying to " + "communicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }

}