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

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

Introduction

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

Prototype

public Option[] getOptions() 

Source Link

Document

Returns an array of the processed Option s.

Usage

From source file:lcmc.ArgumentParser.java

public void parseClusterOptionsAndCreateClusterButton(final CommandLine cmd) throws ParseException {
    String clusterName = null;/*from w  ww  .  j  av  a  2  s. co  m*/
    List<HostOptions> hostsOptions = null;
    final Map<String, List<HostOptions>> clusters = new LinkedHashMap<String, List<HostOptions>>();
    for (final Option option : cmd.getOptions()) {
        final String op = option.getLongOpt();
        if (CLUSTER_OP.equals(op)) {
            clusterName = option.getValue();
            if (clusterName == null) {
                throw new ParseException("could not parse " + CLUSTER_OP + " option");

            }
            clusters.put(clusterName, new ArrayList<HostOptions>());
        } else if (HOST_OP.equals(op)) {
            final String[] hostNames = option.getValues();
            if (clusterName == null) {
                clusterName = "default";
                clusters.put(clusterName, new ArrayList<HostOptions>());
            }
            if (hostNames == null) {
                throw new ParseException("could not parse " + HOST_OP + " option");
            }
            hostsOptions = new ArrayList<HostOptions>();
            for (final String hostNameEntered : hostNames) {
                final String hostName;
                String port = null;
                if (hostNameEntered.indexOf(':') > 0) {
                    final String[] he = hostNameEntered.split(":");
                    hostName = he[0];
                    port = he[1];
                    if (port != null && port.isEmpty() || !lcmc.common.domain.util.Tools.isNumber(port)) {
                        throw new ParseException("could not parse " + HOST_OP + " option");
                    }
                } else {
                    hostName = hostNameEntered;
                }
                final HostOptions ho = new HostOptions(hostName);
                if (port != null) {
                    ho.setPort(port);
                }
                hostsOptions.add(ho);
                clusters.get(clusterName).add(ho);
            }
        } else if (SUDO_OP.equals(op)) {
            if (hostsOptions == null) {
                throw new ParseException(SUDO_OP + " must be defined after " + HOST_OP);
            }
            for (final HostOptions ho : hostsOptions) {
                ho.setUseSudo(true);
            }
        } else if (USER_OP.equals(op)) {
            if (hostsOptions == null) {
                throw new ParseException(USER_OP + " must be defined after " + HOST_OP);
            }
            final String userName = option.getValue();
            if (userName == null) {
                throw new ParseException("could not parse " + USER_OP + " option");
            }
            for (final HostOptions ho : hostsOptions) {
                ho.setLoginUser(userName);
            }
        } else if (PORT_OP.equals(op)) {
            if (hostsOptions == null) {
                throw new ParseException(PORT_OP + " must be defined after " + HOST_OP);
            }
            final String port = option.getValue();
            if (port == null) {
                throw new ParseException("could not parse " + PORT_OP + " option");
            }
            for (final HostOptions ho : hostsOptions) {
                ho.setPort(port);
            }
        } else if (PCMKTEST_OP.equals(op)) {
            final String index = option.getValue();
            if (index != null && !index.isEmpty()) {
                application.setAutoTest(new Test(StartTests.Type.PCMK, index.charAt(0)));
            }
        } else if (DRBDTEST_OP.equals(op)) {
            final String index = option.getValue();
            if (index != null && !index.isEmpty()) {
                application.setAutoTest(new Test(StartTests.Type.DRBD, index.charAt(0)));
            }
        } else if (VMTEST_OP.equals(op)) {
            final String index = option.getValue();
            if (index != null && !index.isEmpty()) {
                application.setAutoTest(new Test(StartTests.Type.VM, index.charAt(0)));
            }
        } else if (GUITEST_OP.equals(op)) {
            final String index = option.getValue();
            if (index != null && !index.isEmpty()) {
                application.setAutoTest(new Test(StartTests.Type.GUI, index.charAt(0)));
            }
        }
    }
    for (final Map.Entry<String, List<HostOptions>> clusterEntry : clusters.entrySet()) {
        final List<HostOptions> hostOptions = clusterEntry.getValue();
        if (hostOptions.size() < 1 || (hostOptions.size() == 1 && !application.isOneHostCluster())) {
            throw new ParseException("not enough hosts for cluster: " + clusterEntry.getKey());
        }
    }
    final String failedHost = setUserConfigFromOptions(clusters);
    if (failedHost != null) {
        LOG.appWarning("parseClusterOptions: could not resolve host \"" + failedHost + "\" skipping");
    }
}

From source file:mitm.application.djigzo.tools.Monitor.java

private void handleCommandline(String[] args)
        throws IOException, ParseException, WSProxyFactoryException, WebServiceCheckedException {
    CommandLineParser parser = new BasicParser();

    Options options = createCommandLineOptions();

    HelpFormatter formatter = new HelpFormatter();

    CommandLine commandLine;

    try {//w w  w . j av a 2s . c  om
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        formatter.printHelp(COMMAND_NAME, options, true);

        throw e;
    }

    initLogging(commandLine.hasOption(loggingOption.getOpt()));

    user = userOption.getValue();

    password = passwordOption.getValue();

    repository = mpaSizeOption.getValue();

    if (commandLine.getOptions().length == 0) {
        formatter.printHelp(COMMAND_NAME, options, true);

        System.exit(1);

        return;
    }

    if (commandLine.getOptions().length == 0 || commandLine.hasOption(helpOption.getOpt())) {
        formatter.printHelp(COMMAND_NAME, options, true);

        return;
    }

    if (commandLine.hasOption(passwordPromptOption.getOpt())) {
        System.err.println("Please enter password: ");
        password = new jline.ConsoleReader().readLine(new Character('*'));
    }

    if (commandLine.hasOption(mpaSizeOption.getOpt())) {
        retrieveMPAQueueSize();
    }

    if (commandLine.hasOption(crlStoreSizeOption.getOpt())) {
        retrieveCRLStoreSize();
    }

    if (commandLine.hasOption(runningOption.getOpt())) {
        checkRunning();
    }

    if (commandLine.hasOption(mtaSizeOption.getOpt())) {
        retrieveMTAQueueSize();
    }

    if (commandLine.hasOption(certStoreSizeOption.getOpt())) {
        retrieveCertStoreSize();
    }

    if (commandLine.hasOption(certRequestStoreSizeOption.getOpt())) {
        retrieveCertRequestStoreSize();
    }

    if (commandLine.hasOption(smsSizeOption.getOpt())) {
        retrieveSMSSize();
    }

    if (commandLine.hasOption(userSizeOption.getOpt())) {
        retrieveUsersSize();
    }
}

From source file:ambit2.data.qmrf.QMRFObject.java

protected void setOptions(CommandLine line) {
    String url;/*from  w  w w.ja va 2 s.  c om*/
    //System.out.println("CommandLine line");
    Option[] o = line.getOptions();
    if (o != null)
        for (int i = 0; i < o.length; i++)
            System.out.println(o[i]);
    if (line.hasOption("d")) {
        url = line.getOptionValue("d");
        try {
            dtdSchema = url;
        } catch (Exception x) {
            logger.error(x);
            dtdSchema = "http://ambit2.acad.bg/qmrf/qmrf.dtd";
            logger.info("Will be using DTD schema at " + dtdSchema);
        }
    }
    if (line.hasOption("t")) {
        setTtfFontUrl(line.getOptionValue("t"));
    }
    if (line.hasOption("r")) {
        setAttachmentReadOnly(true);
    } else
        setAttachmentReadOnly(false);

    if (line.hasOption("u")) {
        adminUser = "admin".equals(line.getOptionValue("u"));
    }
    if (line.hasOption("c")) {
        setSaveSelectedOnly(true);
    }
    if (line.hasOption("e")) {
        url = line.getOptionValue("e");

        try {
            System.out.println("reading catalogs from URL " + url);
            external_catalogs.read(new InputSource(new InputStreamReader(new URL(url).openStream(), "UTF-8")));

        } catch (Exception x) {
            System.err.println(x.getMessage());
            readDefaultCatalogs(external_catalogs);
        } finally {

        }

    }
    if (external_catalogs.size() == 0)
        readDefaultCatalogs(external_catalogs);

}

From source file:ambit.data.qmrf.QMRFObject.java

protected void setOptions(CommandLine line) {
    String url;//  ww w .  ja  va2s  .c  o  m
    //System.out.println("CommandLine line");
    Option[] o = line.getOptions();
    if (o != null)
        for (int i = 0; i < o.length; i++)
            System.out.println(o[i]);
    if (line.hasOption("d")) {
        url = line.getOptionValue("d");
        try {
            dtdSchema = url;
        } catch (Exception x) {
            logger.error(x);
            dtdSchema = "http://ambit.acad.bg/qmrf/qmrf.dtd";
            logger.info("Will be using DTD schema at " + dtdSchema);
        }
    }
    if (line.hasOption("t")) {
        setTtfFontUrl(line.getOptionValue("t"));
    }
    if (line.hasOption("r")) {
        setAttachmentReadOnly(true);
    } else
        setAttachmentReadOnly(false);

    if (line.hasOption("u")) {
        adminUser = "admin".equals(line.getOptionValue("u"));
    }
    if (line.hasOption("c")) {
        setSaveSelectedOnly(true);
    }
    if (line.hasOption("e")) {
        url = line.getOptionValue("e");

        try {
            System.out.println("reading catalogs from URL " + url);
            external_catalogs.read(new InputSource(new InputStreamReader(new URL(url).openStream(), "UTF-8")));

        } catch (Exception x) {
            System.err.println(x.getMessage());
            readDefaultCatalogs(external_catalogs);
        } finally {

        }

    }
    if (external_catalogs.size() == 0)
        readDefaultCatalogs(external_catalogs);

}

From source file:com.netflix.subtitles.cli.TtmlConverterCmdLineParser.java

/**
 * Parses command line.//from  w w  w .  ja v  a 2  s . c o m
 *
 * @param args cli arguments
 * @return parsed parameters object
 * @throws ParseException
 */
public TtmlConverterCmdLineParams parse(String[] args) throws ParseException {
    TtmlConverterCmdLineParams params = new TtmlConverterCmdLineParams();

    CommandLineParser parser = new DefaultParser();
    CommandLine line;
    try {
        line = parser.parse(options, args);
    } catch (org.apache.commons.cli.ParseException e) {
        throw new ParseException(e);
    }

    // help
    if (line.hasOption(help.getOpt())) {
        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp("ttml2stl", options);

        return null;
    }

    // outputFile
    if (line.hasOption(out.getOpt())) {
        params.setOutputFile(line.getOptionValue(out.getOpt()));
    } else {
        throw new ParseException("Output file option must be provided.");
    }

    // frameRate
    if (line.hasOption(frameRate.getOpt())) {
        params.setFrameRate(parseFrameRate(line.getOptionValue(frameRate.getOpt())));
    }

    // ttml
    params.getTtmlOptions().addAll(Stream.of(line.getOptions()).filter((o) -> o.equals(ttml)).map((o) -> {
        TtmlOption ttmlOption = new TtmlOption();

        try {
            ttmlOption.setFileName(o.getValue(0));
            ttmlOption.setOffsetMS(parseTtmlParameter(o, 1, "offsetMS"));
            ttmlOption.setStartMS(parseTtmlParameter(o, 2, "startMS"));
            ttmlOption.setEndMS(parseTtmlParameter(o, 3, "endMS"));
        } catch (IndexOutOfBoundsException e) {
            //It is error only if don't have file name
            //For required file it may not be thrown. We will check it later.
        }

        if (ttmlOption.getFileName() == null) {
            throw new ParseException("--ttml parameter must have at least <file> attribute defined.");
        }

        return ttmlOption;
    }).collect(Collectors.toCollection(ArrayList::new)));
    if (params.getTtmlOptions().isEmpty()) {
        throw new ParseException("At least one input TTML file must be provided.");
    }

    return params;
}

From source file:com.planet57.gshell.util.cli2.CliProcessor.java

public void process(final String... args) throws Exception {
    checkNotNull(args);// ww  w.j av a  2 s .  c  o  m
    if (log.isTraceEnabled()) {
        log.trace("Processing: {}", Arrays.toString(args));
    }

    CliParser parser = flavor.create();
    log.trace("Parser: {}", parser);

    CommandLine cl;
    try {
        cl = parser.parse(createOptions(), args, stopAtNonOption);
    } catch (UnrecognizedOptionException e) {
        throw new ProcessingException(messages.UNDEFINED_OPTION(e.getOption()));
    } catch (MissingArgumentException e) {
        OptionDescriptor desc = ((Opt) e.getOption()).getDescriptor();
        throw new ProcessingException(messages.MISSING_OPERAND(desc.getSyntax(), desc.getToken()));
    } catch (ParseException e) {
        throw new ProcessingException(e);
    }

    Set<CliDescriptor> present = new HashSet<>();
    boolean override = false;

    if (log.isTraceEnabled()) {
        log.trace("Parsed options: {}", Arrays.toString(cl.getOptions()));
    }

    for (Object tmp : cl.getOptions()) {
        Opt opt = (Opt) tmp;
        log.trace("Processing option: {}", opt);

        OptionDescriptor desc = opt.getDescriptor();
        present.add(desc);

        // Track the override, this is used to handle when --help present, but a required arg/opt is missing
        if (!override) {
            override = desc.getOverride();
        }

        Handler handler = Handlers.create(desc);
        String[] values = opt.getValues();

        if (values == null || values.length == 0) {
            // Set the value
            handler.handle(opt.getValue());
        } else {
            // Set the values
            for (String value : values) {
                handler.handle(value);
            }
        }
    }

    log.trace("Remaining arguments: {}", cl.getArgList());

    int i = 0;
    for (final String arg : cl.getArgs()) {
        log.trace("Processing argument: {}", arg);

        // Check if we allow an argument or we have overflowed
        if (i >= argumentDescriptors.size()) {
            throw new ProcessingException(argumentDescriptors.size() == 0 ? messages.NO_ARGUMENT_ALLOWED(arg)
                    : messages.TOO_MANY_ARGUMENTS(arg));
        }

        ArgumentDescriptor desc = argumentDescriptors.get(i);
        present.add(desc);

        // For single-valued args, increment the argument index, else let the multivalued handler consume it
        if (!desc.isMultiValued()) {
            i++;
        }

        // Set the value
        Handler handler = Handlers.create(desc);
        handler.handle(arg);
    }

    // Check for any required arguments which were not present
    if (!override) {
        try {
            parser.ensureRequiredOptionsPresent();
        } catch (MissingOptionException e) {
            throw new ProcessingException(messages.REQUIRED_OPTION_MISSING(e.getMissingOptions()));
        }

        for (ArgumentDescriptor arg : argumentDescriptors) {
            if (arg.isRequired() && !present.contains(arg)) {
                throw new ProcessingException(messages.REQUIRED_ARGUMENT_MISSING(arg.getToken()));
            }
        }
    }

    // TODO: Handle setting defaults
}

From source file:edu.buffalo.fusim.Fusim.java

public void run(String[] args) throws IOException, InterruptedException {
    buildOptions();/*from   w w w  . j a  va2s.co m*/

    CommandLineParser clParser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = clParser.parse(options, args);
    } catch (ParseException e) {
        printHelpAndExit(options, e.getMessage());
    }

    if (cmd.hasOption("v")) {
        printVersionAndExit();
    }

    if (cmd.hasOption("h") || cmd.getOptions().length == 0) {
        printHelpAndExit(options);
    }

    if (cmd.hasOption("z")) {
        if (!cmd.hasOption("i")) {
            printHelpAndExit(options, "Please specify a path to a GTF/GFF file for conversion with option -i");
        }
        if (!cmd.hasOption("o")) {
            printHelpAndExit(options, "Please specify an output filename with option -O");
        }

        File outFile = new File(cmd.getOptionValue("o"));
        File gtfFile = new File(cmd.getOptionValue("i"));
        if (!gtfFile.canRead()) {
            printHelpAndExit(options, "Can't read input GTF file");
        }

        GTF2RefFlat gtf2Flat = new GTF2RefFlat();

        gtf2Flat.convert(gtfFile, outFile);
        System.exit(0);
    }

    if (!cmd.hasOption("g")) {
        printHelpAndExit(options, "Please specify a path to a gene model file with option -g");
    }

    File geneModelFile = new File(cmd.getOptionValue("g"));
    if (!geneModelFile.canRead()) {
        printHelpAndExit(options, "Can't read Gene Model file");
    }

    PrintWriter textOutput = null;
    if (cmd.hasOption("t")) {
        if ("-".equals(cmd.getOptionValue("t"))) {
            textOutput = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8"));
        } else {
            textOutput = new PrintWriter(
                    new OutputStreamWriter(new FileOutputStream(cmd.getOptionValue("t")), "UTF-8"));
        }
    }

    PrintWriter fastaOutput = null;
    if (cmd.hasOption("f")) {
        if ("-".equals(cmd.getOptionValue("f"))) {
            fastaOutput = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8"));
        } else {
            fastaOutput = new PrintWriter(
                    new OutputStreamWriter(new FileOutputStream(cmd.getOptionValue("f")), "UTF-8"));
        }
    }

    // Default to TXT output
    if (fastaOutput == null && textOutput == null) {
        textOutput = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8"));
    }

    if (cmd.hasOption("f") && !cmd.hasOption("r")) {
        printHelpAndExit(options,
                "You must provide an indexed (.fai) genome reference file for FASTA output using option \"-r\".");
    }

    File referenceFile = null;
    if (cmd.hasOption("r")) {
        referenceFile = new File(cmd.getOptionValue("r"));
    }
    if (cmd.hasOption("f") && !referenceFile.canRead()) {
        printHelpAndExit(options, "Please provide a valid reference file in fasta format");
    }
    if (cmd.hasOption("f")) {
        File referenceIndexFile = new File(referenceFile.getAbsolutePath() + ".fai");
        if (!referenceIndexFile.canRead()) {
            fatalError("Missing index file. Please index your fasta file with: samtools faidx my_genome.fa");
        }
    }

    int nFusions = 0;
    if (cmd.hasOption("n")) {
        try {
            nFusions = Integer.parseInt(cmd.getOptionValue("n"));
        } catch (NumberFormatException e) {
            printHelpAndExit(options, "Number of fusions (-n) must be a number");
        }
    }

    int nReadThrough = 0;
    if (cmd.hasOption("x")) {
        try {
            nReadThrough = Integer.parseInt(cmd.getOptionValue("x"));
        } catch (NumberFormatException e) {
            printHelpAndExit(options, "Number of read through fusion genes (-x) must be a number");
        }
    }

    int nTriFusion = 0;
    if (cmd.hasOption("j")) {
        try {
            nTriFusion = Integer.parseInt(cmd.getOptionValue("j"));
        } catch (NumberFormatException e) {
            printHelpAndExit(options, "Number of tri-fusions (-j) must be a number");
        }
    }

    int nIntraChromFusion = 0;
    if (cmd.hasOption("y")) {
        try {
            nIntraChromFusion = Integer.parseInt(cmd.getOptionValue("y"));
        } catch (NumberFormatException e) {
            printHelpAndExit(options, "Number of intra-chromosome fusions (-y) must be a number");
        }
    }

    int nSelfFusion = 0;
    if (cmd.hasOption("s")) {
        try {
            nSelfFusion = Integer.parseInt(cmd.getOptionValue("s"));
        } catch (NumberFormatException e) {
            printHelpAndExit(options, "Number of self-fusions (-s) must be a number");
        }
    }

    int foreignInsertionLen = 0;
    if (cmd.hasOption("u")) {
        try {
            foreignInsertionLen = Integer.parseInt(cmd.getOptionValue("u"));
        } catch (NumberFormatException e) {
            printHelpAndExit(options, "Foreign insertion length (-u) must be a number");
        }
    }

    int nThreads = Runtime.getRuntime().availableProcessors();
    if (cmd.hasOption("p")) {
        try {
            nThreads = Integer.parseInt(cmd.getOptionValue("p"));
        } catch (NumberFormatException e) {
            printHelpAndExit(options, "Number of threads to spawn (-p) must be a number");
        }
    }

    double rpkmCutoff = 0.2;
    if (cmd.hasOption("k")) {
        try {
            rpkmCutoff = Double.parseDouble(cmd.getOptionValue("k"));
            if (rpkmCutoff < 0 || rpkmCutoff > 1)
                throw new NumberFormatException();
        } catch (NumberFormatException e) {
            printHelpAndExit(options, "RPKM cutoff (-k) must be 0 < cutoff < 1");
        }
    }

    double foreignInsertionPct = 0.0;
    if (cmd.hasOption("w")) {
        try {
            foreignInsertionPct = Double.parseDouble(cmd.getOptionValue("w"));
            if (foreignInsertionPct < 0 || foreignInsertionPct > 1)
                throw new NumberFormatException();
        } catch (NumberFormatException e) {
            printHelpAndExit(options, "Foreign insertion percent (-w) must be 0 < x < 1");
        }
    }

    GeneSelectionMethod geneSelectioMethod = GeneSelectionMethod.UNIFORM;
    if (cmd.hasOption("m")) {
        GeneSelectionMethod sm = GeneSelectionMethod.fromString(cmd.getOptionValue("m"));
        if (sm == null) {
            printHelpAndExit(options, "Invalid gene selection method: " + cmd.getOptionValue("m"));
        }
        geneSelectioMethod = sm;
    }

    Map<String, Boolean> limit = null;
    if (cmd.hasOption("l")) {
        limit = new HashMap<String, Boolean>();
        String[] limits = cmd.getOptionValue("l").split(",");
        if (limits.length < 1) {
            printHelpAndExit(options, "Must provide a limit of at least one genes (ex. gene1,gene2,..): "
                    + cmd.getOptionValue("l"));
        }
        for (int i = 0; i < limits.length; i++) {
            limit.put(limits[i], true);
        }
    }

    List<String[]> filters = new ArrayList<String[]>();
    for (String filterOption : new String[] { "1", "2", "3" }) {
        if (cmd.hasOption(filterOption)) {
            filters.add(cmd.getOptionValue(filterOption).split(","));
        } else {
            filters.add(null);
        }
    }

    File bamFile = null;
    if (cmd.hasOption("b")) {
        bamFile = new File(cmd.getOptionValue("b"));

        if (!bamFile.canRead()) {
            printHelpAndExit(options, "Please provide a valid BAM file");
        }
    }

    logger.info("========================================================================");
    logger.info("Running Fusim with the following settings:");
    logger.info("========================================================================");
    logger.info("Reference Gene Model: " + geneModelFile.getAbsolutePath());
    if (cmd.hasOption("t")) {
        logger.info(
                "Text Output: " + ("-".equals(cmd.getOptionValue("t")) ? "<stdout>" : cmd.getOptionValue("t")));
    }
    if (cmd.hasOption("f")) {
        logger.info("Fasta Output: "
                + ("-".equals(cmd.getOptionValue("f")) ? "<stdout>" : cmd.getOptionValue("f")));
    }
    if (!cmd.hasOption("f") && !cmd.hasOption("t")) {
        logger.info("Text Output: <stdout>");
    }
    logger.info("");
    logger.info("------------------");
    logger.info("Gene Selection");
    logger.info("------------------");
    if (cmd.hasOption("b")) {
        logger.info("Mode: background reads");
        logger.info("BAM file: " + bamFile.getAbsolutePath());
        logger.info("RPKM cutoff: " + rpkmCutoff);
        logger.info("Number of threads: " + nThreads);
        logger.info("Gene selection method: " + geneSelectioMethod.toString());
    } else {
        logger.info("Mode: gene model");
    }
    logger.info("");
    logger.info("------------------");
    logger.info("Type of fusions");
    logger.info("------------------");
    logger.info("Hybrid: " + nFusions);
    logger.info("Self: " + nSelfFusion);
    logger.info("Complex: " + nTriFusion);
    logger.info("Intra-chromosome: " + nIntraChromFusion);
    logger.info("Read through: " + nReadThrough);
    logger.info("");
    logger.info("------------------");
    logger.info("Fusion options");
    logger.info("------------------");
    logger.info("CDS only: " + (cmd.hasOption("c") ? "yes" : "no"));
    logger.info("Auto-correct orientation: " + (cmd.hasOption("a") ? "yes" : "no"));
    logger.info("Allow fusions outside of ORF: " + (cmd.hasOption("d") ? "yes" : "no"));
    logger.info("Force fusion breaks on exon boundries: " + (cmd.hasOption("e") ? "yes" : "no"));
    if (cmd.hasOption("u")) {
        logger.info("Foreign insertion max length: " + foreignInsertionLen);
        logger.info("Foreign insertion percent: " + foreignInsertionPct);
    }
    logger.info("========================================================================");

    GeneModelParser parser = new UCSCRefFlatParser(cmd.hasOption("e"), cmd.hasOption("c"), limit);
    GeneSelector selector = null;
    FusionGenerator fg = null;

    if (cmd.hasOption("b")) {
        selector = new BackgroundSelector(bamFile, rpkmCutoff, nThreads);
        fg = new BackgroundGenerator();
    } else {
        selector = new StaticSelector();
        fg = new RandomGenerator();
    }

    selector.setGeneModelFile(geneModelFile);
    selector.setGeneModelParser(parser);

    fg.setGeneSelector(selector);
    fg.setGeneSelectionMethod(geneSelectioMethod);
    fg.setFilters(filters);

    List<FusionGene> fusions = new ArrayList<FusionGene>();

    if (nFusions > 0) {
        fusions.addAll(fg.generate(nFusions, 2));
    }

    // Generate any read through fusion genes
    if (nReadThrough > 0) {
        logger.info("Generating read through genes...");
        ReadThroughGenerator rt = new ReadThroughGenerator();
        rt.setGeneSelector(selector);
        rt.setGeneSelectionMethod(geneSelectioMethod);

        List<FusionGene> rtFusions = rt.generate(nReadThrough, 2);
        for (FusionGene g : rtFusions) {
            g.setFusionType(FusionType.READ_THROUGH);
        }
        fusions.addAll(rtFusions);
    }

    // Generate any tri-fusions
    if (nTriFusion > 0) {
        logger.info("Generating tri-fusion genes...");
        List<FusionGene> tfusions = fg.generate(nTriFusion, 3);
        for (FusionGene g : tfusions) {
            g.setFusionType(FusionType.TRI_FUSION);
        }
        fusions.addAll(tfusions);
    }

    // Generate any intra chromosome fusions
    if (nIntraChromFusion > 0) {
        logger.info("Generating intra-chromosome fusions...");
        IntraChromGenerator ig = new IntraChromGenerator();
        ig.setGeneSelector(selector);
        ig.setGeneSelectionMethod(geneSelectioMethod);

        List<FusionGene> ifusions = ig.generate(nIntraChromFusion, 2);
        for (FusionGene g : ifusions) {
            g.setFusionType(FusionType.INTRA_CHROMOSOME);
        }
        fusions.addAll(ifusions);
    }

    // Generate any self-fusions
    if (nSelfFusion > 0) {
        logger.info("Generating self-fusion genes...");
        List<FusionGene> sfusions = fg.generate(nSelfFusion, 1);
        for (FusionGene g : sfusions) {
            g.setFusionType(FusionType.SELF_FUSION);
        }
        fusions.addAll(sfusions);
    }

    if (fusions.size() == 0) {
        fatalError(
                "No fusions to simulate! Check to be sure you have -j,-n,-s,-x,-y specified and your filters are correct.");
    }

    if (textOutput != null) {
        textOutput.println(StringUtils.join(FusionGene.getHeader(), "\t"));
    }

    int foreignInsertionCutoff = (int) (foreignInsertionPct * fusions.size());

    Random rgen = new Random();
    for (int g = 0; g < fusions.size(); g++) {
        FusionGene f = fusions.get(g);

        //out.println(f);
        List<int[]> breaks = new ArrayList<int[]>();

        // First half of gene 1
        breaks.add(f.getGene(0).generateExonBreak(true, cmd.hasOption("c")));

        if (f.size() == 2) {
            // Second half of gene2
            breaks.add(f.getGene(1).generateExonBreak(false, cmd.hasOption("c")));
        } else if (f.size() == 3) {
            // Second half of gene2
            breaks.add(f.getGene(1).generateExonBreak(false, cmd.hasOption("c")));

            // Second half of gene3
            breaks.add(f.getGene(2).generateExonBreak(false, cmd.hasOption("c")));
        }

        // Keep ORF (don't allow out of frame) and allow splitting of exons
        if (!cmd.hasOption("d") && !cmd.hasOption("e")) {
            // Split last exon in half and ensure within ORF
            for (int i = 0; i < breaks.size(); i++) {
                int[] exons = breaks.get(i);
                int[] lastExon = f.getGene(i).getExons(cmd.hasOption("c")).get(exons[exons.length - 1]);
                int randIndex = rgen.nextInt(lastExon[1] - lastExon[0]);
                while (randIndex % 3 != 0) {
                    randIndex--;
                }
                f.getGene(i).getExons(cmd.hasOption("c")).get(exons[exons.length - 1])[1] -= randIndex;
            }
        } else if (cmd.hasOption("e") && !cmd.hasOption("d")) {
            breaks.clear();
            // Keep ORF (don't allow out of frame) and don't allow splitting of exons (keep exon boundries)
            // Break genes on exons boundries
            breaks.add(f.getGene(0).generateExonBoundryBreak(cmd.hasOption("c")));

            if (f.size() == 2) {
                breaks.add(f.getGene(1).generateExonBoundryBreak(cmd.hasOption("c")));
            } else if (f.size() == 3) {
                breaks.add(f.getGene(2).generateExonBoundryBreak(cmd.hasOption("c")));
                breaks.add(f.getGene(3).generateExonBoundryBreak(cmd.hasOption("c")));
            }
        }

        // Set options for output
        if (cmd.hasOption("a")) {
            f.addOption(FusionOption.AUTO_CORRECT_ORIENTATION);
        }
        if (cmd.hasOption("c")) {
            f.addOption(FusionOption.CDS_ONLY);
        }
        if (cmd.hasOption("d")) {
            f.addOption(FusionOption.OUT_OF_FRAME);
        } else {
            f.addOption(FusionOption.SYMMETRICAL_EXONS);
        }
        if (cmd.hasOption("e")) {
            f.addOption(FusionOption.KEEP_EXON_BOUNDRY);
        }

        if (textOutput != null) {
            textOutput.print(f.outputText(breaks, cmd.hasOption("c")));
        }

        if (fastaOutput != null) {
            if (foreignInsertionLen > 0 && foreignInsertionCutoff > 0 && g <= foreignInsertionCutoff) {
                f.addOption(FusionOption.FOREIGN_INSERTION);
                fastaOutput.println(f.outputFasta(breaks, referenceFile, cmd.hasOption("c"), cmd.hasOption("a"),
                        foreignInsertionLen));
            } else {
                fastaOutput
                        .println(f.outputFasta(breaks, referenceFile, cmd.hasOption("c"), cmd.hasOption("a")));
            }
        }
    }

    if (textOutput != null)
        textOutput.flush();
    if (fastaOutput != null)
        fastaOutput.flush();

    logger.info("Fusim run complete. Goodbye!");
}

From source file:com.aliyun.openservices.odps.console.resource.CreateResourceCommand.java

public static AddResourceCommand parse(String commandString, ExecutionContext sessionContext)
        throws ODPSConsoleException {

    String[] tokens = new AntlrObject(commandString).getTokenStringArray();

    if (tokens != null && tokens.length >= 2 && tokens[0].toUpperCase().equals("CREATE")
            && tokens[1].toUpperCase().equals("RESOURCE")) {

        GnuParser parser = new GnuParser();
        Options options = new Options();
        options.addOption("p", "project", true, null);
        options.addOption("c", "comment", true, null);
        options.addOption("f", "force", false, null);

        try {/*from ww w  . ja  v a 2  s  .c om*/
            CommandLine cl = parser.parse(options, tokens);

            String refName = null;
            String alias = "";
            String comment = null;
            String type = null;
            String partitionSpec = "";
            boolean isUpdate = false;

            List<String> argList = cl.getArgList();
            int size = argList.size();

            if (size < 4) {
                throw new ODPSConsoleException(ODPSConsoleConstants.BAD_COMMAND + "Missing parameters");
            }

            ListIterator<String> iter = argList.listIterator();
            iter.next();
            iter.next();
            type = iter.next();
            refName = iter.next();
            if (iter.hasNext()) {
                String item = iter.next();
                if (item.equals("(")) {
                    boolean isParenPaired = false;

                    while (iter.hasNext()) {
                        String s = iter.next();
                        if (s.equals(")")) {
                            isParenPaired = true;
                            break;
                        }
                        partitionSpec += s;
                    }

                    if (!isParenPaired) {
                        throw new ODPSConsoleException(
                                ODPSConsoleConstants.BAD_COMMAND + "Unpaired parenthesis");
                    }

                    if (!iter.hasNext()) {
                        throw new ODPSConsoleException(
                                ODPSConsoleConstants.BAD_COMMAND + "Missing parameter: alias");
                    }
                    item = iter.next();
                }

                alias = item;
            }

            if (iter.hasNext()) {
                throw new ODPSConsoleException(
                        ODPSConsoleConstants.BAD_COMMAND + "Illegal parameter: " + iter.next());
            }

            String projectName = null;
            Option[] opts = cl.getOptions();
            for (Option opt : opts) {
                if ("f".equals(opt.getOpt())) {
                    isUpdate = true;
                } else if ("c".equals(opt.getOpt())) {
                    comment = opt.getValue();
                } else if ("p".equals(opt.getOpt())) {
                    projectName = opt.getValue();
                } else {
                    throw new ODPSConsoleException(
                            ODPSConsoleConstants.BAD_COMMAND + "Illegal option: " + opt.getOpt());
                }
            }

            return new AddResourceCommand(commandString, sessionContext, refName, alias, comment, type,
                    partitionSpec, isUpdate, projectName);
        } catch (ParseException e) {
            throw new ODPSConsoleException(ODPSConsoleConstants.BAD_COMMAND + "Invalid parameters");
        }
    } else {
        return null;
    }
}

From source file:com.netcrest.pado.tools.pado.command.put.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from  w w w.  j a v  a  2s  .  c  o  m
public void run(CommandLine commandLine, String command) throws Exception {
    String path = commandLine.getOptionValue("path");
    String bufferName = commandLine.getOptionValue("buffer");
    List<String> argList = commandLine.getArgList();

    if (path != null && bufferName != null) {
        PadoShell.printlnError(this, "Specifying both path and buffer not allowed. Only one option allowed.");
        return;
    }
    if (argList.size() < 2) {
        PadoShell.println(this, "Must specify key/value pair(s).");
        return;
    }
    if (path == null && bufferName == null) {
        path = padoShell.getCurrentPath();
    }

    boolean keyEnumerated = commandLine.hasOption('k');
    boolean valueEnumerated = commandLine.hasOption('v');
    Option options[] = commandLine.getOptions();
    for (Option option : options) {
        if (keyEnumerated == false) {
            keyEnumerated = option.getOpt().contains("k");
        }
        if (valueEnumerated == false) {
            valueEnumerated = option.getOpt().contains("v");
        }
    }

    int keyIndex = argList.indexOf(argList.get(1));
    String fullPath;
    String gridId;
    String gridPath;
    BufferInfo bufferInfo = null;
    if (path != null) {
        fullPath = padoShell.getFullPath(path);
        gridPath = GridUtil.getChildPath(fullPath);
        gridId = SharedCache.getSharedCache().getGridId(fullPath);
    } else {
        bufferInfo = SharedCache.getSharedCache().getBufferInfo(bufferName);
        if (bufferInfo == null) {
            PadoShell.printlnError(this, bufferName + ": Buffer undefined.");
            return;
        }
        gridId = bufferInfo.getGridId();
        gridPath = bufferInfo.getGridPath();
        if (gridId == null || gridPath == null) {
            PadoShell.printlnError(this, bufferName + ": Invalid buffer. This buffer does not contain keys.");
            return;
        }
        fullPath = SharedCache.getSharedCache().getPado().getCatalog().getGridService().getFullPath(gridId,
                gridPath);
    }
    Map map = getEntryMap(fullPath, bufferInfo, argList, keyEnumerated, valueEnumerated, keyIndex);
    IGridMapBiz gridMapBiz = SharedCache.getSharedCache().getPado().getCatalog().newInstance(IGridMapBiz.class,
            gridPath);
    gridMapBiz.getBizContext().getGridContextClient().setGridIds(gridId);
    gridMapBiz.putAll(map);

    // ArrayList keyList = new ArrayList();
    if (padoShell.isShowResults()) {
        PrintUtil.printEntries(gridMapBiz, map.keySet(), null);
    }
}

From source file:mitm.application.djigzo.tools.CLITool.java

private void handleCommandline(String[] args) throws Exception {
    CommandLineParser parser = new PosixParser();

    Options options = createCommandLineOptions();

    HelpFormatter formatter = new HelpFormatter();

    CommandLine commandLine;

    try {//from  w w w.  ja va 2s. co  m
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        formatter.printHelp(COMMAND_NAME, options, true);

        throw e;
    }

    initLogging(commandLine.hasOption(loggingOption.getLongOpt()));

    soapUser = soapUserOption.getValue();

    soapPassword = soapPasswordOption.getValue();

    encrypt = commandLine.hasOption(encryptOption.getLongOpt());

    value = valueOption.getValue();

    email = StringUtils.trimToNull(emailOption.getValue());

    domain = StringUtils.trimToNull(domainOption.getValue());

    global = commandLine.hasOption(globalOption.getLongOpt());

    salt = StringUtils.trimToNull(saltOption.getValue());

    if (commandLine.getOptions().length == 0 || commandLine.hasOption(helpOption.getLongOpt())) {
        formatter.printHelp(COMMAND_NAME, options, true);

        System.exit(1);

        return;
    }

    if (commandLine.hasOption(setPropertyOption.getLongOpt())) {
        setProperty();
    } else if (commandLine.hasOption(getPropertyOption.getLongOpt())) {
        getProperty();
    } else if (commandLine.hasOption(addUserOption.getLongOpt())) {
        addUser();
    } else if (commandLine.hasOption(deleteUserOption.getLongOpt())) {
        deleteUser();
    } else if (commandLine.hasOption(addDomainOption.getLongOpt())) {
        addDomain();
    } else if (commandLine.hasOption(deleteDomainOption.getLongOpt())) {
        deleteDomain();
    } else if (commandLine.hasOption(importXMLOption.getLongOpt())) {
        importXML();
    } else if (commandLine.hasOption(encodePasswordOption.getLongOpt())) {
        encodePassword();
    }
}