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:javadepchecker.Main.java

/**
 * @param args the command line arguments
 *///from www  .j av  a  2 s.  com
public static void main(String[] args) throws IOException {
    int exit = 0;
    try {
        CommandLineParser parser = new PosixParser();
        Options options = new Options();
        options.addOption("h", "help", false, "print help");
        options.addOption("i", "image", true, "image directory");
        options.addOption("v", "verbose", false, "print verbose output");
        CommandLine line = parser.parse(options, args);
        String[] files = line.getArgs();
        if (line.hasOption("h") || files.length == 0) {
            HelpFormatter h = new HelpFormatter();
            h.printHelp("java-dep-check [-i <image] <package.env>+", options);
        } else {
            image = line.getOptionValue("i", "");

            for (String arg : files) {
                if (line.hasOption('v')) {
                    System.out.println("Checking " + arg);
                }
                if (!checkPkg(new File(arg))) {
                    exit = 1;
                }
            }
        }
    } catch (ParseException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.exit(exit);
}

From source file:de.unileipzig.ub.scroller.Main.java

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

    Options options = new Options();
    // add t option
    options.addOption("h", "help", false, "display this help");

    // elasticsearch options
    options.addOption("t", "host", true, "elasticsearch hostname (default: 0.0.0.0)");
    options.addOption("p", "port", true, "transport port (that's NOT the http port, default: 9300)");
    options.addOption("c", "cluster", true, "cluster name (default: elasticsearch_mdma)");

    options.addOption("i", "index", true, "index to use");

    options.addOption("f", "filter", true, "filter(s) - e.g. meta.kind=title");
    options.addOption("j", "junctor", true, "values: and, or (default: and)");
    options.addOption("n", "notice-every", true, "show speed after every N items");

    options.addOption("v", "verbose", false, "be verbose");
    // options.addOption("z", "end-of-message", true, "sentinel to print to stdout, once the regular input finished (default: EOM)");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;/*from  w w w. jav a  2s.  com*/

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        logger.error(ex);
        System.exit(1);
    }

    // process options
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("scroller", options, true);
        System.exit(0);
    }

    String endOfMessage = "EOM";

    boolean verbose = false;
    if (cmd.hasOption("verbose")) {
        verbose = true;
    }

    if (!cmd.hasOption("i")) {
        System.err.println("error: no index specified");
        System.exit(1);
    }

    long noticeEvery = 10000;
    if (cmd.hasOption("n")) {
        noticeEvery = Long.parseLong(cmd.getOptionValue("n"));
    }

    // ES options
    String[] hosts = new String[] { "0.0.0.0" };
    int port = 9300;
    String clusterName = "elasticsearch_mdma";
    int bulkSize = 3000;

    if (cmd.hasOption("host")) {
        hosts = cmd.getOptionValues("host");
    }
    if (cmd.hasOption("port")) {
        port = Integer.parseInt(cmd.getOptionValue("port"));
    }
    if (cmd.hasOption("cluster")) {
        clusterName = cmd.getOptionValue("cluster");
    }

    // Index
    String indexName = cmd.getOptionValue("index");

    Map<String, String> filterMap = new HashMap<String, String>();
    if (cmd.hasOption("filter")) {
        try {
            filterMap = getMapForKeys(cmd.getOptionValues("filter"));
        } catch (ParseException pe) {
            System.err.println(pe);
            System.exit(1);
        }
    }

    Collection<HashMap> filterList = new ArrayList<HashMap>();
    if (cmd.hasOption("filter")) {
        try {
            filterList = getFilterList(cmd.getOptionValues("filter"));
        } catch (ParseException pe) {
            System.err.println(pe);
            System.exit(1);
        }
    }

    // ES Client
    final Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "elasticsearch_mdma")
            .put("client.transport.ping_timeout", "60s").build();
    final TransportClient client = new TransportClient(settings);
    for (String host : hosts) {
        client.addTransportAddress(new InetSocketTransportAddress(host, port));
    }

    // build the query
    String junctor = "and";
    if (cmd.hasOption("j")) {
        junctor = cmd.getOptionValue("j");
    }

    //        ArrayList<TermFilterBuilder> filters = new ArrayList<TermFilterBuilder>();
    //        if (filterMap.size() > 0) {
    //            for (Map.Entry<String, String> entry : filterMap.entrySet()) {
    //                filters.add(new TermFilterBuilder(entry.getKey(), entry.getValue()));
    //            }
    //        }

    ArrayList<TermFilterBuilder> filters = new ArrayList<TermFilterBuilder>();
    if (filterList.size() > 0) {
        for (HashMap map : filterList) {
            for (Object obj : map.entrySet()) {
                Map.Entry entry = (Map.Entry) obj;
                filters.add(new TermFilterBuilder(entry.getKey().toString(), entry.getValue().toString()));
            }
        }
    }

    FilterBuilder fb = null;
    if (junctor.equals("and")) {
        AndFilterBuilder afb = new AndFilterBuilder();
        for (TermFilterBuilder tfb : filters) {
            afb.add(tfb);
        }
        fb = afb;
    }

    if (junctor.equals("or")) {
        OrFilterBuilder ofb = new OrFilterBuilder();
        for (TermFilterBuilder tfb : filters) {
            ofb.add(tfb);
        }
        fb = ofb;
    }

    //        TermFilterBuilder tfb0 = new TermFilterBuilder("meta.kind", "title");
    //        TermFilterBuilder tfb1 = new TermFilterBuilder("meta.timestamp", "201112081240");
    //
    //        AndFilterBuilder afb0 = new AndFilterBuilder(tfb0, tfb1);

    QueryBuilder qb0 = null;
    if (filterMap.isEmpty()) {
        qb0 = matchAllQuery();
    } else {
        qb0 = filteredQuery(matchAllQuery(), fb);
    }

    // sorting
    // FieldSortBuilder sortBuilder = new FieldSortBuilder("meta.timestamp");
    // sortBuilder.order(SortOrder.DESC);

    // FilteredQueryBuilder fqb0 = filteredQuery(matchAllQuery(), tfb0);

    final CountResponse countResponse = client.prepareCount(indexName).setQuery(qb0).execute().actionGet();
    final long total = countResponse.getCount();

    SearchResponse scrollResp = client.prepareSearch(indexName).setSearchType(SearchType.SCAN)
            .setScroll(new TimeValue(60000)).setQuery(qb0)
            // .addSort(sortBuilder) // sort has no effect on scroll type (see: https://github.com/CPAN-API/cpan-api/issues/172)
            .setSize(1000) //1000 hits per shard will be returned for each scroll
            .execute().actionGet();

    //Scroll until no hits are returned

    System.err.println("[Scroller] query: " + qb0.toString());
    System.err.println("[Scroller] took: " + scrollResp.getTookInMillis() + "ms");
    System.err.println("[Scroller] docs found: " + total);

    long counter = 0;
    long start = System.currentTimeMillis();

    while (true) {
        scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(600000))
                .execute().actionGet();

        if (scrollResp.getHits().hits().length == 0) {
            break;
        }

        for (SearchHit hit : scrollResp.getHits()) {

            System.out.println(hit.sourceAsString());
            counter += 1;
            if (counter % noticeEvery == 0) {
                final double elapsed = (System.currentTimeMillis() - start) / 1000;
                final double speed = counter / elapsed;
                final long eta = (long) ((elapsed / counter) * (total - counter) * 1000);
                System.err.println(
                        counter + "/" + total + " records recvd @ speed " + String.format("%1$,.1f", speed)
                                + " r/s eta: " + DurationFormatUtils.formatDurationWords(eta, false, false));
            }
        }
    }
    System.out.close();
    // System.out.println(endOfMessage);
}

From source file:de.ipbhalle.metfrag.main.CommandLineTool.java

/**
 * @param args/*from  ww  w  .  ja  va  2s  .c o m*/
 * @throws Exception 
 */
public static void main(String[] args) {

    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();

    options.addOption("d", "database", true, "database: " + Databases.getString() + " (default: kegg)");
    options.addOption("l", "localdb", true,
            "use a local database together with a settings file for candidate search (default: not used) note: only usable if pubchem database is selected (-d)");
    options.addOption("a", "mzabs", true,
            "allowed absolute (Da) mass deviation of fragment and peak masses (default: 0.01)");
    options.addOption("p", "mzppm", true,
            "allowed relative (ppm) mass deviation of fragment and peak masses (default: 10)");
    options.addOption("s", "searchppm", true,
            "relative (ppm) mass deviation used for candidate search in given compound database (-d) (default: 10; not used by default if sdf database is selected (-d))\n");
    options.addOption("n", "exactmass", true,
            "neutral mass of measured compound used for candidate search in database (-d) (mandatory)");
    options.addOption("b", "biological", false,
            "only consider compounds including CHNOPS atoms (not used by default)");
    options.addOption("i", "databaseids", true,
            "database ids of compounds used for in silico fragmentation (separated by ,) (not used by default; not used if sdf database is selected (-d)) note: given ids must be valid ids of given database (-d)");
    options.addOption("t", "treedepth", true,
            "treedepth used for in silico fragmentation (default: 2) note: high values result in high computation time");
    options.addOption("M", "mode", true,
            "mode used for measured ms/ms spectrum:\n" + Modes.getString() + "(default: 3)");
    options.addOption("f", "formula", true,
            "molecular formula of measured compound used for candidate search in database (-d) (not used by default; not used if sdf database is selected (-d))");
    options.addOption("B", "breakrings", false,
            "allow splitting of aromatic rings of candidate structures during in silico fragmentation (not used by default)");
    options.addOption("F", "storefragments", false,
            "store in silico generated fragments of candidate molecules (not used by default)");
    options.addOption("R", "resultspath", true, "directory where result files are stored (default: /tmp)");
    options.addOption("L", "sdffile", true,
            "location of the local sdf file (mandatory if sdf database (-d) is selected)");
    options.addOption("h", "help", false, "print help");
    options.addOption("D", "spectrumfile", true,
            "file containing peak data (mandatory) note: commandline options overwrite parameters given in the spectrum data file");
    options.addOption("T", "threads", true,
            "number of threads used for fragment calculation (default: number of available cpu cores)");
    options.addOption("c", "chemspidertoken", true,
            "Token for ChemSpider database search (not used by default; only necessary (mandatory) if ChemSpider database (-d) is selected)");
    options.addOption("v", "verbose", false,
            "get more output information during the processing (not used by default)");
    options.addOption("S", "samplename", true,
            "name of the sample measured (mandatory) note: result files are stored with given value");
    options.addOption("P", "saveparameters", false, "save used parameters (not used by default)");
    options.addOption("e", "printexamplespecfile", false,
            "print an example spectrum data file (not used by default)");
    options.addOption("C", "charge", true,
            "charge used in combination with mode (-M):\n" + Charges.getString() + " (default: 1)");
    options.addOption("r", "range", true,
            "range of candidates that will be processed: N (first N), M-N (from M to N), M- (from M), -N (till N); if N is greater than the number of candidates it will be set accordingly");

    // parse the command line arguments
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException e1) {
        System.out.println(e1.getMessage());
        System.out.println("Error: Could not parse option parameters.");
        System.out.println("Use help -h (--help) for information.");
        System.exit(1);
    }

    if (line == null) {
        System.out.println("Error: Could not parse option parameters.");
        System.out.println("Use help -h (--help) for information.");
        System.exit(1);
    }
    if (checkInitialParamsPresent(line, options))
        System.exit(0);

    if (!checkSpectrumFile(line)) {
        System.out.println("Error: Option parameters are not set correctly.");
        System.out.println("Use help -h (--help) for information.");
        System.exit(1);
    }
    if (!parseSpectrumFile(spectrumfile)) {
        System.out.println("Error: Could not correctly parse the spectrum data file.");
        System.out.println("Use help -h (--help) for information.");
        System.exit(1);
    }

    int successfulSet = setParameters(line, options);
    if (successfulSet == 2)
        System.exit(0);
    if (successfulSet != 0) {
        System.out.println("Error: Option parameters are not set correctly.");
        System.out.println("Use help -h (--help) for information.");
        System.exit(1);
    }

    boolean successfulChecked = true;
    if (successfulSet == 0)
        successfulChecked = checkParameters();
    if (saveParametersIsSet) {
        try {
            BufferedWriter bwriter = new BufferedWriter(new FileWriter(new File(
                    resultspath + System.getProperty("file.separator") + "parameters_" + sampleName + ".txt")));
            bwriter.write(getParameters());
            bwriter.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    try {
        boolean isPositive = true;
        if (charge.getValue() == 2)
            isPositive = false;
        spec = new WrapperSpectrum(peaksString, mode.getValueWithOffset(), exactMass.getValue(), isPositive);
    } catch (Exception e) {
        System.out.println("Error: Could not parse spectrum correctly. Check the given peak list.");
        System.exit(1);
    }

    if (!successfulChecked) {
        System.out.println("Error: Option parameters are not set correctly.");
        System.out.println("Use help -h (--help) for information.");
        System.exit(1);
    }

    List<MetFragResult> results = null;
    String pathToStoreFrags = "";
    if (storeFragments)
        pathToStoreFrags = resultspath;
    //run metfrag when all checks were successful

    if (usesdf) {
        try {
            if (verbose) {
                System.out.println("start fragmenter with local database");
                System.out.println("using database " + database);
            }
            results = MetFrag.startConvenienceSDF(spec, mzabs.getValue(), mzppm.getValue(),
                    searchppm.getValue(), true, breakRings, treeDepth.getValue(), true, true, true, false,
                    Integer.MAX_VALUE, true, sdfFile, "", null, searchppmIsSet, pathToStoreFrags,
                    numberThreads.getValue(), verbose, sampleName, onlyBiologicalCompounds);
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
            System.out.println("Error: Could not perform in silico fragmentation step.");
            System.exit(1);
        }
    } else {
        try {
            if (verbose) {
                if (!localdbIsSet)
                    System.out.println("start fragmenter with web database");
                else
                    System.out.println("start fragmenter with local database");
                System.out.println("using database " + database);
            }
            results = MetFrag.startConvenience(database, databaseIDs, formula, exactMass.getValue(), spec,
                    useProxy, mzabs.getValue(), mzppm.getValue(), searchppm.getValue(), true, breakRings,
                    treeDepth.getValue(), true, false, true, false, startindex.getValue(), endindex.getValue(),
                    true, pathToStoreFrags, numberThreads.getValue(), chemSpiderToken, verbose, sampleName,
                    localdb, onlyBiologicalCompounds, dblink, dbuser, dbpass, uniquebyinchi);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error: " + e.getMessage());
            System.out.println("Error: Could not perform in silico fragmentation step.");
            System.exit(1);
        }
    }

    saveResults(results);

}

From source file:com.genentech.chemistry.openEye.apps.enumerate.SDFEnumerator.java

public static void main(String... args) throws IOException {
    Options options = new Options();
    Option opt = new Option("out", true, "output file oe-supported");
    opt.setRequired(true);//from w  w w  . j a  va  2s  .  co  m
    options.addOption(opt);

    opt = new Option("hydrogenExplicit", false, "Use explicit hydrogens");
    options.addOption(opt);

    opt = new Option("correctValences", false, "Correct valences after the enumeration");
    options.addOption(opt);

    opt = new Option("regenerate2D", false, "Regenerate 2D coordinates for the products");
    options.addOption(opt);

    opt = new Option("reactAllSites", false, "Generate a product for each match in a reagent.");
    options.addOption(opt);

    opt = new Option("randomFraction", true, "Only output a fraction of the products.");
    options.addOption(opt);

    opt = new Option("maxAtoms", true, "Only output products with <= maxAtoms.");
    options.addOption(opt);

    opt = new Option("notReacted", true,
            "Output file for reagents that didn't produce at leaste one output molecule, useful for debugging SMIRKS.");
    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 < 2) {
        exitWithHelp("Transformation and/or reagentFiles missing", options);
    }
    String smirks = args[0];
    if (new File(smirks).canRead())
        smirks = IOUtil.fileToString(smirks).trim();
    if (!smirks.contains(">>"))
        smirks = scaffoldToSmirks(smirks);
    String[] reagentSmiOrFiles = Arrays.copyOfRange(args, 1, args.length);

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

    String outFile = cmd.getOptionValue("out");
    OELibraryGen lg = new OELibraryGen();
    lg.Init(smirks);
    if (!lg.IsValid())
        exitWithHelp("Invalid Transform: " + smirks, options);

    lg.SetExplicitHydrogens(cmd.hasOption("hydrogenExplicit"));
    lg.SetValenceCorrection(cmd.hasOption("correctValences"));
    lg.SetRemoveUnmappedFragments(true);

    boolean regenerate2D = cmd.hasOption("regenerate2D");
    boolean reactAllSites = cmd.hasOption("reactAllSites");
    String unreactedFile = null;
    if (cmd.hasOption("notReacted")) {
        unreactedFile = cmd.getOptionValue("notReacted");
    }

    double randomFract = 2;
    if (cmd.hasOption("randomFraction"))
        randomFract = Double.parseDouble(cmd.getOptionValue("randomFraction"));

    int maxAtoms = 0;
    if (cmd.hasOption("maxAtoms"))
        maxAtoms = Integer.parseInt(cmd.getOptionValue("maxAtoms"));

    SDFEnumerator en = new SDFEnumerator(lg, reactAllSites, reagentSmiOrFiles);
    en.generateLibrary(outFile, maxAtoms, randomFract, regenerate2D, unreactedFile);
    en.delete();
}

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

/**
 * Command-line interface to Arc2Warc.//from   w  ww . ja  v a 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."));
    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;
    for (int i = 0; i < cmdlineOptions.length; i++) {
        switch (cmdlineOptions[i].getId()) {
        case 'h':
            usage(formatter, options, 0);
            break;

        case 'f':
            force = true;
            break;

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

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

From source file:net.bobah.mail.Dupes.java

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

    final CommandLineParser parser = new PosixParser();
    final Options options = new Options()
            .addOption("j", "threads", true, "number of parallel threads to use for analyzing")
            .addOption("hash", true,
                    "hash function to use, possible values: " + Arrays.toString(Hashes.values()))
            .addOption("dir", true, "add directory to search");
    final CommandLine cmdline = parser.parse(options, args);

    final int threads = Integer.valueOf(
            cmdline.getOptionValue("threads", String.valueOf(Runtime.getRuntime().availableProcessors())));
    final HashFunction hash = Hashes.valueOf(cmdline.getOptionValue("hash", "adler32")).hashfunc;
    final File[] dirs = Collections2
            .transform(Arrays.asList(cmdline.getOptionValues("dir")), new Function<String, File>() {
                @Override//from  w w w .ja va 2  s. co m
                public File apply(String from) {
                    return new File(from);
                }
            }).toArray(new File[] {});

    log.info("hash: {}, threads: {}, dirs: {} in total", hash, threads, dirs.length);
    try {
        new Dupes(threads, hash, dirs).run();
    } finally {
        Utils.shutdownLogger();
    }
}

From source file:com.ict.dtube.tools.command.MQAdminStartup.java

public static void main(String[] args) {
    System.setProperty(RemotingCommand.RemotingVersionKey, Integer.toString(MQVersion.CurrentVersion));

    try {/*from  www . j ava 2 s.c  o  m*/
        initLogback();
        switch (args.length) {
        case 0:
            printHelp();
            break;
        case 2:
            if (args[0].equals("help")) {
                SubCommand cmd = findSubCommand(args[1]);
                if (cmd != null) {
                    Options options = ServerUtil.buildCommandlineOptions(new Options());
                    options = cmd.buildCommandlineOptions(options);
                    if (options != null) {
                        ServerUtil.printCommandLineHelp("mqadmin " + cmd.commandName(), options);
                    }
                } else {
                    System.out.println("The sub command \'" + args[1] + "\' not exist.");
                }
                break;
            }
        case 1:
        default:
            SubCommand cmd = findSubCommand(args[0]);
            if (cmd != null) {
                // mainargs?args?
                String[] subargs = parseSubArgs(args);

                // ?
                Options options = ServerUtil.buildCommandlineOptions(new Options());
                final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs,
                        cmd.buildCommandlineOptions(options), new PosixParser());
                if (null == commandLine) {
                    System.exit(-1);
                    return;
                }

                if (commandLine.hasOption('n')) {
                    String namesrvAddr = commandLine.getOptionValue('n');
                    System.setProperty(MixAll.NAMESRV_ADDR_PROPERTY, namesrvAddr);
                }

                cmd.execute(commandLine, options);
            } else {
                System.out.println("The sub command \'" + args[0] + "\' not exist.");
            }
            break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:eqtlmappingpipeline.util.ModuleEqtWestraReplication.java

/**
 * @param args the command line arguments
 *//*from w ww  .  j  a  v a 2s.c om*/
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');
    String[] replicationHeader = replicationQtlReader.readNext();
    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;
            }

            Alleles variantAlleles = variant.getVariantAlleles();
            String[] replicationAllelesString = StringUtils.split(replicationLine[REPLICATION_ALLELES_COL],
                    '/');

            Alleles replicationAlleles = Alleles.createBasedOnString(replicationAllelesString[0],
                    replicationAllelesString[1]);
            Allele assessedAlleleReplication = Allele.create(replicationLine[REPLICATION_ALLELE_ASSESSED_COL]);

            boolean isAmbigous = replicationAlleles.isAtOrGcSnp();

            if (!variantAlleles.equals(replicationAlleles)) {
                if (variantAlleles.equals(replicationAlleles.getComplement())) {
                    assessedAlleleReplication = assessedAlleleReplication.getComplement();
                } else {
                    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]),
                    assessedAlleleReplication.getAlleleAsString(), replicationLine, isAmbigous);
            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[15 + EXTRA_COL_FROM_REPLICATION.length];
    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";
    outputLine[c++] = "replicationAmbigous";
    for (int i = 0; i < EXTRA_COL_FROM_REPLICATION.length; ++i) {
        outputLine[c++] = replicationHeader[EXTRA_COL_FROM_REPLICATION[i]];
    }
    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;
                //replicationZCorrected = alleleAssessed.equals(replicationAlleleAssessed) || alleleAssessed.equals(String.valueOf(Utils.getComplementNucleotide(replicationAlleleAssessed.charAt(0)))) ? 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);
        outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(bestMatch.isIsAmbigous());

        if (bestMatch == null) {
            for (int i = 0; i < EXTRA_COL_FROM_REPLICATION.length; ++i) {
                outputLine[c++] = "NA";
            }
        } else {
            for (int i = 0; i < EXTRA_COL_FROM_REPLICATION.length; ++i) {
                outputLine[c++] = bestMatch.getLine()[EXTRA_COL_FROM_REPLICATION[i]];
            }
        }

        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.cws.esolutions.security.main.PasswordUtility.java

public static void main(final String[] args) {
    final String methodName = PasswordUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {// w w w .j a  v  a 2  s . c om
        DEBUGGER.debug("Value: {}", methodName);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(PasswordUtility.CNAME, options, true);

        System.exit(1);
    }

    BufferedReader bReader = null;
    BufferedWriter bWriter = null;

    try {
        // load service config first !!
        SecurityServiceInitializer.initializeService(PasswordUtility.SEC_CONFIG, PasswordUtility.LOG_CONFIG,
                false);

        if (DEBUG) {
            DEBUGGER.debug("Options options: {}", options);

            for (String arg : args) {
                DEBUGGER.debug("Value: {}", arg);
            }
        }

        CommandLineParser parser = new PosixParser();
        CommandLine commandLine = parser.parse(options, args);

        if (DEBUG) {
            DEBUGGER.debug("CommandLineParser parser: {}", parser);
            DEBUGGER.debug("CommandLine commandLine: {}", commandLine);
            DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions());
            DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList());
        }

        final SecurityConfigurationData secConfigData = PasswordUtility.svcBean.getConfigData();
        final SecurityConfig secConfig = secConfigData.getSecurityConfig();
        final PasswordRepositoryConfig repoConfig = secConfigData.getPasswordRepo();
        final SystemConfig systemConfig = secConfigData.getSystemConfig();

        if (DEBUG) {
            DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData);
            DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig);
            DEBUGGER.debug("RepositoryConfig secConfig: {}", repoConfig);
            DEBUGGER.debug("SystemConfig systemConfig: {}", systemConfig);
        }

        if (commandLine.hasOption("encrypt")) {
            if ((StringUtils.isBlank(repoConfig.getPasswordFile()))
                    || (StringUtils.isBlank(repoConfig.getSaltFile()))) {
                System.err.println("The password/salt files are not configured. Entries will not be stored!");
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            final String entryName = commandLine.getOptionValue("entry");
            final String username = commandLine.getOptionValue("username");
            final String password = commandLine.getOptionValue("password");
            final String salt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength());

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
                DEBUGGER.debug("String password: {}", password);
                DEBUGGER.debug("String salt: {}", salt);
            }

            final String encodedSalt = PasswordUtils.base64Encode(salt);
            final String encodedUserName = PasswordUtils.base64Encode(username);
            final String encryptedPassword = PasswordUtils.encryptText(password, salt,
                    secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                    secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                    systemConfig.getEncoding());
            final String encodedPassword = PasswordUtils.base64Encode(encryptedPassword);

            if (DEBUG) {
                DEBUGGER.debug("String encodedSalt: {}", encodedSalt);
                DEBUGGER.debug("String encodedUserName: {}", encodedUserName);
                DEBUGGER.debug("String encodedPassword: {}", encodedPassword);
            }

            if (commandLine.hasOption("store")) {
                try {
                    new File(passwordFile.getParent()).mkdirs();
                    new File(saltFile.getParent()).mkdirs();

                    boolean saltFileExists = (saltFile.exists()) ? true : saltFile.createNewFile();

                    if (DEBUG) {
                        DEBUGGER.debug("saltFileExists: {}", saltFileExists);
                    }

                    // write the salt out first
                    if (!(saltFileExists)) {
                        throw new IOException("Unable to create salt file");
                    }

                    boolean passwordFileExists = (passwordFile.exists()) ? true : passwordFile.createNewFile();

                    if (!(passwordFileExists)) {
                        throw new IOException("Unable to create password file");
                    }

                    if (commandLine.hasOption("replace")) {
                        File[] files = new File[] { saltFile, passwordFile };

                        if (DEBUG) {
                            DEBUGGER.debug("File[] files: {}", (Object) files);
                        }

                        for (File file : files) {
                            if (DEBUG) {
                                DEBUGGER.debug("File: {}", file);
                            }

                            String currentLine = null;
                            File tmpFile = new File(FileUtils.getTempDirectory() + "/" + "tmpFile");

                            if (DEBUG) {
                                DEBUGGER.debug("File tmpFile: {}", tmpFile);
                            }

                            bReader = new BufferedReader(new FileReader(file));
                            bWriter = new BufferedWriter(new FileWriter(tmpFile));

                            while ((currentLine = bReader.readLine()) != null) {
                                if (!(StringUtils.equals(currentLine.trim().split(",")[0], entryName))) {
                                    bWriter.write(currentLine + System.getProperty("line.separator"));
                                    bWriter.flush();
                                }
                            }

                            bWriter.close();

                            FileUtils.deleteQuietly(file);
                            FileUtils.copyFile(tmpFile, file);
                            FileUtils.deleteQuietly(tmpFile);
                        }
                    }

                    FileUtils.writeStringToFile(saltFile, entryName + "," + encodedUserName + "," + encodedSalt
                            + System.getProperty("line.separator"), true);
                    FileUtils.writeStringToFile(passwordFile, entryName + "," + encodedUserName + ","
                            + encodedPassword + System.getProperty("line.separator"), true);
                } catch (IOException iox) {
                    ERROR_RECORDER.error(iox.getMessage(), iox);
                }
            }

            System.out.println("Entry Name " + entryName + " stored.");
        }

        if (commandLine.hasOption("decrypt")) {
            String saltEntryName = null;
            String saltEntryValue = null;
            String decryptedPassword = null;
            String passwordEntryName = null;

            if ((StringUtils.isEmpty(commandLine.getOptionValue("entry"))
                    && (StringUtils.isEmpty(commandLine.getOptionValue("username"))))) {
                throw new ParseException("No entry or username was provided to decrypt.");
            }

            if (StringUtils.isEmpty(commandLine.getOptionValue("username"))) {
                throw new ParseException("no entry provided to decrypt");
            }

            String entryName = commandLine.getOptionValue("entry");
            String username = commandLine.getOptionValue("username");

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            if ((!(saltFile.canRead())) || (!(passwordFile.canRead()))) {
                throw new IOException(
                        "Unable to read configured password/salt file. Please check configuration and/or permissions.");
            }

            for (String lineEntry : FileUtils.readLines(saltFile, systemConfig.getEncoding())) {
                saltEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String saltEntryName: {}", saltEntryName);
                }

                if (StringUtils.equals(saltEntryName, entryName)) {
                    saltEntryValue = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    break;
                }
            }

            if (StringUtils.isEmpty(saltEntryValue)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            for (String lineEntry : FileUtils.readLines(passwordFile, systemConfig.getEncoding())) {
                passwordEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String passwordEntryName: {}", passwordEntryName);
                }

                if (StringUtils.equals(passwordEntryName, saltEntryName)) {
                    String decodedPassword = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    decryptedPassword = PasswordUtils.decryptText(decodedPassword, saltEntryValue,
                            secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                            secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                            systemConfig.getEncoding());

                    break;
                }
            }

            if (StringUtils.isEmpty(decryptedPassword)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            System.out.println(decryptedPassword);
        } else if (commandLine.hasOption("encode")) {
            System.out.println(PasswordUtils.base64Encode((String) commandLine.getArgList().get(0)));
        } else if (commandLine.hasOption("decode")) {
            System.out.println(PasswordUtils.base64Decode((String) commandLine.getArgList().get(0)));
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        System.err.println("An error occurred during processing: " + iox.getMessage());
        System.exit(1);
    } catch (ParseException px) {
        ERROR_RECORDER.error(px.getMessage(), px);

        System.err.println("An error occurred during processing: " + px.getMessage());
        System.exit(1);
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        System.err.println("An error occurred during processing: " + sx.getMessage());
        System.exit(1);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
        System.exit(1);
    } finally {
        try {
            if (bReader != null) {
                bReader.close();
            }

            if (bWriter != null) {
                bReader.close();
            }
        } catch (IOException iox) {
        }
    }

    System.exit(0);
}

From source file:eu.scape_project.droid_identify.DroidIdentification.java

public static void main(String[] args)
        throws ParseException, IOException, InterruptedException, ClassNotFoundException {
    CommandLineParser cmdParser = new PosixParser();

    DroidCliOptions droidCliOpts = new DroidCliOptions();
    appConfig = new DroidCliConfig();

    CommandLine cmd = cmdParser.parse(droidCliOpts.options, args);
    if ((args.length == 0) || (cmd.hasOption(droidCliOpts.HELP_OPT))) {
        droidCliOpts.exit("Help", 0);
    } else {//from  w  w w  .  ja  va2  s.  co m
        droidCliOpts.initOptions(cmd, appConfig);
        DroidIdentification tc = new DroidIdentification();
        if (appConfig.isLocal()) {
            tc.startApplication();
        } else {
            tc.startHadoopJob();
        }
    }
}