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

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

Introduction

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

Prototype

public String[] getOptionValues(char opt) 

Source Link

Document

Retrieves the array of values, if any, of an option.

Usage

From source file:eqtlmappingpipeline.util.ModuleEqtlNeutrophilReplication.java

/**
 * @param args the command line arguments
 *//*from ww  w . j ava2s  .  c  o m*/
public static void main(String[] args) throws IOException, LdCalculatorException {

    System.out.println(HEADER);
    System.out.println();
    System.out.flush(); //flush to make sure header is before errors
    try {
        Thread.sleep(25); //Allows flush to complete
    } catch (InterruptedException ex) {
    }

    CommandLineParser parser = new PosixParser();
    final CommandLine commandLine;
    try {
        commandLine = parser.parse(OPTIONS, args, true);
    } catch (ParseException ex) {
        System.err.println("Invalid command line arguments: " + ex.getMessage());
        System.err.println();
        new HelpFormatter().printHelp(" ", OPTIONS);
        System.exit(1);
        return;
    }

    final String[] genotypesBasePaths = commandLine.getOptionValues("g");
    final RandomAccessGenotypeDataReaderFormats genotypeDataType;
    final String replicationQtlFilePath = commandLine.getOptionValue("e");
    final String interactionQtlFilePath = commandLine.getOptionValue("i");
    final String outputFilePath = commandLine.getOptionValue("o");
    final double ldCutoff = Double.parseDouble(commandLine.getOptionValue("ld"));
    final int window = Integer.parseInt(commandLine.getOptionValue("w"));

    System.out.println("Genotype: " + Arrays.toString(genotypesBasePaths));
    System.out.println("Interaction file: " + interactionQtlFilePath);
    System.out.println("Replication file: " + replicationQtlFilePath);
    System.out.println("Output: " + outputFilePath);
    System.out.println("LD: " + ldCutoff);
    System.out.println("Window: " + window);

    try {
        if (commandLine.hasOption("G")) {
            genotypeDataType = RandomAccessGenotypeDataReaderFormats
                    .valueOf(commandLine.getOptionValue("G").toUpperCase());
        } else {
            if (genotypesBasePaths[0].endsWith(".vcf")) {
                System.err.println(
                        "Only vcf.gz is supported. Please see manual on how to do create a vcf.gz file.");
                System.exit(1);
                return;
            }
            try {
                genotypeDataType = RandomAccessGenotypeDataReaderFormats
                        .matchFormatToPath(genotypesBasePaths[0]);
            } catch (GenotypeDataException e) {
                System.err
                        .println("Unable to determine input 1 type based on specified path. Please specify -G");
                System.exit(1);
                return;
            }
        }
    } catch (IllegalArgumentException e) {
        System.err.println("Error parsing --genotypesFormat \"" + commandLine.getOptionValue("G")
                + "\" is not a valid input data format");
        System.exit(1);
        return;
    }

    final RandomAccessGenotypeData genotypeData;

    try {
        genotypeData = genotypeDataType.createFilteredGenotypeData(genotypesBasePaths, 100, null, null, null,
                0.8);
    } catch (TabixFileNotFoundException e) {
        LOGGER.fatal("Tabix file not found for input data at: " + e.getPath() + "\n"
                + "Please see README on how to create a tabix file");
        System.exit(1);
        return;
    } catch (IOException e) {
        LOGGER.fatal("Error reading input data: " + e.getMessage(), e);
        System.exit(1);
        return;
    } catch (IncompatibleMultiPartGenotypeDataException e) {
        LOGGER.fatal("Error combining the impute genotype data files: " + e.getMessage(), e);
        System.exit(1);
        return;
    } catch (GenotypeDataException e) {
        LOGGER.fatal("Error reading input data: " + e.getMessage(), e);
        System.exit(1);
        return;
    }

    ChrPosTreeMap<ArrayList<ReplicationQtl>> replicationQtls = new ChrPosTreeMap<>();

    CSVReader replicationQtlReader = new CSVReader(new FileReader(replicationQtlFilePath), '\t');
    replicationQtlReader.readNext();//skip header
    String[] replicationLine;
    while ((replicationLine = replicationQtlReader.readNext()) != null) {

        try {

            GeneticVariant variant = genotypeData.getSnpVariantByPos(replicationLine[REPLICATION_SNP_CHR_COL],
                    Integer.parseInt(replicationLine[REPLICATION_SNP_POS_COL]));
            if (variant == null) {
                continue;
            }

            ReplicationQtl replicationQtl = new ReplicationQtl(replicationLine[REPLICATION_SNP_CHR_COL],
                    Integer.parseInt(replicationLine[REPLICATION_SNP_POS_COL]),
                    replicationLine[REPLICATION_GENE_COL],
                    Double.parseDouble(replicationLine[REPLICATION_BETA_COL]),
                    variant.getAlternativeAlleles().get(0).getAlleleAsString());
            ArrayList<ReplicationQtl> posReplicationQtls = replicationQtls.get(replicationQtl.getChr(),
                    replicationQtl.getPos());
            if (posReplicationQtls == null) {
                posReplicationQtls = new ArrayList<>();
                replicationQtls.put(replicationQtl.getChr(), replicationQtl.getPos(), posReplicationQtls);
            }
            posReplicationQtls.add(replicationQtl);

        } catch (Exception e) {
            System.out.println(Arrays.toString(replicationLine));
            throw e;
        }
    }

    int interactionSnpNotInGenotypeData = 0;
    int noReplicationQtlsInWindow = 0;
    int noReplicationQtlsInLd = 0;
    int multipleReplicationQtlsInLd = 0;
    int replicationTopSnpNotInGenotypeData = 0;

    final CSVWriter outputWriter = new CSVWriter(new FileWriter(new File(outputFilePath)), '\t', '\0');
    final String[] outputLine = new String[14];
    int c = 0;
    outputLine[c++] = "Chr";
    outputLine[c++] = "Pos";
    outputLine[c++] = "SNP";
    outputLine[c++] = "Gene";
    outputLine[c++] = "Module";
    outputLine[c++] = "DiscoveryZ";
    outputLine[c++] = "ReplicationZ";
    outputLine[c++] = "DiscoveryZCorrected";
    outputLine[c++] = "ReplicationZCorrected";
    outputLine[c++] = "DiscoveryAlleleAssessed";
    outputLine[c++] = "ReplicationAlleleAssessed";
    outputLine[c++] = "bestLd";
    outputLine[c++] = "bestLd_dist";
    outputLine[c++] = "nextLd";
    outputWriter.writeNext(outputLine);

    HashSet<String> notFound = new HashSet<>();

    CSVReader interactionQtlReader = new CSVReader(new FileReader(interactionQtlFilePath), '\t');
    interactionQtlReader.readNext();//skip header
    String[] interactionQtlLine;
    while ((interactionQtlLine = interactionQtlReader.readNext()) != null) {

        String snp = interactionQtlLine[1];
        String chr = interactionQtlLine[2];
        int pos = Integer.parseInt(interactionQtlLine[3]);
        String gene = interactionQtlLine[4];
        String alleleAssessed = interactionQtlLine[9];
        String module = interactionQtlLine[12];
        double discoveryZ = Double.parseDouble(interactionQtlLine[10]);

        GeneticVariant interactionQtlVariant = genotypeData.getSnpVariantByPos(chr, pos);

        if (interactionQtlVariant == null) {
            System.err.println("Interaction QTL SNP not found in genotype data: " + chr + ":" + pos);
            ++interactionSnpNotInGenotypeData;
            continue;
        }

        ReplicationQtl bestMatch = null;
        double bestMatchR2 = Double.NaN;
        Ld bestMatchLd = null;
        double nextBestR2 = Double.NaN;

        ArrayList<ReplicationQtl> sameSnpQtls = replicationQtls.get(chr, pos);

        if (sameSnpQtls != null) {
            for (ReplicationQtl sameSnpQtl : sameSnpQtls) {
                if (sameSnpQtl.getGene().equals(gene)) {
                    bestMatch = sameSnpQtl;
                    bestMatchR2 = 1;
                }
            }
        }

        NavigableMap<Integer, ArrayList<ReplicationQtl>> potentionalReplicationQtls = replicationQtls
                .getChrRange(chr, pos - window, true, pos + window, true);

        for (ArrayList<ReplicationQtl> potentialReplicationQtls : potentionalReplicationQtls.values()) {

            for (ReplicationQtl potentialReplicationQtl : potentialReplicationQtls) {

                if (!potentialReplicationQtl.getGene().equals(gene)) {
                    continue;
                }

                GeneticVariant potentialReplicationQtlVariant = genotypeData
                        .getSnpVariantByPos(potentialReplicationQtl.getChr(), potentialReplicationQtl.getPos());

                if (potentialReplicationQtlVariant == null) {
                    notFound.add(potentialReplicationQtl.getChr() + ":" + potentialReplicationQtl.getPos());
                    ++replicationTopSnpNotInGenotypeData;
                    continue;
                }

                Ld ld = interactionQtlVariant.calculateLd(potentialReplicationQtlVariant);
                double r2 = ld.getR2();

                if (r2 > 1) {
                    r2 = 1;
                }

                if (bestMatch == null) {
                    bestMatch = potentialReplicationQtl;
                    bestMatchR2 = r2;
                    bestMatchLd = ld;
                } else if (r2 > bestMatchR2) {
                    bestMatch = potentialReplicationQtl;
                    nextBestR2 = bestMatchR2;
                    bestMatchR2 = r2;
                    bestMatchLd = ld;
                }

            }
        }

        double replicationZ = Double.NaN;
        double replicationZCorrected = Double.NaN;
        double discoveryZCorrected = Double.NaN;

        String replicationAlleleAssessed = null;

        if (bestMatch != null) {
            replicationZ = bestMatch.getBeta();
            replicationAlleleAssessed = bestMatch.getAssessedAllele();

            if (pos != bestMatch.getPos()) {

                String commonHap = null;
                double commonHapFreq = -1;
                for (Map.Entry<String, Double> hapFreq : bestMatchLd.getHaplotypesFreq().entrySet()) {

                    double f = hapFreq.getValue();

                    if (f > commonHapFreq) {
                        commonHapFreq = f;
                        commonHap = hapFreq.getKey();
                    }

                }

                String[] commonHapAlleles = StringUtils.split(commonHap, '/');

                discoveryZCorrected = commonHapAlleles[0].equals(alleleAssessed) ? discoveryZ : discoveryZ * -1;
                replicationZCorrected = commonHapAlleles[1].equals(replicationAlleleAssessed) ? replicationZ
                        : replicationZ * -1;

            } else {

                discoveryZCorrected = discoveryZ;
                replicationZCorrected = alleleAssessed.equals(replicationAlleleAssessed) ? replicationZ
                        : replicationZ * -1;

            }

        }

        c = 0;
        outputLine[c++] = chr;
        outputLine[c++] = String.valueOf(pos);
        outputLine[c++] = snp;
        outputLine[c++] = gene;
        outputLine[c++] = module;
        outputLine[c++] = String.valueOf(discoveryZ);
        outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(replicationZ);
        outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(discoveryZCorrected);
        outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(replicationZCorrected);
        outputLine[c++] = alleleAssessed;
        outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(bestMatch.getAssessedAllele());
        outputLine[c++] = String.valueOf(bestMatchR2);
        outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(Math.abs(pos - bestMatch.getPos()));
        outputLine[c++] = String.valueOf(nextBestR2);
        outputWriter.writeNext(outputLine);

    }

    outputWriter.close();

    for (String e : notFound) {
        System.err.println("Not found: " + e);
    }

    System.out.println("interactionSnpNotInGenotypeData: " + interactionSnpNotInGenotypeData);
    System.out.println("noReplicationQtlsInWindow: " + noReplicationQtlsInWindow);
    System.out.println("noReplicationQtlsInLd: " + noReplicationQtlsInLd);
    System.out.println("multipleReplicationQtlsInLd: " + multipleReplicationQtlsInLd);
    System.out.println("replicationTopSnpNotInGenotypeData: " + replicationTopSnpNotInGenotypeData);

}

From source file:com.github.besherman.fingerprint.Main.java

public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withDescription("creates a fingerprint file for the directory").hasArg()
            .withArgName("dir").create('c'));

    options.addOption(OptionBuilder.withDescription("shows a diff between two fingerprint files")
            .withArgName("left-file> <right-file").hasArgs(2).create('d'));

    options.addOption(OptionBuilder.withDescription("shows a diff between a fingerprint and a directory")
            .withArgName("fingerprint> <dir").hasArgs(2).create('t'));

    options.addOption(OptionBuilder.withDescription("shows duplicates in a directory").withArgName("dir")
            .hasArgs(1).create('u'));

    options.addOption(/*from   w w  w  .  j  av a2 s  .  c o m*/
            OptionBuilder.withDescription("output to file").withArgName("output-file").hasArg().create('o'));

    PosixParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        System.out.println(ex.getMessage());
        System.out.println("");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fingerprint-dir", options, true);
        System.exit(7);
    }

    if (cmd.hasOption('c')) {
        Path root = Paths.get(cmd.getOptionValue('c'));

        if (!Files.isDirectory(root)) {
            System.err.println("root is not a directory");
            System.exit(7);
        }

        OutputStream out = System.out;

        if (cmd.hasOption('o')) {
            Path p = Paths.get(cmd.getOptionValue('o'));
            out = Files.newOutputStream(p);
        }

        Fingerprint fp = new Fingerprint(root, "");
        fp.write(out);

    } else if (cmd.hasOption('d')) {
        String[] ar = cmd.getOptionValues('d');
        Path leftFingerprintFile = Paths.get(ar[0]), rightFingerprintFile = Paths.get(ar[1]);
        if (!Files.isRegularFile(leftFingerprintFile)) {
            System.out.printf("%s is not a file%n", leftFingerprintFile);
            System.exit(7);
        }
        if (!Files.isRegularFile(rightFingerprintFile)) {
            System.out.printf("%s is not a file%n", rightFingerprintFile);
            System.exit(7);
        }

        Fingerprint left, right;
        try (InputStream input = Files.newInputStream(leftFingerprintFile)) {
            left = new Fingerprint(input);
        }

        try (InputStream input = Files.newInputStream(rightFingerprintFile)) {
            right = new Fingerprint(input);
        }

        Diff diff = new Diff(left, right);

        // TODO: if we have redirected output
        diff.print(System.out);
    } else if (cmd.hasOption('t')) {
        throw new RuntimeException("Not yet implemented");
    } else if (cmd.hasOption('u')) {
        Path root = Paths.get(cmd.getOptionValue('u'));
        Fingerprint fp = new Fingerprint(root, "");
        Map<String, FilePrint> map = new HashMap<>();
        fp.stream().forEach(f -> {
            if (map.containsKey(f.getHash())) {
                System.out.println("  " + map.get(f.getHash()).getPath());
                System.out.println("= " + f.getPath());
                System.out.println("");
            } else {
                map.put(f.getHash(), f);
            }
        });
    } else {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fingd", options, true);
    }
}

From source file:com.aguin.stock.recommender.UserOptions.java

public static void main(String[] args) {
    options = new Options();
    Option optU = OptionBuilder.hasArg().withArgName("uid").isRequired(true).withType(String.class)
            .withDescription(// w  w  w  . j  a va  2 s.  c  o m
                    "User ID : must be a valid email address which serves as the unique identity of the portfolio")
            .create("u");

    Option optI = OptionBuilder.hasOptionalArgs().withArgName("item").withType(String.class).isRequired(false)
            .withDescription(
                    "Stock(s) in your portfolio: Print all stocks selected by this option and preferences against them")
            .create("i");

    Option optP = OptionBuilder.hasOptionalArgs().withArgName("pref").isRequired(false).withType(Long.class)
            .withDescription(
                    "Preference(s) against stocks in portfolio : Print all preferences specified in option and all stocks listed against that preference. Multiple preferences may be specified to draw on the many-many relationship between stocks and preferences matrices")
            .create("p");

    Option optIP = OptionBuilder.hasArg().withArgName("itempref").withValueSeparator(':').isRequired(false)
            .withDescription(
                    "Enter stock and preferences over command line. Any new stock will be registered as a new entry along with preference. Each new preference for an already existing stock will overwrite the existing preference(so be careful!)")
            .create("ip");

    Option optF = OptionBuilder.hasArg().withArgName("itempreffile").withType(String.class)
            .withDescription("File to read stock preference data from").isRequired(false).create("f");

    Option optH = OptionBuilder.hasArg(false).withArgName("help").withType(String.class)
            .withDescription("Display usage").isRequired(false).create("h");

    options.addOption(optU);
    options.addOption(optI);
    options.addOption(optP);
    options.addOption(optIP);
    options.addOption(optF);
    options.addOption(optH);

    parser = new BasicParser();
    CommandLine line = null;

    try {
        line = parser.parse(options, args);
    } catch (MissingOptionException e) {
        System.out.println("Missing options");
        printUsage();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (line.hasOption("help")) {
        printUsage();
    }
    UserArgumentEmailType uEmailId = new UserArgumentEmailType(line.getOptionValue("u"));
    String uEmailIdStr = uEmailId.toString();

    if (MongoDBUserModel.registered(uEmailIdStr)) {
        System.out.format("Already registered user %s\n", uEmailIdStr);
    } else {
        System.out.format("+--Starting transaction for user %s --+\n", uEmailIdStr);
    }

    if (line.hasOption("f")) {
        System.out.println("Query::UpdateDB: itempreffile(s)\n");
        String[] uItemPrefFiles = line.getOptionValues("f");
        for (String it : uItemPrefFiles) {
            System.out.format("Updating db with user file %s\n", it);
            UserItemPrefFile uItemPrefFile = new UserItemPrefFile(uEmailIdStr, it);
            uItemPrefFile.writeToDB();
        }
    }
    if (line.hasOption("i")) {
        System.out.println("Query::ReadDB: item(s)\n");
        String[] uItems = line.getOptionValues("i");
        for (String it : uItems) {
            System.out.format("Searching for item %s in db\n", it);
            UserItem uItem = new UserItem(uEmailIdStr, it);
            uItem.readFromDB();
        }
    }
    if (line.hasOption("p")) {
        System.out.println("Query::ReadDB: preference(s)");
        String[] uPrefs = line.getOptionValues("p");
        for (String it : uPrefs) {
            System.out.format("Searching for preference %s in db\n", it);
            UserPreference uPref = new UserPreference(uEmailIdStr, it);
            uPref.readFromDB();
        }
    }
    if (line.hasOption("ip")) {
        System.out.println("Query::UpdateDB: itempref(s)\n");
        String[] uItemPrefs = line.getOptionValues("ip");
        for (String it : uItemPrefs) {
            System.out.format("Updating item:preference pair %s\n", it);
            String[] pair = it.split(":");
            System.out.format("%s:%s:%s", uEmailIdStr, pair[0], pair[1]);
            UserItemPreference uItemPref = new UserItemPreference(uEmailIdStr, pair[0], pair[1]);
            uItemPref.writeToDB();
        }
    }
    System.out.format("+-- Ending transaction for user %s --+\n", uEmailIdStr);

}

From source file:com.ibm.zurich.Main.java

public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
    Option help = new Option(HELP, "print this message");
    Option version = new Option(VERSION, "print the version information");

    Options options = new Options();

    Option useCurve = Option.builder(USECURVE).hasArg().argName("curve")
            .desc("Specify the BN Curve. Options: " + curveOptions()).build();
    Option isskeygen = Option.builder(IKEYGEN).numberOfArgs(3).argName("ipk><isk><RL")
            .desc("Generate Issuer key pair and empty revocation list and store it in files").build();
    Option join1 = Option.builder(JOIN1).numberOfArgs(3).argName("ipk><authsk><msg1")
            .desc("Create an authenticator secret key and perform the first step of the join protocol").build();
    Option join2 = Option.builder(JOIN2).numberOfArgs(4).argName("ipk><isk><msg1><msg2")
            .desc("Complete the join protocol").build();
    Option verify = Option.builder(VERIFY).numberOfArgs(5).argName("ipk><sig><krd><appId><RL")
            .desc("Verify a signature").build();
    Option sign = Option.builder(SIGN).numberOfArgs(6).argName("ipk><authsk><msg2><appId><krd><sig")
            .desc("create a signature").build();

    options.addOption(help);//from   ww  w .j av a2s  . c  o  m
    options.addOption(version);
    options.addOption(useCurve);
    options.addOption(isskeygen);
    options.addOption(sign);
    options.addOption(verify);
    options.addOption(join1);
    options.addOption(join2);

    HelpFormatter formatter = new HelpFormatter();
    CommandLineParser parser = new DefaultParser();

    //FIXME Choose a proper instantiation of SecureRandom depending on the platform
    SecureRandom random = new SecureRandom();
    Base64.Encoder encoder = Base64.getUrlEncoder();
    Base64.Decoder decoder = Base64.getUrlDecoder();
    try {
        CommandLine line = parser.parse(options, args);
        BNCurveInstantiation instantiation = null;
        BNCurve curve = null;
        if (line.hasOption(HELP) || line.getOptions().length == 0) {
            formatter.printHelp(USAGE, options);
        } else if (line.hasOption(VERSION)) {
            System.out.println("Version " + Main.class.getPackage().getImplementationVersion());
        } else if (line.hasOption(USECURVE)) {
            instantiation = BNCurveInstantiation.valueOf(line.getOptionValue(USECURVE));
            curve = new BNCurve(instantiation);
        } else {
            System.out.println("Specify the curve to use.");
            return;
        }

        if (line.hasOption(IKEYGEN)) {
            String[] optionValues = line.getOptionValues(IKEYGEN);

            // Create secret key
            IssuerSecretKey sk = Issuer.createIssuerKey(curve, random);

            // Store pk
            writeToFile((new IssuerPublicKey(curve, sk, random)).toJSON(curve), optionValues[0]);

            // Store sk
            writeToFile(sk.toJson(curve), optionValues[1]);

            // Create empty revocation list and store
            HashSet<BigInteger> rl = new HashSet<BigInteger>();
            writeToFile(Verifier.revocationListToJson(rl, curve), optionValues[2]);
        } else if (line.hasOption(SIGN)) {
            //("ipk><authsk><msg2><appId><krd><sig")

            String[] optionValues = line.getOptionValues(SIGN);
            IssuerPublicKey ipk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0]));

            BigInteger authsk = curve.bigIntegerFromB(decoder.decode(readFromFile(optionValues[1])));
            JoinMessage2 msg2 = new JoinMessage2(curve, readStringFromFile(optionValues[2]));

            // setup a new authenticator
            Authenticator auth = new Authenticator(curve, ipk, authsk);
            auth.EcDaaJoin1(curve.getRandomModOrder(random));
            if (auth.EcDaaJoin2(msg2)) {
                EcDaaSignature sig = auth.EcDaaSign(optionValues[3]);

                // Write krd to file
                writeToFile(sig.krd, optionValues[4]);

                // Write signature to file
                writeToFile(sig.encode(curve), optionValues[5]);

                System.out.println("Signature written to " + optionValues[5]);
            } else {
                System.out.println("JoinMsg2 invalid");
            }
        } else if (line.hasOption(VERIFY)) {
            Verifier ver = new Verifier(curve);
            String[] optionValues = line.getOptionValues(VERIFY);
            String pkFile = optionValues[0];
            String sigFile = optionValues[1];
            String krdFile = optionValues[2];
            String appId = optionValues[3];
            String rlPath = optionValues[4];
            byte[] krd = Files.readAllBytes(Paths.get(krdFile));
            IssuerPublicKey pk = new IssuerPublicKey(curve, readStringFromFile(pkFile));
            EcDaaSignature sig = new EcDaaSignature(Files.readAllBytes(Paths.get(sigFile)), krd, curve);
            boolean valid = ver.verify(sig, appId, pk,
                    Verifier.revocationListFromJson(readStringFromFile(rlPath), curve));
            System.out.println("Signature is " + (valid ? "valid." : "invalid."));
        } else if (line.hasOption(JOIN1)) {
            String[] optionValues = line.getOptionValues(JOIN1);
            IssuerPublicKey ipk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0]));

            // Create authenticator key
            BigInteger sk = curve.getRandomModOrder(random);
            writeToFile(encoder.encodeToString(curve.bigIntegerToB(sk)), optionValues[1]);
            Authenticator auth = new Authenticator(curve, ipk, sk);
            JoinMessage1 msg1 = auth.EcDaaJoin1(curve.getRandomModOrder(random));
            writeToFile(msg1.toJson(curve), optionValues[2]);
        } else if (line.hasOption(JOIN2)) {
            String[] optionValues = line.getOptionValues(JOIN2);

            // create issuer with the specified key
            IssuerPublicKey pk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0]));
            IssuerSecretKey sk = new IssuerSecretKey(curve, readStringFromFile(optionValues[1]));
            Issuer iss = new Issuer(curve, sk, pk);

            JoinMessage1 msg1 = new JoinMessage1(curve, readStringFromFile(optionValues[2]));

            // Note that we do not check for nonce freshness.
            JoinMessage2 msg2 = iss.EcDaaIssuerJoin(msg1, false);
            if (msg2 == null) {
                System.out.println("Join message invalid.");
            } else {
                System.out.println("Join message valid, msg2 written to file.");
                writeToFile(msg2.toJson(curve), optionValues[3]);
            }
        }
    } catch (ParseException e) {
        System.out.println("Error parsing input.");
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

/**
 * @param args// w  w w. j  a v a2s. 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);
    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);

    opt = new Option(OPT_NORMALIZATION, true,
            "Normalization method: Counts|CountsPerAtom|CountsPerFeature(def) multiple allowed");
    opt.setArgName("meth");
    options.addOption(opt);

    opt = new Option(OPT_PRINTDESC, false,
            "Causes the descriptor for describing each linear path in a molceule to be created");
    options.addOption(opt);

    opt = new Option(OPT_RGROUPTYPES, false, "treat RGroup attachement point ([U]) as atom type.");
    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);
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);

    AtomTyperInterface[] myTypes = CATSIndexer.typers;
    String tagPrefix = "";
    if (cmd.hasOption(OPT_RGROUPTYPES)) {
        myTypes = CATSIndexer.rgroupTypers;
        tagPrefix = "RG";
    }

    if (cmd.hasOption(OPT_PRINTDESC)) {
        SDFCatsIndexer sdfIndexer = new SDFCatsIndexer(myTypes, tagPrefix);
        sdfIndexer.printDescriptors(inFile, outFile);
        sdfIndexer.close();
        return;
    }

    EnumSet<Normalization> normMeth = EnumSet.noneOf(Normalization.class);
    if (cmd.hasOption(OPT_NORMALIZATION))
        for (String n : cmd.getOptionValues(OPT_NORMALIZATION))
            normMeth.add(Normalization.valueOf(n));
    else
        normMeth.add(Normalization.CountsPerFeature);

    SDFCatsIndexer sdfIndexer = new SDFCatsIndexer(myTypes, tagPrefix);
    sdfIndexer.run(inFile, outFile, normMeth);
    sdfIndexer.close();
}

From source file:com.msd.gin.halyard.tools.HalyardUpdate.java

/**
 * Main of the HalyardUpdate/*from w w w  .j av a2  s. c  o m*/
 * @param args String command line arguments
 * @throws Exception throws Exception in case of any problem
 */
public static void main(final String args[]) throws Exception {
    if (conf == null)
        conf = new Configuration();
    Options options = new Options();
    options.addOption(newOption("h", null, "Prints this help"));
    options.addOption(newOption("v", null, "Prints version"));
    options.addOption(newOption("s", "source_htable", "Source HBase table with Halyard RDF store"));
    options.addOption(
            newOption("q", "sparql_query", "SPARQL tuple or graph query executed to export the data"));
    try {
        CommandLine cmd = new PosixParser().parse(options, args);
        if (args.length == 0 || cmd.hasOption('h')) {
            printHelp(options);
            return;
        }
        if (cmd.hasOption('v')) {
            Properties p = new Properties();
            try (InputStream in = HalyardUpdate.class
                    .getResourceAsStream("/META-INF/maven/com.msd.gin.halyard/hbasesail/pom.properties")) {
                if (in != null)
                    p.load(in);
            }
            System.out.println("Halyard Update version " + p.getProperty("version", "unknown"));
            return;
        }
        if (!cmd.getArgList().isEmpty())
            throw new ParseException("Unknown arguments: " + cmd.getArgList().toString());
        for (char c : "sq".toCharArray()) {
            if (!cmd.hasOption(c))
                throw new ParseException("Missing mandatory option: " + c);
        }
        for (char c : "sq".toCharArray()) {
            String s[] = cmd.getOptionValues(c);
            if (s != null && s.length > 1)
                throw new ParseException("Multiple values for option: " + c);
        }

        SailRepository rep = new SailRepository(
                new HBaseSail(conf, cmd.getOptionValue('s'), false, 0, true, 0, null));
        rep.initialize();
        try {
            Update u = rep.getConnection().prepareUpdate(QueryLanguage.SPARQL, cmd.getOptionValue('q'));
            LOG.info("Update execution started");
            u.execute();
            LOG.info("Update finished");
        } finally {
            rep.shutDown();
        }

    } catch (Exception exp) {
        System.out.println(exp.getMessage());
        printHelp(options);
        throw exp;
    }
}

From source file:CircularGenerator.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options helpOptions = new Options();
    helpOptions.addOption("h", "help", false, "show this help page");
    Options options = new Options();
    options.addOption("h", "help", false, "show this help page");
    options.addOption(OptionBuilder.withLongOpt("input").withArgName("INPUT")
            .withDescription("the input FastA File").isRequired().hasArg().create("i"));
    options.addOption(OptionBuilder.withLongOpt("elongation").withArgName("ELONGATION")
            .withDescription("the elongation factor [INT]").isRequired().hasArg().create("e"));
    options.addOption(OptionBuilder.withLongOpt("seq").withArgName("SEQ")
            .withDescription("the names of the sequences that should to be elongated").isRequired().hasArg()
            .hasOptionalArgs().hasArg().create("s"));
    HelpFormatter helpformatter = new HelpFormatter();
    CommandLineParser parser = new BasicParser();
    try {/* w w  w  .  j a va 2s . c o m*/
        CommandLine cmd = parser.parse(helpOptions, args);
        if (cmd.hasOption('h')) {
            helpformatter.printHelp(CLASS_NAME + "v" + VERSION, options);
            System.exit(0);
        }
    } catch (ParseException e1) {
    }
    String input = "";
    String tmpElongation = "";
    Integer elongation = 0;
    String[] names = new String[0];
    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption('i')) {
            input = cmd.getOptionValue('i');
        }
        if (cmd.hasOption('e')) {
            tmpElongation = cmd.getOptionValue('e');
            try {
                elongation = Integer.parseInt(tmpElongation);
            } catch (Exception e) {
                System.err.println("elongation not an Integer: " + tmpElongation);
                System.exit(0);
            }
        }
        if (cmd.hasOption('s')) {
            names = cmd.getOptionValues('s');
        }
    } catch (ParseException e) {
        helpformatter.printHelp(CLASS_NAME, options);
        System.err.println(e.getMessage());
        System.exit(0);
    }

    CircularGenerator cg = new CircularGenerator(elongation);
    File f = new File(input);
    for (String s : names) {
        cg.keys_to_treat_circular.add(s);
    }
    cg.extendFastA(f);

}

From source file:com.bericotech.clavin.index.IndexDirectoryBuilder.java

/**
 * Turns a GeoNames gazetteer file into a Lucene index, and adds
 * some supplementary gazetteer records at the end.
 *
 * @param args              not used//from  w ww  .j  a v a2 s  . c o m
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    Options options = getOptions();
    CommandLine cmd = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException pe) {
        LOG.error(pe.getMessage());
        printHelp(options);
        System.exit(-1);
    }

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

    String indexPath = cmd.getOptionValue(INDEX_PATH_OPTION, DEFAULT_INDEX_DIRECTORY);
    String[] gazetteerPaths = cmd.getOptionValues(GAZETTEER_FILES_OPTION);
    if (gazetteerPaths == null || gazetteerPaths.length == 0) {
        gazetteerPaths = DEFAULT_GAZETTEER_FILES;
    }
    boolean replaceIndex = cmd.hasOption(REPLACE_INDEX_OPTION);
    boolean fullAncestry = cmd.hasOption(FULL_ANCESTRY_OPTION);

    File idir = new File(indexPath);
    // if the index directory exists, delete it if we are replacing, otherwise
    // exit gracefully
    if (idir.exists()) {
        if (replaceIndex) {
            LOG.info("Replacing index: {}", idir.getAbsolutePath());
            FileUtils.deleteDirectory(idir);
        } else {
            LOG.info("{} exists. Remove the directory and try again.", idir.getAbsolutePath());
            System.exit(-1);
        }
    }

    List<File> gazetteerFiles = new ArrayList<File>();
    for (String gp : gazetteerPaths) {
        File gf = new File(gp);
        if (gf.isFile() && gf.canRead()) {
            gazetteerFiles.add(gf);
        } else {
            LOG.info("Unable to read Gazetteer file: {}", gf.getAbsolutePath());
        }
    }
    if (gazetteerFiles.isEmpty()) {
        LOG.error("No Gazetteer files found.");
        System.exit(-1);
    }

    String altNamesPath = cmd.getOptionValue(ALTERNATE_NAMES_OPTION);
    File altNamesFile = altNamesPath != null ? new File(altNamesPath) : null;
    if (altNamesFile != null && !(altNamesFile.isFile() && altNamesFile.canRead())) {
        LOG.error("Unable to read alternate names file: {}", altNamesPath);
        System.exit(-1);
    }

    new IndexDirectoryBuilder(fullAncestry).buildIndex(idir, gazetteerFiles, altNamesFile);
}

From source file:IMAPService.java

public static void main(String[] args) {
    // Arguments//from www .j a  v a  2  s  .  c om
    String server = "";
    int port = -1;
    String login = "";
    String password = "";
    boolean deleteAfterDownload = false;
    boolean downloadAll = false;
    String[] foldersToDownload = null;

    // Set up apache cli
    Options options = new Options();

    Option S = new Option("S", true, "Server Name");
    S.setRequired(true);
    options.addOption(S);

    Option P = new Option("P", true, "Port Number");
    P.setRequired(true);
    options.addOption(P);

    Option l = new Option("l", true, "Login");
    l.setRequired(true);
    options.addOption(l);

    Option p = new Option("p", true, "Password if not on stdin");
    options.addOption(p);

    Option d = new Option("d", false, "Delete after downloading");
    d.setRequired(false);
    options.addOption(d);

    Option a = new Option("a", false, "Download from all folders");
    a.setRequired(false);
    options.addOption(a);

    Option f = new Option("f", true, "Download messages from specified folder");
    options.addOption(f);

    CommandLineParser clp = new DefaultParser();

    try {
        CommandLine cl = clp.parse(options, args);

        if (cl.hasOption("S"))
            server = cl.getOptionValue("S");

        if (cl.hasOption("P"))
            port = Integer.parseInt(cl.getOptionValue("P"));

        if (cl.hasOption("l"))
            login = cl.getOptionValue("l");

        if (cl.hasOption("p"))
            password = cl.getOptionValue("p");

        if (cl.hasOption("d"))
            deleteAfterDownload = true;

        if (cl.hasOption("a"))
            downloadAll = true;
        else if (cl.hasOption("f"))
            foldersToDownload = cl.getOptionValues("f");
        else {
            showArgMenu(options);
            return;
        }

    } catch (Exception e) {
        showArgMenu(options);
        return;
    }

    if (password.isEmpty()) {
        // Grab p/w of stdin if it's there
        Scanner sc = new Scanner(System.in);

        password = sc.nextLine();

        sc.close();
    }

    if (!server.isEmpty() && port != -1 && !login.isEmpty() && !password.isEmpty()
            && (downloadAll || foldersToDownload != null)) {
        //IMAPService imapService = new IMAPService("imap.gmail.com", 993);
        IMAPService imapService = new IMAPService(server, port);
        //imapService.login("kinglibingli@gmail.com", "kingli1bingli");
        imapService.login(login, password);
        imapService.buildMailbox();
        // Check if service should delete emails
        if (deleteAfterDownload)
            imapService.deleteEmailsAfterDownload();
        // Proceed with downloads
        if (downloadAll)
            imapService.downloadAllFolders();
        else {
            for (String folderNames : foldersToDownload) {
                imapService.downloadFoldersEmails(folderNames);
            }
        }

        imapService.logout();
    }

}

From source file:fr.inria.edelweiss.kgdqp.core.CentralizedInferrencing.java

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

    List<String> endpoints = new ArrayList<String>();
    String queryPath = null;//ww  w.j av  a2s  . com
    boolean rulesSelection = false;
    File rulesDir = null;
    File ontDir = null;

    /////////////////
    Graph graph = Graph.create();
    QueryProcess exec = QueryProcess.create(graph);

    Options options = new Options();
    Option helpOpt = new Option("h", "help", false, "print this message");
    //        Option queryOpt = new Option("q", "query", true, "specify the sparql query file");
    //        Option endpointOpt = new Option("e", "endpoint", true, "a federated sparql endpoint URL");
    Option versionOpt = new Option("v", "version", false, "print the version information and exit");
    Option rulesOpt = new Option("r", "rulesDir", true, "directory containing the inference rules");
    Option ontOpt = new Option("o", "ontologiesDir", true,
            "directory containing the ontologies for rules selection");
    //        Option locOpt = new Option("c", "centralized", false, "performs centralized inferences");
    Option dataOpt = new Option("l", "load", true, "data file or directory to be loaded");
    //        Option selOpt = new Option("s", "rulesSelection", false, "if set to true, only the applicable rules are run");
    //        options.addOption(queryOpt);
    //        options.addOption(endpointOpt);
    options.addOption(helpOpt);
    options.addOption(versionOpt);
    options.addOption(rulesOpt);
    options.addOption(ontOpt);
    //        options.addOption(selOpt);
    //        options.addOption(locOpt);
    options.addOption(dataOpt);

    String header = "Corese/KGRAM rule engine experiment command line interface";
    String footer = "\nPlease report any issue to alban.gaignard@cnrs.fr, olivier.corby@inria.fr";

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("kgdqp", header, options, footer, true);
        System.exit(0);
    }
    if (cmd.hasOption("o")) {
        rulesSelection = true;
        String ontDirPath = cmd.getOptionValue("o");
        ontDir = new File(ontDirPath);
        if (!ontDir.isDirectory()) {
            logger.warn(ontDirPath + " is not a valid directory path.");
            System.exit(0);
        }
    }
    if (!cmd.hasOption("r")) {
        logger.info("You must specify a path for inference rules directory !");
        System.exit(0);
    }

    if (cmd.hasOption("l")) {
        String[] dataPaths = cmd.getOptionValues("l");
        for (String path : dataPaths) {
            Load ld = Load.create(graph);
            ld.load(path);
            logger.info("Loaded " + path);
        }
    }

    if (cmd.hasOption("v")) {
        logger.info("version 3.0.4-SNAPSHOT");
        System.exit(0);
    }

    String rulesDirPath = cmd.getOptionValue("r");
    rulesDir = new File(rulesDirPath);
    if (!rulesDir.isDirectory()) {
        logger.warn(rulesDirPath + " is not a valid directory path.");
        System.exit(0);
    }

    // Local rules graph initialization
    Graph rulesG = Graph.create();
    Load ld = Load.create(rulesG);

    if (rulesSelection) {
        // Ontology loading
        if (ontDir.isDirectory()) {
            for (File o : ontDir.listFiles()) {
                logger.info("Loading " + o.getAbsolutePath());
                ld.load(o.getAbsolutePath());
            }
        }
    }

    // Rules loading
    if (rulesDir.isDirectory()) {
        for (File r : rulesDir.listFiles()) {
            logger.info("Loading " + r.getAbsolutePath());
            ld.load(r.getAbsolutePath());
        }
    }

    // Rule engine initialization
    RuleEngine ruleEngine = RuleEngine.create(graph);
    ruleEngine.set(exec);
    ruleEngine.setOptimize(true);
    ruleEngine.setConstructResult(true);
    ruleEngine.setTrace(true);

    StopWatch sw = new StopWatch();
    logger.info("Federated graph size : " + graph.size());
    logger.info("Rules graph size : " + rulesG.size());

    // Rule selection
    logger.info("Rules selection");
    QueryProcess localKgram = QueryProcess.create(rulesG);
    ArrayList<String> applicableRules = new ArrayList<String>();
    sw.start();
    String rulesSelQuery = "";
    if (rulesSelection) {
        rulesSelQuery = pertinentRulesQuery;
    } else {
        rulesSelQuery = allRulesQuery;
    }
    Mappings maps = localKgram.query(rulesSelQuery);
    logger.info("Rules selected in " + sw.getTime() + " ms");
    logger.info("Applicable rules : " + maps.size());

    // Selected rule loading
    for (Mapping map : maps) {
        IDatatype dt = (IDatatype) map.getValue("?res");
        String rule = dt.getLabel();
        //loading rule in the rule engine
        //            logger.info("Adding rule : ");
        //            System.out.println("-------");
        //            System.out.println(rule);
        //            System.out.println("");
        //            if (! rule.toLowerCase().contains("sameas")) {
        applicableRules.add(rule);
        ruleEngine.addRule(rule);
        //            }
    }

    // Rules application on distributed sparql endpoints
    logger.info("Rules application (" + applicableRules.size() + " rules)");
    ExecutorService threadPool = Executors.newCachedThreadPool();
    RuleEngineThread ruleThread = new RuleEngineThread(ruleEngine);
    sw.reset();
    sw.start();

    //        ruleEngine.process();
    threadPool.execute(ruleThread);
    threadPool.shutdown();

    //monitoring loop
    while (!threadPool.isTerminated()) {
        //            System.out.println("******************************");
        //            System.out.println(Util.jsonDqpCost(QueryProcessDQP.queryCounter, QueryProcessDQP.queryVolumeCounter, QueryProcessDQP.sourceCounter, QueryProcessDQP.sourceVolumeCounter));
        //            System.out.println("Rule engine running for " + sw.getTime() + " ms");
        //            System.out.println("Federated graph size : " + graph.size());
        System.out.println(sw.getTime() + " , " + graph.size());
        Thread.sleep(5000);
    }

    logger.info("Federated graph size : " + graph.size());
    //        logger.info(Util.jsonDqpCost(QueryProcessDQP.queryCounter, QueryProcessDQP.queryVolumeCounter, QueryProcessDQP.sourceCounter, QueryProcessDQP.sourceVolumeCounter));

    //        TripleFormat f = TripleFormat.create(graph, true);
    //        f.write("/tmp/gAll.ttl");

}