Example usage for org.apache.commons.cli Option getOpt

List of usage examples for org.apache.commons.cli Option getOpt

Introduction

In this page you can find the example usage for org.apache.commons.cli Option getOpt.

Prototype

public String getOpt() 

Source Link

Document

Retrieve the name of this Option.

Usage

From source file:calculadora.controlador.ControladorComandos.java

/**
 * Controlo si un comando con posix largo se escribio a la vez que otro
 * posix largo como puede ser (--help) junto con --(seno) de error.
 *
 * Controlo si un comando posix largo se escribio a la vez que otro de posix
 * corto que no sean --help y -D(ya que si ocurriera esto mostraria la
 * ayuda), y viceversa tiene que dar error.
 *
 * @param opt dos opciones//from ww w .jav a 2s  .c  om
 * @see Option
 * @throws ParseException Demasiados comandos
 */
private void hasBuenosComandos(Option[] opt) throws ParseException {
    //Obtengo la primera y la segunda opcion
    Option op1 = opt[0];
    Option op2 = opt[1];

    boolean isLongOpt1 = op1.hasLongOpt();
    boolean isLongOpt2 = op2.hasLongOpt();

    //Si los dos comandos son posix largo error
    if (isLongOpt1 && isLongOpt2) {
        throw errorComandos(); //Error de comandos
        //Si el primero es posix largo y el segundo no pero son el comando
        //-help y -D no debe ocurrir nada
    } else if ((isLongOpt1 && !isLongOpt2 && op1.getLongOpt().equals(HELP) && op2.getOpt().equals(PROPERTY))) {
        //No debe hacer nada importante esto vacio.
        //Si el primero es poxis largo y el segundo posix corto y viceversa
    } else if (isLongOpt1 && !isLongOpt2 || !isLongOpt1 && isLongOpt2) {
        throw errorComandos(); //Error de comandos
    }
}

From source file:dumptspacket.Main.java

public void start(String[] args) throws org.apache.commons.cli.ParseException {
    final String fileName;
    final Long limit;
    final Set<Integer> pids;

    System.out.println("args   : " + dumpArgs(args));

    final Option fileNameOption = Option.builder("f").required().longOpt("filename").desc("ts??")
            .hasArg().type(String.class).build();

    final Option limitOption = Option.builder("l").required(false).longOpt("limit")
            .desc("??(???????EOF??)").hasArg()
            .type(Long.class).build();

    final Option pidsOption = Option.builder("p").required().longOpt("pids")
            .desc("pid(?16?)").type(String.class).hasArgs().build();

    Options opts = new Options();
    opts.addOption(fileNameOption);/*w  w  w .j a va2 s . c  om*/
    opts.addOption(limitOption);
    opts.addOption(pidsOption);
    CommandLineParser parser = new DefaultParser();
    CommandLine cl;
    HelpFormatter help = new HelpFormatter();

    try {

        // parse options
        cl = parser.parse(opts, args);

        // handle interface option.
        fileName = cl.getOptionValue(fileNameOption.getOpt());
        if (fileName == null) {
            throw new ParseException("????????");
        }

        // handlet destination option.
        Long xl = null;
        try {
            xl = Long.parseUnsignedLong(cl.getOptionValue(limitOption.getOpt()));
        } catch (NumberFormatException e) {
            xl = null;
        } finally {
            limit = xl;
        }

        Set<Integer> x = new HashSet<>();
        List<String> ls = new ArrayList<>();
        ls.addAll(Arrays.asList(cl.getOptionValues(pidsOption.getOpt())));
        for (String s : ls) {
            try {
                x.add(Integer.parseUnsignedInt(s, 16));
            } catch (NumberFormatException e) {
                throw new ParseException(e.getMessage());
            }
        }
        pids = Collections.unmodifiableSet(x);

        System.out.println("Starting application...");
        System.out.println("filename   : " + fileName);
        System.out.println("limit : " + limit);
        System.out.println("pids : " + dumpSet(pids));

        // your code
        TsReader reader;
        if (limit == null) {
            reader = new TsReader(new File(fileName), pids);
        } else {
            reader = new TsReader(new File(fileName), pids, limit);
        }

        Map<Integer, List<TsPacketParcel>> ret = reader.getPackets();
        try {
            for (Integer pid : ret.keySet()) {

                FileWriter writer = new FileWriter(fileName + "_" + Integer.toHexString(pid) + ".txt");

                for (TsPacketParcel par : ret.get(pid)) {
                    String text = Hex.encodeHexString(par.getPacket().getData());
                    writer.write(text + "\n");

                }
                writer.flush();
                writer.close();
            }
        } catch (IOException ex) {
            LOG.fatal("", ex);
        }

    } catch (ParseException e) {
        // print usage.
        help.printHelp("My Java Application", opts);
        throw e;
    } catch (FileNotFoundException ex) {
        LOG.fatal("", ex);
    }
}

From source file:channellistmaker.main.Main.java

public void start(String[] args) throws ParseException {

    final Option charSetOption = Option.builder("c").required(false).longOpt("charset").desc(
            "?????????????")
            .hasArg().type(String.class).build();

    final Option directoryNameOption = Option.builder("d").required().longOpt("directoryname")
            .desc("??").hasArg().type(String.class).build();

    final Option destFileNameOption = Option.builder("f").required().longOpt("destname")
            .desc("???").hasArg().type(String.class).build();

    Options opts = new Options();
    opts.addOption(charSetOption);//  www .j a va2 s  .  co  m
    opts.addOption(directoryNameOption);
    opts.addOption(destFileNameOption);
    CommandLineParser parser = new DefaultParser();

    HelpFormatter help = new HelpFormatter();
    CommandLine cl;
    try {
        cl = parser.parse(opts, args);
    } catch (ParseException ex) {
        LOG.fatal("??????", ex);
        help.printHelp("My Java Application", opts);
        throw ex;
    }

    final Charset charSet;
    try {
        final String chersetstr = cl.getOptionValue(charSetOption.getOpt());
        if (chersetstr == null || "".equals(chersetstr)) {
            charSet = Charset.defaultCharset();
            LOG.info(
                    "???????????");
        } else {
            charSet = Charset.forName(chersetstr);
        }
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException("????????", e);
    }
    LOG.info(" = " + charSet);

    final File dirName = new File(cl.getOptionValue(directoryNameOption.getOpt()));
    if (!dirName.isDirectory()) {
        throw new IllegalArgumentException(
                "???????????");
    }
    LOG.info("?? = " + dirName.getAbsolutePath());

    final File destFile = new File(cl.getOptionValue(destFileNameOption.getOpt()));
    LOG.info("??? = " + destFile.getAbsolutePath());

    final Set<Document> docs = new EPGListMaker(dirName, charSet).seek();

    final Map<MultiKey<Integer>, Channel> channels = new AllChannelDataExtractor(docs).getAllEPGRecords();

    final ChannelDocumentMaker dm = new ChannelDocumentMaker(channels);

    try (FileOutputStream fos = new FileOutputStream(destFile);
            OutputStreamWriter os = new OutputStreamWriter(fos, charSet);
            BufferedWriter bw = new BufferedWriter(os);) {
        bw.write(dm.getChannelList());
        bw.flush();
        os.flush();
        fos.flush();
        LOG.info("?????");
    } catch (IOException ex) {
        LOG.fatal("???", ex);
    }
}

From source file:epgtools.dumpchannellistfromts.Main.java

public void start(String[] args) throws ParseException {
    final String fileName;
    final Long limit;

    final Option directoryNameOption = Option.builder("d").required().longOpt("directoryname")
            .desc("??").hasArg().type(String.class).build();

    final Option limitOption = Option.builder("l").required(false).longOpt("limit")
            .desc("??(???????EOF??)").hasArg()
            .type(Long.class).build();

    final Option destFileNameOption = Option.builder("f").required().longOpt("destname")
            .desc("???").hasArg().type(String.class).build();

    Options opts = new Options();
    opts.addOption(directoryNameOption);
    opts.addOption(limitOption);//from   w  w  w. ja va  2 s  .  co m
    opts.addOption(destFileNameOption);
    CommandLineParser parser = new DefaultParser();

    HelpFormatter help = new HelpFormatter();
    CommandLine cl;
    try {
        cl = parser.parse(opts, args);
    } catch (ParseException ex) {
        LOG.fatal("??????", ex);
        help.printHelp("My Java Application", opts);
        throw ex;
    }

    final File dirName = new File(cl.getOptionValue(directoryNameOption.getOpt()));
    if (!dirName.isDirectory()) {
        throw new IllegalArgumentException(
                "??????????? = "
                        + dirName.getAbsolutePath());
    }
    LOG.info("?? = " + dirName.getAbsolutePath());

    Long xl = null;
    try {
        if (cl.hasOption(limitOption.getOpt())) {
            xl = Long.parseUnsignedLong(cl.getOptionValue(limitOption.getOpt()));
        }
    } catch (NumberFormatException e) {
        LOG.error(e);
        throw new IllegalArgumentException("????????");
    } finally {
        limit = xl;
        LOG.info("?? = " + limit);
    }

    final File destFile = new File(cl.getOptionValue(destFileNameOption.getOpt()));
    LOG.info("??? = " + destFile.getAbsolutePath());

    List<File> files = new TsFileSeeker(dirName).seek();

    LOG.info("?? = " + files.size());

    final PhysicalChannelNumberRecordBuilder bu = new PhysicalChannelNumberRecordBuilder();
    final Set<PhysicalChannelNumberRecord> records = Collections.synchronizedSet(new TreeSet<>());
    //NIT?
    for (File f : files) {
        SectionLoader loader = new SectionLoader(f, limit, RESERVED_PROGRAM_ID.NIT.getPids());
        try {
            Map<Integer, List<Section>> pids_sections = loader.load();
            for (Integer k : pids_sections.keySet()) {
                for (Section s : pids_sections.get(k)) {
                    if (s.checkCRC() != Section.CRC_STATUS.NO_CRC_ERROR) {
                        throw new IllegalArgumentException(
                                "CRC?? = " + Hex.encodeHexString(s.getData()));
                    } else if (s.getTable_id_const() != TABLE_ID.NIT_THIS_NETWORK) {
                        throw new IllegalArgumentException(
                                "?NIT????? = "
                                        + Hex.encodeHexString(s.getData()));
                    } else {
                        NetworkInformationTableBody nitbody = (NetworkInformationTableBody) s.getSectionBody();
                        bu.setNetworkId(nitbody.getNetwork_id());
                        for (Descriptor d1 : nitbody.getDescriptors_loop().getDescriptors_loopList()) {
                            if (d1.getDescriptor_tag_const() == DESCRIPTOR_TAG.NETWORK_NAME_DESCRIPTOR) {
                                final NetworkNameDescriptor nnd = (NetworkNameDescriptor) d1;
                                bu.setNetworkName(nnd.getChar_String());
                            }
                        }
                        for (TransportStreamLoop tsLoop : nitbody.getTransport_streams_loop()) {
                            bu.setTransportStreamId(tsLoop.getTransport_stream_id());
                            bu.setOriginalNetworkId(tsLoop.getOriginal_network_id());
                            for (Descriptor desc : tsLoop.getDescriptors_loop().getDescriptors_loopList()) {
                                if (desc.getDescriptor_tag_const() == DESCRIPTOR_TAG.SERVICE_LIST_DESCRIPTOR) {
                                    ServiceListDescriptor sd = (ServiceListDescriptor) desc;
                                    List<Service> svList = sd.getServiceList();
                                    for (Service service : svList) {
                                        if (service.getService_type_Enum() == SERVICE_TYPE.DIGITAL_TV_SERVICE) {
                                            bu.setServiceId(service.getService_id());

                                            if (bu.getOriginalNetworkId() < 0x10) {
                                                //BS
                                                bu.setPhysicalChannelNumber(bu.getServiceId());
                                            } else {
                                                //          
                                                bu.setPhysicalChannelNumber(
                                                        Integer.valueOf(this.getNameWithoutExtension(f)));
                                            }

                                            records.add(bu.build());
                                        }
                                    }

                                }
                            }
                        }
                    }
                }
            }
        } catch (FileNotFoundException ex) {
            LOG.info("????? = " + f.getAbsolutePath(), ex);
        }
    }

    //        for (PhysicalChannelNumberRecord rec : records) {
    //            LOG.info(rec);
    //        }
    //        
    //???????
    List<PhysicalChannelNumberRecord> nl = new ArrayList<>();
    nl.addAll(records);
    CsvManager csvManager = CsvManagerFactory.newCsvManager();
    LOG.info(destFile.getAbsolutePath());
    try {
        csvManager.save(nl, PhysicalChannelNumberRecord.class).to(destFile, "UTF-8");
    } catch (IOException ex) {
        LOG.fatal("???????? = " + destFile.getAbsolutePath(), ex);
    }

}

From source file:edu.usc.scrc.PriorityPruner.CommandLineOptions.java

/**
 * Parses command line arguments, evaluates them, and stores values if
 * they're correct.//w  ww.  ja  va  2s. c  o m
 * 
 * @param options
 *            collection of Option-objects
 * @param args
 *            command line arguments
 * @throws PriorityPrunerException
 *             if error occurs during parsing
 */
private void parse(Options options, String[] args) throws PriorityPrunerException {
    try {
        CommandLineParser cmdLineParser = new GnuParser();
        CommandLine commandLine = cmdLineParser.parse(options, args);
        setParsedOptions(commandLine.getOptions());
        // gets set to true if -tfile option is entered through the command
        // line
        //boolean tFlag = false;
        // counts --tped & --tfam options entered through the command line
        //int tpedCount = 0;
        //int tfamCount = 0;

        // loops through all options to save the ones in effect as a String
        // for printing
        String tmp = "Options in effect:";
        for (Option opt : commandLine.getOptions()) {
            tmp += ("\r\n   -" + opt.getOpt());
            if (opt.getValues() != null) {
                for (int i = 0; i < opt.getValues().length; i++) {
                    tmp += (" " + opt.getValues()[i]);
                }
            }
        }

        // saves options in effect for printing
        this.setOptionsInEffect(tmp + "\r\n");

        // parse max_distance
        if (commandLine.hasOption("max_distance")) {
            this.maxDistance(getLongArgument("max_distance", commandLine.getOptionValue("max_distance"), 0,
                    Long.MAX_VALUE));
            checkInput(1, "max_distance", commandLine);
        }

        // parse min_maf
        if (commandLine.hasOption("min_maf")) {
            this.setMinMaf(getDoubleArgument("min_maf", commandLine.getOptionValue("min_maf"), 0, 0.5));
            checkInput(1, "min_maf", commandLine);
        }

        // parse min_hwe
        //         if (commandLine.hasOption("min_hwe")) {
        //            this.setMinHwe(getDoubleArgument("min_hwe",
        //                  commandLine.getOptionValue("min_hwe"), 0, 1));
        //            checkInput(1, "min_hwe", commandLine);
        //         }

        // parses min_snp_callrate
        if (commandLine.hasOption("min_snp_callrate")) {
            this.setMinSnpCallRate(getDoubleArgument("min_snp_callrate",
                    commandLine.getOptionValue("min_snp_callrate"), 0, 1));
            checkInput(1, "min_snp_callrate", commandLine);
        }

        // parses min_design_score
        if (commandLine.hasOption("min_design_score")) {
            this.setMinDesignScore(getDoubleArgument("min_design_score",
                    commandLine.getOptionValue("min_design_score"), 0, Double.MAX_VALUE));
            checkInput(1, "min_design_score", commandLine);
        }

        //         // parses option that sets the absolute minimum design score
        //         // value, allowed arguments are doubles between 0.0 and
        //         // Double.MAX_VALUE
        //         if (commandLine.hasOption("amds")) {
        //            this.setAbsoluteMinDesignScore(getDoubleArgument(
        //                  "absmindesignscore",
        //                  commandLine.getOptionValue("amds"), 0, Double.MAX_VALUE));
        //            checkInput(1, "amds", commandLine);
        //         }

        // parse metric
        if (commandLine.hasOption("metric")) {
            String[] str = commandLine.getOptionValues("metric");
            if (str.length % 2 == 1) {
                throw new PriorityPrunerException(
                        "Only one argument specified for option \"metric\", a column name (text string) and a weight (decimal number) are required.");
            } else {
                for (int i = 0; i < str.length; i++) {
                    if (str[i].equals("design_score")) {
                        throw new PriorityPrunerException("Invalid metric: \"" + str[i]
                                + "\". To filter on design score, simply add correct column in the SNP input file, no metric is needed.");
                    }
                    addMetric(str[i], this.getDoubleArgument("metric", str[i + 1], 0, Double.MAX_VALUE));
                    i++;
                }
            }
        }

        // parse st
        if (commandLine.hasOption("st")) {
            String[] str = commandLine.getOptionValues("st");
            if (str.length % 2 == 1) {
                throw new PriorityPrunerException(
                        "Only one argument specified for option: \"st\", a p-value (decimal number) and a number of surrogates (integer) are are required.");
            } else {
                for (int i = 0; i < str.length; i++) {
                    addSurrogateThreshold(this.getDoubleArgument("st", str[i], 0, 1),
                            this.getIntegerArgument("st", str[i + 1], 0, Integer.MAX_VALUE));
                    i++;
                }
            }
        }

        // parse r2t
        if (commandLine.hasOption("r2t")) {
            String[] str = commandLine.getOptionValues("r2t");
            if (str.length % 2 == 1) {
                throw new PriorityPrunerException(
                        "Only one argument specified for option: \"r2t\", a p-value and a threshold (decimal numbers between 0 and 1) are required.");
            } else {
                for (int i = 0; i < str.length; i++) {
                    addR2Threshold(this.getDoubleArgument("r2t", str[i], 0, 1),
                            this.getDoubleArgument("r2t", str[i + 1], 0, 1));
                    i++;
                }
            }
        }

        // parse r2
        if (commandLine.hasOption("r2")) {
            String value = commandLine.getOptionValue("r2");
            this.addR2Threshold(1, this.getDoubleArgument("r2", value, 0, 1));
            checkInput(1, "r2", commandLine);
        }

        // parse chr
        if (commandLine.hasOption("chr")) {
            String value = commandLine.getOptionValue("chr");
            // recoding chromosome X-representations to "23"
            if (value.toUpperCase().equals("X") || value.toUpperCase().equals("CHRX")) {
                //value = "23";
            }
            // if chromosome Y or mitochondrial DNA is encountered, an
            // exception is thrown
            else if (value.toUpperCase().equals("M") || value.toUpperCase().equals("MT")
                    || value.toUpperCase().equals("CHRM") || value.toUpperCase().equals("CHRMT")
                    || value.toUpperCase().equals("Y") || value.toUpperCase().equals("CHRY")
                    || value.toUpperCase().equals("24")) {
                throw new PriorityPrunerException("Chromosome \"" + value
                        + "\" specified in the command line, is not supported. Please update input files and rerun program.");
            }
            this.setChr(value);
            checkInput(1, "chr", commandLine);
        }

        // parse out
        if (commandLine.hasOption("out")) {
            String value = commandLine.getOptionValue("out");
            if (value.endsWith("/")) {
                value = new StringBuilder(value).append("prioritypruner").toString();
            }
            this.setOutputPrefix(value);
            checkInput(1, "out", commandLine);
        }

        //         // parse forceInclude
        //         if (commandLine.hasOption("force_include")) {
        //            String value = commandLine.getOptionValue("force_include");
        //            this.setForceIncludeFilePath(value);
        //            checkInput(1, "force_include", commandLine);
        //         }

        // parse do_not_pick_force_included_snps_first
        if (commandLine.hasOption("do_not_pick_force_included_snps_first")) {
            this.setSortByForceIncludeAndPValue(false);
        }

        // parse snp_table
        if (commandLine.hasOption("snp_table")) {
            String[] str = commandLine.getOptionValues("snp_table");
            this.setSnpTablePath(str[0]);
            // counts number of metrics added to command line
            int metrics = 0;
            for (int i = 0; i < getParsedOptions().length; i++) {
                if (getParsedOptions()[i].getOpt().equals("metric")) {
                    metrics++;
                }
            }
            this.setNumMetrics(metrics);
            checkInput(1, "snp_table", commandLine);
        }

        // parse tped
        if (commandLine.hasOption("tped")) {
            String value = commandLine.getOptionValue("tped");
            checkInput(1, "tped", commandLine);
            this.setTped(value);
        }

        // parse tfam
        if (commandLine.hasOption("tfam")) {
            String value = commandLine.getOptionValue("tfam");
            checkInput(1, "tfam", commandLine);
            this.setTfam(value);
        }

        // parse tfile
        if (commandLine.hasOption("tfile")) {
            String value = commandLine.getOptionValue("tfile");
            checkInput(1, "tfile", commandLine);
            this.setTped(value + ".tped");
            this.setTfam(value + ".tfam");
            this.setTfile(value);
        }

        // parse use_surrogate_for_non_passing_index_snps
        //         if (commandLine.hasOption("use_surrogate_for_non_passing_index_snps")) {
        //            this.setUseSurrogateForNonPassingIndexSnp(true);
        //         }

        // parses verbose
        if (commandLine.hasOption("verbose")) {
            this.setVerbose(true);
        }

        // parse outputLDTable
        if (commandLine.hasOption("ld")) {
            this.setOutputLDTable(true);
        }

        // parse remove
        if (commandLine.hasOption("remove")) {
            String value = commandLine.getOptionValue("remove");
            checkInput(1, "remove", commandLine);
            this.setRemove(value);
        }

        // parse keep
        if (commandLine.hasOption("keep")) {
            String value = commandLine.getOptionValue("keep");
            checkInput(1, "keep", commandLine);
            this.setKeep(value);
        }

        // parse keep_random
        if (commandLine.hasOption("keep_random")) {
            String value = commandLine.getOptionValue("keep_random");
            this.setKeepPercentage(this.getDoubleArgument("keep_random", value, 0, 1));
            checkInput(1, "keep_random", commandLine);
        }

        // parse no_surrogates_for_force_included_snps
        if (commandLine.hasOption("no_surrogates_for_force_included_snps")) {
            this.setAddSurrogatesForForceIncludedSnps(false);
        }

        // parse seed
        if (commandLine.hasOption("seed")) {
            String value = commandLine.getOptionValue("seed");
            this.seed = new Long(this.getLongArgument("seed", value, Long.MIN_VALUE, Long.MAX_VALUE));
        }

        // check that we have all required arguments
        checkRequiredArguments(commandLine);

        // checks if any unrecognized arguments been entered
        checkLeftArguments(commandLine);

        // if several options from the same options group been entered,
        // an AlreadySelectedException gets thrown. A custom message is
        // generated since we wanted another design than the one provided in
        // the library gave
    } catch (AlreadySelectedException e) {
        String message = "";
        for (int i = 0; i < e.getOptionGroup().getNames().toArray().length; i++) {
            message += "\"" + e.getOptionGroup().getNames().toArray()[i] + "\" ";
        }
        throw new PriorityPrunerException(
                "The options: " + message + " may not both be defined. Type --help for help.");

        // if an undefined option is entered an UnrecognizedOptionException
        // gets thrown
    } catch (UnrecognizedOptionException e) {
        throw new PriorityPrunerException(e.getOption() + " is not a valid option. Type --help for help.");

        // if an option that is supposed to have arguments is missing,
        // a MissingArgumentException gets thrown
    } catch (MissingArgumentException e) {
        throw new PriorityPrunerException("Missing argument for option \"" + e.getOption().getOpt()
                + "\". Expected: " + e.getOption().getArgName() + ". Type --help for help.");

        // if a required option is missing, a MissingOptionException gets
        // thrown
    } catch (MissingOptionException e) {
        // if any other problem occurs while parsing, a general
        // ParseException gets thrown
    } catch (ParseException parseException) {
        throw new PriorityPrunerException("Invalid command line options. Type --help for help.");
    }
}

From source file:com.haulmont.cuba.core.sys.utils.DbUpdaterUtil.java

@SuppressWarnings("AccessStaticViaInstance")
public void execute(String[] args) {
    Options cliOptions = new Options();

    Option dbConnectionOption = OptionBuilder.withArgName("connectionString").hasArgs()
            .withDescription("JDBC Database URL").isRequired().create("dbUrl");

    Option dbUserOption = OptionBuilder.withArgName("userName").hasArgs().withDescription("Database user")
            .isRequired().create("dbUser");

    Option dbPasswordOption = OptionBuilder.withArgName("password").hasArgs()
            .withDescription("Database password").isRequired().create("dbPassword");

    Option dbDriverClassOption = OptionBuilder.withArgName("driverClassName").hasArgs()
            .withDescription("JDBC driver class name").create("dbDriver");

    Option dbDirOption = OptionBuilder.withArgName("filePath").hasArgs()
            .withDescription("Database scripts directory").isRequired().create("scriptsDir");

    Option dbTypeOption = OptionBuilder.withArgName("dbType").hasArgs()
            .withDescription("DBMS type: postgres|mssql|oracle|etc").isRequired().create("dbType");

    Option dbVersionOption = OptionBuilder.withArgName("dbVersion").hasArgs()
            .withDescription("DBMS version: 2012|etc").create("dbVersion");

    Option dbExecuteGroovyOption = OptionBuilder.withArgName("executeGroovy").hasArgs()
            .withDescription("Ignoring Groovy scripts").create("executeGroovy");

    Option showUpdatesOption = OptionBuilder.withDescription("Print update scripts").create("check");

    Option applyUpdatesOption = OptionBuilder.withDescription("Update database").create("update");

    Option createDbOption = OptionBuilder.withDescription("Create database").create("create");

    cliOptions.addOption("help", false, "Print help");
    cliOptions.addOption(dbConnectionOption);
    cliOptions.addOption(dbUserOption);/*from www  .ja  va2  s  . c om*/
    cliOptions.addOption(dbPasswordOption);
    cliOptions.addOption(dbDirOption);
    cliOptions.addOption(dbTypeOption);
    cliOptions.addOption(dbVersionOption);
    cliOptions.addOption(dbExecuteGroovyOption);
    cliOptions.addOption(showUpdatesOption);
    cliOptions.addOption(applyUpdatesOption);
    cliOptions.addOption(createDbOption);

    CommandLineParser parser = new PosixParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;
    try {
        cmd = parser.parse(cliOptions, args);
    } catch (ParseException exp) {
        formatter.printHelp("dbupdate", cliOptions);
        return;
    }

    if (cmd.hasOption("help") || (!cmd.hasOption(showUpdatesOption.getOpt()))
            && !cmd.hasOption(applyUpdatesOption.getOpt()) && !cmd.hasOption(createDbOption.getOpt()))
        formatter.printHelp("dbupdate", cliOptions);
    else {
        this.dbScriptsDirectory = cmd.getOptionValue(dbDirOption.getOpt());
        File directory = new File(dbScriptsDirectory);
        if (!directory.exists()) {
            log.error("Not found db update directory");
            return;
        }

        dbmsType = cmd.getOptionValue(dbTypeOption.getOpt());
        dbmsVersion = StringUtils.trimToEmpty(cmd.getOptionValue(dbVersionOption.getOpt()));

        AppContext.Internals.setAppComponents(new AppComponents("core"));

        AppContext.setProperty("cuba.dbmsType", dbmsType);
        AppContext.setProperty("cuba.dbmsVersion", dbmsVersion);

        String dbDriver;
        if (!cmd.hasOption(dbDriverClassOption.getOpt())) {
            switch (dbmsType) {
            case "postgres":
                dbDriver = "org.postgresql.Driver";
                break;
            case "mssql":
                if (MS_SQL_2005.equals(dbmsVersion)) {
                    dbDriver = "net.sourceforge.jtds.jdbc.Driver";
                } else {
                    dbDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
                }
                break;
            case "oracle":
                dbDriver = "oracle.jdbc.OracleDriver";
                break;
            default:
                log.error(
                        "Unable to determine driver class name by DBMS type. Please provide driverClassName option");
                return;
            }
        } else {
            dbDriver = cmd.getOptionValue(dbDriverClassOption.getOpt());
        }

        try {
            Class.forName(dbDriver);
        } catch (ClassNotFoundException e) {
            log.error("Unable to load driver class " + dbDriver);
            return;
        }

        String connectionStringParam = cmd.getOptionValue(dbConnectionOption.getOpt());
        try {
            this.dataSource = new SingleConnectionDataSource(connectionStringParam,
                    cmd.getOptionValue(dbUserOption.getOpt()), cmd.getOptionValue(dbPasswordOption.getOpt()));
        } catch (SQLException e) {
            log.error("Unable to connect to db: " + connectionStringParam);
            return;
        }

        if (cmd.hasOption(createDbOption.getOpt())) {
            // create database from init scripts
            StringBuilder availableScripts = new StringBuilder();
            for (ScriptResource initScript : getInitScripts()) {
                availableScripts.append("\t").append(getScriptName(initScript)).append("\n");
            }
            log.info("Available create scripts: \n" + availableScripts);
            log.info(String.format("Do you want to create database %s ? [y/n]", connectionStringParam));
            Scanner scanner = new Scanner(new InputStreamReader(System.in, StandardCharsets.UTF_8));
            if ("y".equals(scanner.next())) {
                doInit();
            }
        } else {
            boolean updatesAvailable = false;
            try {
                List<String> scripts;

                executeGroovy = !(cmd.hasOption(dbExecuteGroovyOption.getOpt())
                        && cmd.getOptionValue(dbExecuteGroovyOption.getOpt()).equals("false"));

                scripts = findUpdateDatabaseScripts();

                if (!scripts.isEmpty()) {
                    StringBuilder availableScripts = new StringBuilder();
                    for (String script : scripts) {
                        availableScripts.append("\t").append(script).append("\n");
                    }
                    log.info("Available updates:\n" + availableScripts);
                    updatesAvailable = true;
                } else
                    log.info("No available updates found for database");
            } catch (DbInitializationException e) {
                log.warn("Database not initialized");
                return;
            }

            if (updatesAvailable && cmd.hasOption(applyUpdatesOption.getOpt())) {
                log.info(String.format("Do you want to apply updates to %s ? [y/n]", connectionStringParam));
                Scanner scanner = new Scanner(new InputStreamReader(System.in, StandardCharsets.UTF_8));
                if ("y".equals(scanner.next())) {
                    doUpdate();
                }
            }
        }
    }
}

From source file:com.haulmont.cuba.uberjar.ServerRunner.java

protected void execute(String[] args) {
    Options cliOptions = new Options();

    Option portOption = Option.builder("port").hasArg().desc("server port").argName("port").build();

    Option contextPathOption = Option.builder("contextName").hasArg().desc("application context name")
            .argName("contextName").build();

    Option frontContextPathOption = Option.builder("frontContextName").hasArg()
            .desc("front application context name").argName("frontContextName").build();

    Option portalContextPathOption = Option.builder("portalContextName").hasArg()
            .desc("portal application context name for single jar application").argName("portalContextName")
            .build();/*from  ww w.ja v  a  2  s  .c  o m*/

    Option jettyEnvPathOption = Option.builder("jettyEnvPath").hasArg().desc("jetty resource xml path")
            .argName("jettyEnvPath").build();

    Option jettyConfOption = Option.builder("jettyConfPath").hasArg().desc("jetty configuration xml path")
            .argName("jettyConfPath").build();

    Option stopPortOption = Option.builder("stopPort").hasArg()
            .desc("port number on which this server waits for a shutdown command").argName("stopPort").build();

    Option stopKeyOption = Option.builder("stopKey").hasArg().desc(
            "secret key on startup which must also be present on the shutdown command to enhance security")
            .argName("stopKey").build();

    Option helpOption = Option.builder("help").desc("print help information").build();

    Option stopOption = Option.builder("stop").desc("stop server").build();

    cliOptions.addOption(helpOption);
    cliOptions.addOption(stopOption);
    cliOptions.addOption(portOption);
    cliOptions.addOption(contextPathOption);
    cliOptions.addOption(frontContextPathOption);
    cliOptions.addOption(portalContextPathOption);
    cliOptions.addOption(jettyEnvPathOption);
    cliOptions.addOption(jettyConfOption);
    cliOptions.addOption(stopPortOption);
    cliOptions.addOption(stopKeyOption);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;
    try {
        cmd = parser.parse(cliOptions, args);
    } catch (ParseException exp) {
        printHelp(formatter, cliOptions);
        return;
    }

    if (cmd.hasOption("help")) {
        printHelp(formatter, cliOptions);
    } else {
        int stopPort = -1;
        if (cmd.hasOption(stopPortOption.getOpt())) {
            try {
                stopPort = Integer.parseInt(cmd.getOptionValue(stopPortOption.getOpt()));
            } catch (NumberFormatException e) {
                System.out.println("stop port has to be number");
                printHelp(formatter, cliOptions);
                return;
            }
        }
        String stopKey = null;
        if (cmd.hasOption(stopKeyOption.getOpt())) {
            stopKey = cmd.getOptionValue(stopKeyOption.getOpt());
        }
        if (stopKey == null || stopKey.isEmpty()) {
            stopKey = DEFAULT_STOP_KEY;
        }
        if (cmd.hasOption("stop")) {
            if (stopPort <= 0) {
                System.out.println("stop port has to be a positive number");
                printHelp(formatter, cliOptions);
                return;
            }
            stop(stopPort, stopKey);
        } else {
            CubaJettyServer jettyServer = new CubaJettyServer();
            jettyServer.setStopPort(stopPort);
            jettyServer.setStopKey(stopKey);
            if (cmd.hasOption(portOption.getOpt())) {
                try {
                    jettyServer.setPort(Integer.parseInt(cmd.getOptionValue(portOption.getOpt())));
                } catch (NumberFormatException e) {
                    System.out.println("port has to be number");
                    printHelp(formatter, cliOptions);
                    return;
                }
            } else {
                jettyServer.setPort(getDefaultWebPort());
            }
            String contextPath = null;
            String frontContextPath = null;
            String portalContextPath = null;
            if (cmd.hasOption(contextPathOption.getOpt())) {
                String contextName = cmd.getOptionValue(contextPathOption.getOpt());
                if (contextName != null && !contextName.isEmpty()) {
                    if (PATH_DELIMITER.equals(contextName)) {
                        contextPath = PATH_DELIMITER;
                    } else {
                        contextPath = PATH_DELIMITER + contextName;
                    }
                }
            }
            if (cmd.hasOption(frontContextPathOption.getOpt())) {
                String contextName = cmd.getOptionValue(frontContextPathOption.getOpt());
                if (contextName != null && !contextName.isEmpty()) {
                    if (PATH_DELIMITER.equals(contextName)) {
                        frontContextPath = PATH_DELIMITER;
                    } else {
                        frontContextPath = PATH_DELIMITER + contextName;
                    }
                }
            }

            if (cmd.hasOption(portalContextPathOption.getOpt())) {
                String contextName = cmd.getOptionValue(portalContextPathOption.getOpt());
                if (contextName != null && !contextName.isEmpty()) {
                    if (PATH_DELIMITER.equals(contextName)) {
                        portalContextPath = PATH_DELIMITER;
                    } else {
                        portalContextPath = PATH_DELIMITER + contextName;
                    }
                }
            }

            if (contextPath == null) {
                String jarName = getJarName();
                if (jarName != null) {
                    jettyServer.setContextPath(PATH_DELIMITER + FilenameUtils.getBaseName(jarName));
                } else {
                    jettyServer.setContextPath(PATH_DELIMITER);
                }
            } else {
                jettyServer.setContextPath(contextPath);
            }
            if (frontContextPath == null) {
                if (PATH_DELIMITER.equals(contextPath)) {
                    jettyServer.setFrontContextPath(PATH_DELIMITER + "app-front");
                } else {
                    jettyServer.setFrontContextPath(jettyServer.getContextPath() + "-front");
                }
            } else {
                jettyServer.setFrontContextPath(frontContextPath);
            }
            if (portalContextPath == null) {
                if (PATH_DELIMITER.equals(contextPath)) {
                    jettyServer.setPortalContextPath(PATH_DELIMITER + "app-portal");
                } else {
                    jettyServer.setPortalContextPath(jettyServer.getContextPath() + "-portal");
                }
            } else {
                jettyServer.setPortalContextPath(frontContextPath);
            }

            if (cmd.hasOption(jettyEnvPathOption.getOpt())) {
                String jettyEnvPath = cmd.getOptionValue(jettyEnvPathOption.getOpt());
                if (jettyEnvPath != null && !jettyEnvPath.isEmpty()) {
                    File file = new File(jettyEnvPath);
                    if (!file.exists()) {
                        System.out.println("jettyEnvPath should point to an existing file");
                        printHelp(formatter, cliOptions);
                        return;
                    }
                    try {
                        jettyServer.setJettyEnvPathUrl(file.toURI().toURL());
                    } catch (MalformedURLException e) {
                        throw new RuntimeException("Unable to create jettyEnvPathUrl", e);
                    }
                }
            }

            if (cmd.hasOption(jettyConfOption.getOpt())) {
                String jettyConf = cmd.getOptionValue(jettyConfOption.getOpt());
                if (jettyConf != null && !jettyConf.isEmpty()) {
                    File file = new File(jettyConf);
                    if (!file.exists()) {
                        System.out.println("jettyConf should point to an existing file");
                        printHelp(formatter, cliOptions);
                        return;
                    }
                    try {
                        jettyServer.setJettyConfUrl(file.toURI().toURL());
                    } catch (MalformedURLException e) {
                        throw new RuntimeException("Unable to create jettyConfUrl", e);
                    }
                }
            } else {
                URL jettyConfUrl = getJettyConfUrl();
                if (jettyConfUrl != null) {
                    jettyServer.setJettyConfUrl(jettyConfUrl);
                }
            }
            System.out.println(format("Starting Jetty server on port: %s and contextPath: %s",
                    jettyServer.getPort(), jettyServer.getContextPath()));
            jettyServer.start();
        }
    }
}

From source file:nl.imvertor.common.Configurator.java

/**
 * Create parameters from arguments passed to the java application. 
 * Arguments are parsed by CLI conventions. 
 * Existing argument parameters are replaced.
 * //from  ww w.  j  a  v a2 s  .  c o  m
 * Parameters set from command line option are placed in /config/cli subelement and take the form 
 * /config/cli/parameter[@name]/text()  
 * 
 * @param options Command line options
 * @throws Exception 
 */
public void setParmsFromOptions(String[] args) throws Exception {
    CommandLine commandLine = null;
    File curFile = baseFolder;
    try {
        BasicParser parser = new BasicParser();
        commandLine = parser.parse(options, args);
        if (commandLine.hasOption("help"))
            dieOnCli(commandLine.getOptionValue("help"));
    } catch (ParseException e) {
        runner.error(logger, e.getMessage());
        dieOnCli("error");
    }

    @SuppressWarnings("unchecked")
    Iterator<Option> it = commandLine.iterator();
    while (it.hasNext()) {
        Option option = it.next();
        String optionName = option.getOpt();
        String[] v = commandLine.getOptionValues(optionName); // same option many times returns array of values.
        if (v.length > 1)
            throw new Exception("Duplicate argument -" + optionName + " on command line");
        if (optionName.equals("arguments"))
            loadFromPropertyFiles(curFile, v[0]);
        setParm(workConfiguration, "cli", optionName, v[0], true);
        setOptionIsReady(optionName, true);
    }

    String missing = checkOptionsAreReady();
    if (!missing.equals("")) {
        runner.error(logger, "Missing required parameters: " + missing);
        dieOnCli("program");
    }

    // record the metamodel used
    metamodel = getParm(workConfiguration, "cli", "metamodel", false);
    metamodel = (metamodel == null) ? DEFAULT_METAMODEL : metamodel;

    // schema rules used
    schemarules = getParm(workConfiguration, "cli", "schemarules", false);
    schemarules = (schemarules == null) ? DEFAULT_SCHEMARULES : schemarules;

    // set the task
    setParm(workConfiguration, "appinfo", "task", getParm(workConfiguration, "cli", "task", true), true);

    // If forced compilation, try all steps irrespective of any errors
    forceCompile = isTrue(getParm(workConfiguration, "cli", "forcecompile", true));

    // If documentation release, set the suffix for the application id
    String docReleaseString = getParm(workConfiguration, "cli", "docrelease", false);

    // if warnings should be signaled
    suppressWarnings = isTrue("cli", "suppresswarnings", false);

    docRelease = docReleaseString != null && !docReleaseString.equals("00000000");
    if (docRelease) {
        setParm("system", "documentation-release", "-" + docReleaseString);
    } else {
        setParm("system", "documentation-release", "");
    }

}

From source file:nl.systemsgenetics.eqtlinteractionanalyser.eqtlinteractionanalyser.createOptionsListForManual.java

/**
 * @param args the command line arguments
 *///ww  w .j a va  2  s. c om
public static void main(String[] args) {

    Options options = EQTLInteractionAnalyser.OPTIONS;

    System.out.println("| Short | Long | Description |");
    System.out.println("|-------|------|-------------|");

    for (Object optionO : options.getOptions()) {
        Option option = (Option) optionO;
        System.out.print("| -");
        System.out.print(option.getOpt());
        System.out.print(" | --");
        System.out.print(option.getLongOpt());
        System.out.print(" | ");
        System.out.print(option.getDescription());
        System.out.println(" | ");
    }

}

From source file:nl.toolforge.karma.console.CommandRenderer.java

private static StringBuffer printCommand(CommandDescriptor descriptor, Option[] options, boolean showOptions,
        boolean showHelp) {

    StringBuffer buffer = new StringBuffer();
    String commandNameAlias = descriptor.getName() + " (" + descriptor.getAlias() + ")";

    buffer.append(commandNameAlias).append(StringUtils.repeat(" ", COMMAND_FILL - commandNameAlias.length()));
    if (!showOptions) {
        buffer.append(descriptor.getDescription());
    }//from   ww w  .j ava  2s  .  com
    buffer.append("\n");

    if (showOptions) {
        for (int j = 0; j < options.length; j++) {

            Option o = options[j];

            String leftPadding = "   ";

            buffer.append(leftPadding).append("-" + o.getOpt()).append(", --" + o.getLongOpt());

            String args = "";
            if (o.hasArg()) {
                args = " <".concat(o.getArgName()).concat(">");
            }

            // todo when the commands are described with too much of text, then FILL will run out of count ...
            //
            buffer.append(args.concat(StringUtils.repeat(" ", OPTION_FILL - (o.getLongOpt() + args).length())));
            buffer.append(leftPadding);
            if (!o.isRequired()) {
                buffer.append("(Optional) ");
            }
            buffer.append(o.getDescription());
            buffer.append("\n");
        }
    }

    if (showHelp) {
        buffer.append("\n");

        String trimmed = NiftyStringUtils.deleteWhiteSpaceExceptOne(descriptor.getHelp());
        String[] split = NiftyStringUtils.split(trimmed, " ", 120);
        String joined = StringUtils.join(split, "\n");

        buffer.append(joined);
        buffer.append("\n");
    }

    return buffer;
}