Example usage for org.apache.commons.cli HelpFormatter printHelp

List of usage examples for org.apache.commons.cli HelpFormatter printHelp

Introduction

In this page you can find the example usage for org.apache.commons.cli HelpFormatter printHelp.

Prototype

public void printHelp(String cmdLineSyntax, Options options) 

Source Link

Document

Print the help for options with the specified command line syntax.

Usage

From source file:de.zib.chordsharp.Main.java

/**
 * Queries the command line options for an action to perform.
 * //from   ww  w .j  a  va2  s . c o m
 * <pre>
 * {@code
 * > java -jar chordsharp.jar -help
 * usage: chordsharp
 *  -getsubscribers <topic>   get subscribers of a topic
 *  -help                     print this message
 *  -publish <params>         publish a new message for a topic: <topic> <message>
 *  -read <key>               read an item
 *  -subscribe <params>       subscribe to a topic: <topic> <url>
 *  -unsubscribe <params>     unsubscribe from a topic: <topic> <url>
 *  -write <params>           write an item: <key> <value>
 *  -minibench                run mini benchmark
 * }
 * </pre>
 * 
 * @param args command line arguments
 */
public static void main(String[] args) {
    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        line = parser.parse(getOptions(), args);
    } catch (ParseException e) {
        System.err.println("Parsing failed. Reason: " + e.getMessage());
        System.exit(0);
    }

    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("chordsharp", getOptions());
        System.exit(0);
    }

    if (line.hasOption("minibench")) {
        minibench();
        System.exit(0);
    }

    if (line.hasOption("read")) {
        try {
            System.out.println("read(" + line.getOptionValue("read") + ") == "
                    + ChordSharp.read(line.getOptionValue("read")));
        } catch (ConnectionException e) {
            System.err.println("read failed: " + e.getMessage());
        } catch (TimeoutException e) {
            System.err.println("read failed with timeout: " + e.getMessage());
        } catch (NotFoundException e) {
            System.err.println("read failed with not found: " + e.getMessage());
        } catch (UnknownException e) {
            System.err.println("read failed with unknown: " + e.getMessage());
        }
    }
    if (line.hasOption("write")) {
        try {
            System.out.println("write(" + line.getOptionValues("write")[0] + ", "
                    + line.getOptionValues("write")[1] + ")");
            ChordSharp.write(line.getOptionValues("write")[0], line.getOptionValues("write")[1]);
        } catch (ConnectionException e) {
            System.err.println("write failed with connection error: " + e.getMessage());
        } catch (TimeoutException e) {
            System.err.println("write failed with timeout: " + e.getMessage());
        } catch (UnknownException e) {
            System.err.println("write failed with unknown: " + e.getMessage());
        }
    }
    if (line.hasOption("publish")) {
        try {
            System.out.println("publish(" + line.getOptionValues("publish")[0] + ", "
                    + line.getOptionValues("publish")[1] + ")");
            ChordSharp.publish(line.getOptionValues("publish")[0], line.getOptionValues("publish")[1]);
        } catch (ConnectionException e) {
            System.err.println("publish failed with connection error: " + e.getMessage());
            //         } catch (TimeoutException e) {
            //            System.err.println("publish failed with timeout: "
            //                  + e.getMessage());
            //         } catch (UnknownException e) {
            //            System.err.println("publish failed with unknown: "
            //                  + e.getMessage());
        }
    }
    if (line.hasOption("subscribe")) {
        try {
            System.out.println("subscribe(" + line.getOptionValues("subscribe")[0] + ", "
                    + line.getOptionValues("subscribe")[1] + ")");
            ChordSharp.subscribe(line.getOptionValues("subscribe")[0], line.getOptionValues("subscribe")[1]);
        } catch (ConnectionException e) {
            System.err.println("subscribe failed with connection error: " + e.getMessage());
        } catch (TimeoutException e) {
            System.err.println("subscribe failed with timeout: " + e.getMessage());
        } catch (UnknownException e) {
            System.err.println("subscribe failed with unknown: " + e.getMessage());
        }
    }
    if (line.hasOption("unsubscribe")) {
        try {
            System.out.println("unsubscribe(" + line.getOptionValues("unsubscribe")[0] + ", "
                    + line.getOptionValues("unsubscribe")[1] + ")");
            ChordSharp.unsubscribe(line.getOptionValues("unsubscribe")[0],
                    line.getOptionValues("unsubscribe")[1]);
        } catch (ConnectionException e) {
            System.err.println("unsubscribe failed with connection error: " + e.getMessage());
        } catch (TimeoutException e) {
            System.err.println("unsubscribe failed with timeout: " + e.getMessage());
        } catch (NotFoundException e) {
            System.err.println("unsubscribe failed with not found: " + e.getMessage());
        } catch (UnknownException e) {
            System.err.println("unsubscribe failed with unknown: " + e.getMessage());
        }
    }
    if (line.hasOption("getsubscribers")) {
        try {
            System.out.println("getSubscribers(" + line.getOptionValues("getsubscribers")[0] + ") == "
                    + ChordSharp.getSubscribers(line.getOptionValues("getsubscribers")[0]));
        } catch (ConnectionException e) {
            System.err.println("getSubscribers failed with connection error: " + e.getMessage());
            //         } catch (TimeoutException e) {
            //            System.err.println("getSubscribers failed with timeout: "
            //                  + e.getMessage());
        } catch (UnknownException e) {
            System.err.println("getSubscribers failed with unknown error: " + e.getMessage());
        }
    }
}

From source file:co.turnus.analysis.buffers.MpcBoundedSchedulingCliLauncher.java

public static void main(String[] args) {
    try {/*from w  w  w  . j ava2 s  .c o  m*/
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(cliOptions, args);
        Configuration config = parseCommandLine(cmd);

        // init models
        AnalysisActivator.init();

        // set logger verbosity
        if (config.getBoolean(VERBOSE, false)) {
            TurnusLogger.setLevel(TurnusLevel.ALL);
        }

        File tDir = new File(config.getString(TRACE_PROJECT));
        TraceProject project = TraceProject.load(tDir);

        MpcBoundedScheduling mpc = new MpcBoundedScheduling(project);
        mpc.setConfiguration(config);
        BufferMinimizationData data = mpc.run();

        TurnusLogger.info("Storing results...");
        File outPath = new File(config.getString(OUTPUT_PATH));

        // store the analysis report
        String uuid = UUID.randomUUID().toString();
        File rFile = new File(outPath, uuid + "." + TurnusExtension.REPORT);
        Report report = DataFactory.eINSTANCE.createReport();
        report.setDate(new Date());
        report.setComment("Report with only Bounded Buffer Scheduling results analysis");
        report.getDataSet().add(data);
        EcoreHelper.storeEObject(report, new ResourceSetImpl(), rFile);
        TurnusLogger.info("TURNUS report stored in " + rFile);

        // store formatted reports
        String xlsName = config.getString(XLS, "");
        if (!xlsName.isEmpty()) {
            File xlsFile = new File(outPath, xlsName + ".xls");
            new XlsBufferMinimizationDataWriter().write(data, xlsFile);
            TurnusLogger.info("XLS report stored in " + xlsFile);
        }

        String bxdfName = config.getString(BXDF, "");
        if (!bxdfName.isEmpty()) {
            File bxdfFile = new File(outPath, bxdfName + ".bxdf");
            new XmlBufferMinimizationDataWriter().write(data, bxdfFile);
            TurnusLogger.info("BXDF files (one for each configuration) " + "stored in " + outPath);
        }

        TurnusLogger.info("Analysis Done!");

    } catch (ParseException e) {
        TurnusLogger.error(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(AlgorithmicBottlenecksCliLauncher.class.getSimpleName(), cliOptions);
    } catch (Exception e) {
        TurnusLogger.error(e.getMessage());
    }
}

From source file:com.denimgroup.threadfix.cli.CommandLineParser.java

public static void main(String[] args) {

    Options options = getOptions();//from ww  w  . ja va2 s  . co m

    PosixParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar tfcli.jar", options);

        } else if (cmd.hasOption("s")) {

            String[] setArgs = cmd.getOptionValues("s");
            if (setArgs == null || setArgs.length != 2) {
                throw new ParseException("Bad arguments for set.");
            }

            if ("url".equals(setArgs[0])) {
                System.out.println("Setting URL to " + setArgs[1]);
                client.setUrl(setArgs[1]);
            } else if ("key".equals(setArgs[0])) {
                System.out.println("Setting API Key to " + setArgs[1]);
                client.setKey(setArgs[1]);
            } else {
                throw new ParseException("First argument to set must be url or key");
            }

        } else if (cmd.hasOption("ct")) {
            String[] createArgs = cmd.getOptionValues("ct");
            if (createArgs.length != 1) {
                throw new ParseException("Wrong number of arguments.");
            }
            System.out.println("Creating a Team with the name " + createArgs[0] + ".");
            System.out.println(client.createTeam(createArgs[0]));

        } else if (cmd.hasOption("cw")) {
            String[] createArgs = cmd.getOptionValues("cw");
            if (createArgs.length != 2) {
                throw new ParseException("Wrong number of arguments.");
            }
            System.out.println("Creating a Waf with the name " + createArgs[0] + ".");
            System.out.println(client.createWaf(createArgs[0], createArgs[1]));

        } else if (cmd.hasOption("ca")) {
            String[] createArgs = cmd.getOptionValues("ca");
            if (createArgs.length != 3) {
                throw new ParseException("Wrong number of arguments.");
            }
            System.out.println("Creating an Application with the name " + createArgs[1] + ".");
            System.out.println(client.createApplication(createArgs[0], createArgs[1], createArgs[2]));

        } else if (cmd.hasOption("teams")) {
            System.out.println("Getting all teams.");
            System.out.println(client.getAllTeams());

        } else if (cmd.hasOption("u")) {
            String[] uploadArgs = cmd.getOptionValues("u");
            // Upload a scan
            if (uploadArgs.length != 2) {
                throw new ParseException("Wrong number of arguments.");
            }
            System.out.println("Uploading " + uploadArgs[1] + " to Application " + uploadArgs[0] + ".");
            System.out.println(client.uploadScan(uploadArgs[0], uploadArgs[1]));

        } else if (cmd.hasOption("st")) {
            String[] searchArgs = cmd.getOptionValues("st");
            if (searchArgs.length != 2) {
                throw new ParseException("Wrong number of arguments.");
            }
            if ("id".equals(searchArgs[0])) {
                System.out.println("Searching for team with the id " + searchArgs[1] + ".");
                System.out.println(client.searchForTeamById(searchArgs[1]));
            } else if ("name".equals(searchArgs[0])) {
                System.out.println("Searching for team with the name " + searchArgs[1] + ".");
                System.out.println(client.searchForTeamByName(searchArgs[1]));
            } else {
                System.out.println("Unknown property argument. Try either id or name.");
                return;
            }

        } else if (cmd.hasOption("sw")) {
            String[] searchArgs = cmd.getOptionValues("sw");
            if (searchArgs.length != 4) {
                throw new ParseException("Wrong number of arguments.");
            }
            if ("id".equals(searchArgs[0])) {
                System.out.println("Searching for WAF with the id " + searchArgs[1] + ".");
                System.out.println(client.searchForWafById(searchArgs[1]));
            } else if ("name".equals(searchArgs[0])) {
                System.out.println("Searching for WAF with the name " + searchArgs[1] + ".");
                System.out.println(client.searchForWafByName(searchArgs[1]));
            } else {
                throw new ParseException("Unknown property argument. Try either id or name.");
            }

        } else if (cmd.hasOption("sa")) {
            String[] searchArgs = cmd.getOptionValues("sa");
            if ("id".equals(searchArgs[0])) {
                if (searchArgs.length != 2) {
                    System.out.println("Wrong number of arguments.");
                    return;
                }
                System.out.println("Searching for application with the id " + searchArgs[1] + ".");
                System.out.println(client.searchForApplicationById(searchArgs[1]));
            } else if ("name".equals(searchArgs[0])) {
                if (searchArgs.length != 3) {
                    System.out.println(
                            "Wrong number of arguments. You need to input application name and team name as well.");
                    return;
                }
                System.out.println("Searching for application with the name " + searchArgs[1] + " of team "
                        + searchArgs[2]);
                System.out.println(client.searchForApplicationByName(searchArgs[1], searchArgs[2]));
            } else {
                System.out.println("Unknown property argument. Try either id or name.");
                return;
            }

        } else if (cmd.hasOption("r")) {
            String[] ruleArgs = cmd.getOptionValues("r");
            if (ruleArgs.length != 1) {
                System.out.println("Wrong number of arguments.'");
            }
            System.out.println("Downloading rules from WAF with ID " + ruleArgs[0] + ".");
            System.out.println(client.getRules(ruleArgs[0]));

        } else {
            throw new ParseException("No arguments found.");
        }

    } catch (ParseException e) {
        if (e.getMessage() != null) {
            System.out.println(e.getMessage());
        }
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar tfcli.jar", options);
    }
}

From source file:com.ingby.socbox.bischeck.configuration.DocManager.java

/**
 * @param args//from   w  w w .  j av  a2  s. c o m
 */
public static void main(String[] args) {
    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    // create the Options
    Options options = new Options();
    options.addOption("u", "usage", false, "show usage.");
    options.addOption("d", "directory", true, "output directory");
    options.addOption("t", "type", true, "type of out put - html or csv");

    try {
        // parse the command line arguments
        line = parser.parse(options, args);

    } catch (org.apache.commons.cli.ParseException e) {
        System.out.println("Command parse error:" + e.getMessage());
        Util.ShellExit(FAILED);
    }

    if (line.hasOption("usage")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("DocManager", options);
        Util.ShellExit(OKAY);
    }

    DocManager dmgmt = null;

    if (line.hasOption("directory")) {
        String dirname = line.getOptionValue("directory");
        try {
            dmgmt = new DocManager(dirname);
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
            Util.ShellExit(FAILED);
        }
    } else {
        try {
            dmgmt = new DocManager();
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
            Util.ShellExit(FAILED);
        }
    }

    try {
        if (line.hasOption("type")) {
            String type = line.getOptionValue("type");
            if ("html".equalsIgnoreCase(type)) {
                dmgmt.genHtml();
            } else if ("text".equalsIgnoreCase(type)) {
                dmgmt.genText();
            }
        } else {
            dmgmt.genHtml();
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
        Util.ShellExit(FAILED);
    }
}

From source file:com.divinesoft.boynas.Boynas.java

public static void main(String args[]) {
    //TODO: Move Options to a different method
    Options options = new Options();

    //Create options
    Option list = OptionBuilder.withDescription("List all config entries in database").create("list");

    Option clean = OptionBuilder.withDescription("Remove all config entries in database").create("clean");

    Option importCSV = OptionBuilder.withArgName("file").hasArg()
            .withDescription("Import config entries from a CSV file").create("importCSV");

    Option exportXML = OptionBuilder.withDescription("Export all config entries to XML CFG files")
            .create("exportXML");

    Option exportTemplate = OptionBuilder.withArgName("templates folder").hasArgs()
            .withDescription("Export all config entries from a set of template files").create("exportTemplate");

    Option version = OptionBuilder.withDescription("Print the version number").create("version");

    Option quickGen = OptionBuilder.withArgName("import file,templates folder")
            .withDescription("Use a one-shot template based config generator").hasArgs(2)
            .withValueSeparator(' ').create("quickExport");

    //Add options
    options.addOption(list);/*from   ww w . ja va2 s.  c  om*/
    options.addOption(clean);
    options.addOption(importCSV);
    options.addOption(exportXML);
    options.addOption(exportTemplate);
    options.addOption(quickGen);
    options.addOption(version);

    CommandLineParser parser = new GnuParser();

    //The main Boynas object
    Boynas boynas;

    //Start dealing with application context
    XmlBeanFactory appContext = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));

    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("list")) {
            boynas = (Boynas) appContext.getBean("boynasList");
            boynas.getAllConfigEntries();
        } else if (cmd.hasOption("clean")) {
            boynas = (Boynas) appContext.getBean("boynasList");
            boynas.clean();
        } else if (cmd.hasOption("importCSV")) {
            Boynas.filePath = cmd.getOptionValue("importCSV");
            boynas = (Boynas) appContext.getBean("bynImportCSV");
            boynas.importCSV();
        } else if (cmd.hasOption("exportXML")) {
            boynas = (Boynas) appContext.getBean("bynExportXML");
            boynas.exportXML();
        } else if (cmd.hasOption("version")) {
            boynas = (Boynas) appContext.getBean("boynasList");
            boynas.printVersion();
        } else if (cmd.hasOption("exportTemplate")) {
            Boynas.templatePath = cmd.getOptionValue("exportTemplate");
            boynas = (Boynas) appContext.getBean("bynExportTemplate");
            boynas.exportTemplate();
        } else if (cmd.hasOption("quickExport")) {
            String[] paths = cmd.getOptionValues("quickExport");

            if (paths.length < 2) {
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("boynas", options);
            }

            Boynas.filePath = paths[0];
            Boynas.templatePath = paths[1];
            boynas = (Boynas) appContext.getBean("bynQuickExport");
            boynas.quickExport();
        }

        else {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("boynas", options);
        }

    } catch (ParseException e) {
        System.err.println("Parsing failed. Reason: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("boynas", options);
    }
}

From source file:com.evolveum.midpoint.testing.model.client.sample.Upload.java

public static void main(String[] args) {
    try {//from w ww .  j a  v  a  2  s  .  c  om

        Options options = new Options();
        options.addOption(OPT_HELP, "help", false, "Print this help information");
        options.addOption(OPT_FILE_TO_UPLOAD, "file", true, "File to be uploaded (XML for the moment)");
        options.addOption(OPT_DIR_TO_UPLOAD, "dir", true,
                "Whole directory to be uploaded (XML files only for the moment)");
        options.addOption(OPT_URL, true, "Endpoint URL (default: " + DEFAULT_ENDPOINT_URL + ")");
        options.addOption(OPT_USER, "user", true, "User name (default: " + ADM_USERNAME + ")");
        options.addOption(OPT_PASSWORD, "password", true, "Password");
        options.addOption(OPT_FILE_FOR_RESULT, "file-for-result", true,
                "Name of the file to write operation result into");
        options.addOption(OPT_HIDE_RESULT, "hide-result", false,
                "Don't display detailed operation result (default: showing if not SUCCESS)");
        options.addOption(OPT_SHOW_RESULT, "show-result", false,
                "Always show detailed operation result (default: showing if not SUCCESS)");
        CommandLineParser parser = new GnuParser();
        CommandLine cmdline = parser.parse(options, args);

        if (cmdline.hasOption(OPT_HELP)
                || (!cmdline.hasOption(OPT_FILE_TO_UPLOAD) && !cmdline.hasOption(OPT_DIR_TO_UPLOAD))) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("upload", options);
            System.out.println(
                    "\nNote that currently it is possible to upload only one object per file (i.e. no <objects> tag), and the "
                            + "file must be written using fully specified XML namespaces (i.e. namespace-guessing algorithm allowing to write data "
                            + "without namespaces is not available).");
            System.exit(-1);
        }

        System.out.println("=================================================================");

        ModelPortType modelPort = createModelPort(cmdline);
        if (cmdline.hasOption(OPT_FILE_TO_UPLOAD)) {
            uploadFile(new File(cmdline.getOptionValue(OPT_FILE_TO_UPLOAD)), cmdline, modelPort);
        }
        if (cmdline.hasOption(OPT_DIR_TO_UPLOAD)) {
            uploadDir(cmdline.getOptionValue(OPT_DIR_TO_UPLOAD), cmdline, modelPort);
        }

    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }

    if (error) {
        System.exit(-1);
    }
}

From source file:de.flashpixx.rrd_antlr4.CMain.java

/**
 * main/*from  w  ww .  jav a  2s  .c  o  m*/
 *
 * @param p_args command-line arguments
 * @throws IOException on any io error
 */
public static void main(final String[] p_args) throws IOException {
    // --- define CLI options ---
    final Options l_clioptions = new Options();
    l_clioptions.addOption("help", false, CCommon.languagestring(CMain.class, "help"));
    l_clioptions.addOption("output", true, CCommon.languagestring(CMain.class, "output", DEFAULTOUTPUT));
    l_clioptions.addOption("imports", true, CCommon.languagestring(CMain.class, "import"));
    l_clioptions.addOption("excludes", true, CCommon.languagestring(CMain.class, "exclude"));
    l_clioptions.addOption("grammar", true, CCommon.languagestring(CMain.class, "grammar"));
    l_clioptions.addOption("language", true, CCommon.languagestring(CMain.class, "language"));
    l_clioptions.addOption("docclean", true, CCommon.languagestring(CMain.class, "documentationclean"));
    l_clioptions.addOption("templates", true, CCommon.languagestring(CMain.class, "template",
            Arrays.asList(ETemplate.values()), DEFAULTTEMPLATE));

    final CommandLine l_cli;
    try {
        l_cli = new DefaultParser().parse(l_clioptions, p_args);
    } catch (final Exception l_exception) {
        System.err
                .println(CCommon.languagestring(CMain.class, "parseerror", l_exception.getLocalizedMessage()));
        System.exit(-1);
        return;
    }

    // --- process CLI arguments and push configuration ---
    if (l_cli.hasOption("help")) {
        final HelpFormatter l_formatter = new HelpFormatter();
        l_formatter.printHelp(
                new java.io.File(CMain.class.getProtectionDomain().getCodeSource().getLocation().getPath())
                        .getName(),
                l_clioptions);
        System.exit(0);
    }

    if (!l_cli.hasOption("grammar")) {
        System.err.println(CCommon.languagestring(CMain.class, "grammarnotset"));
        System.exit(-1);
    }

    final Tuple5<File, Set<ETemplate>, Set<File>, Set<String>, Set<String>> l_initdata = CMain.initialize(
            l_cli.getOptionValue("language"),

            l_cli.hasOption("output") ? l_cli.getOptionValue("output") : DEFAULTOUTPUT,

            l_cli.hasOption("templates") ? l_cli.getOptionValue("templates").split(",")
                    : new String[] { DEFAULTTEMPLATE },

            l_cli.getOptionValue("imports", "").split(","),

            l_cli.getOptionValue("excludes", "").split(","),

            l_cli.getOptionValue("docclean", "").split(","));

    // --- run generator ---
    final IGenerator l_generator = new CStandalone(l_initdata.v1(), l_initdata.v3(), l_initdata.v5(),
            l_initdata.v2());

    if (Arrays.stream(l_cli.getOptionValue("grammar").split(","))
            .flatMap(i -> CMain.filelist(new File(i.trim()), l_initdata.v3(), l_initdata.v4()))
            .map(i -> l_generator.generate(i).hasError()).findFirst().isPresent())
        System.exit(-1);

    l_generator.finish();
}

From source file:com.ingby.socbox.bischeck.test.JDBCtest.java

static public void main(String[] args)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {

    CommandLineParser parser = new GnuParser();
    CommandLine line = null;//from  ww  w . j  av  a  2s.c o m

    // create the Options
    Options options = new Options();
    options.addOption("u", "usage", false, "show usage.");
    options.addOption("c", "connection", true, "the connection url");
    options.addOption("s", "sql", true, "the sql statement to run");
    options.addOption("m", "meta", true, "get the table meta data");
    options.addOption("C", "columns", true, "the number of columns to display, default 1");
    options.addOption("d", "driver", true, "the driver class");
    options.addOption("v", "verbose", false, "verbose outbout");

    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (org.apache.commons.cli.ParseException e) {
        System.out.println("Command parse error:" + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("JDBCtest", options);
        Util.ShellExit(1);
    }

    if (line.hasOption("verbose")) {
        verbose = true;
    }

    if (line.hasOption("usage")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Bischeck", options);
        Util.ShellExit(0);
    }

    String driverclassname = null;
    if (!line.hasOption("driver")) {
        System.out.println("Driver class must be set");
        Util.ShellExit(1);
    } else {
        driverclassname = line.getOptionValue("driver");
        outputln("DriverClass: " + driverclassname);
    }

    String connectionname = null;
    if (!line.hasOption("connection")) {
        System.out.println("Connection url must be set");
        Util.ShellExit(1);
    } else {
        connectionname = line.getOptionValue("connection");
        outputln("Connection: " + connectionname);
    }

    String sql = null;
    String tablename = null;

    if (line.hasOption("sql")) {
        sql = line.getOptionValue("sql");
        outputln("SQL: " + sql);

    }

    if (line.hasOption("meta")) {
        tablename = line.getOptionValue("meta");
        outputln("Table: " + tablename);
    }

    int nrColumns = 1;
    if (line.hasOption("columns")) {
        nrColumns = new Integer(line.getOptionValue("columns"));
    }

    long execStart = 0l;
    long execEnd = 0l;
    long openStart = 0l;
    long openEnd = 0l;
    long metaStart = 0l;
    long metaEnd = 0l;

    Class.forName(driverclassname).newInstance();
    openStart = System.currentTimeMillis();
    Connection conn = DriverManager.getConnection(connectionname);
    openEnd = System.currentTimeMillis();

    if (tablename != null) {
        ResultSet rsCol = null;
        metaStart = System.currentTimeMillis();
        DatabaseMetaData md = conn.getMetaData();
        metaEnd = System.currentTimeMillis();

        rsCol = md.getColumns(null, null, tablename, null);
        if (verbose) {
            tabular("COLUMN_NAME");
            tabular("TYPE_NAME");
            tabular("COLUMN_SIZE");
            tabularlast("DATA_TYPE");
            outputln("");
        }

        while (rsCol.next()) {
            tabular(rsCol.getString("COLUMN_NAME"));
            tabular(rsCol.getString("TYPE_NAME"));
            tabular(rsCol.getString("COLUMN_SIZE"));
            tabularlast(rsCol.getString("DATA_TYPE"));
            outputln("", true);
        }
    }

    if (sql != null) {
        Statement stat = conn.createStatement();
        stat.setQueryTimeout(10);

        execStart = System.currentTimeMillis();
        ResultSet res = stat.executeQuery(sql);
        ResultSetMetaData rsmd = res.getMetaData();
        execEnd = System.currentTimeMillis();

        if (verbose) {
            for (int i = 1; i < nrColumns + 1; i++) {
                if (i != nrColumns)
                    tabular(rsmd.getColumnName(i));
                else
                    tabularlast(rsmd.getColumnName(i));
            }
            outputln("");
        }
        while (res.next()) {
            for (int i = 1; i < nrColumns + 1; i++) {
                if (i != nrColumns)
                    tabular(res.getString(i));
                else
                    tabularlast(res.getString(i));
            }
            outputln("", true);
        }

        stat.close();
        res.close();
    }

    conn.close();

    // Print the execution times
    outputln("Open time: " + (openEnd - openStart) + " ms");

    if (line.hasOption("meta")) {
        outputln("Meta time: " + (metaEnd - metaStart) + " ms");
    }

    if (line.hasOption("sql")) {
        outputln("Exec time: " + (execEnd - execStart) + " ms");
    }
}

From source file:com.google.testing.pogen.PageObjectGenerator.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    if (args.length == 0) {
        printUsage(System.out);/*from   w ww. ja v  a2 s. c o  m*/
        return;
    }

    String commandName = args[0];
    // @formatter:off
    Options options = new Options()
            .addOption(OptionBuilder.withDescription(
                    "Attribute name to be assigned in tagas containing template variables (default is 'id').")
                    .hasArg().withLongOpt("attr").create('a'))
            .addOption(OptionBuilder.withDescription("Print help for this command.").withLongOpt("help")
                    .create('h'))
            .addOption(OptionBuilder.withDescription("Print processed files verbosely.").withLongOpt("verbose")
                    .create('v'));
    // @formatter:on

    String helpMessage = null;
    if (commandName.equals(GENERATE_COMMAND)) {
        // @formatter:off
        options.addOption(OptionBuilder.withDescription("Package name of generating skeleton test code.")
                .hasArg().isRequired().withLongOpt("package").create('p'))
                .addOption(OptionBuilder.withDescription("Output directory of generating skeleton test code.")
                        .hasArg().isRequired().withLongOpt("out").create('o'))
                .addOption(OptionBuilder.withDescription(
                        "Root input directory of html template files for analyzing the suffixes of the package name.")
                        .hasArg().isRequired().withLongOpt("in").create('i'))
                .addOption(OptionBuilder.withDescription("Regex for finding html template files.").hasArg()
                        .withLongOpt("regex").create('e'))
                .addOption(OptionBuilder.withDescription("Option for finding html template files recursively.")
                        .withLongOpt("recursive").create('r'));
        // @formatter:on
        helpMessage = "java PageObjectGenerator generate -o <test_out_dir> -p <package_name> -i <root_directory> "
                + " [OPTIONS] <template_file1> <template_file2> ...\n"
                + "e.g. java PageObjectGenerator generate -a class -o PageObjectGeneratorTest/src/test/java/com/google/testing/pogen/pages"
                + " -i PageObjectGeneratorTest/src/main/resources -p com.google.testing.pogen.pages -e (.*)\\.html -v";
    } else if (commandName.equals(MEASURE_COMMAND)) {
        helpMessage = "java PageObjectGenerator measure [OPTIONS] <template_file1> <template_file2> ...";
    } else if (commandName.equals(LIST_COMMAND)) {
        helpMessage = "java PageObjectGenerator list <template_file1> <template_file2> ...";
    } else {
        System.err.format("'%s' is not a PageObjectGenerator command.", commandName);
        printUsage(System.err);
        System.exit(-1);
    }

    BasicParser cmdParser = new BasicParser();
    HelpFormatter f = new HelpFormatter();
    try {
        CommandLine cl = cmdParser.parse(options, Arrays.copyOfRange(args, 1, args.length));
        if (cl.hasOption('h')) {
            f.printHelp(helpMessage, options);
            return;
        }

        Command command = null;
        String[] templatePaths = cl.getArgs();
        String attributeName = cl.getOptionValue('a');
        attributeName = attributeName != null ? attributeName : "id";
        if (commandName.equals(GENERATE_COMMAND)) {
            String rootDirectoryPath = cl.getOptionValue('i');
            String templateFilePattern = cl.getOptionValue('e');
            boolean isRecusive = cl.hasOption('r');
            command = new GenerateCommand(templatePaths, cl.getOptionValue('o'), cl.getOptionValue('p'),
                    attributeName, cl.hasOption('v'), rootDirectoryPath, templateFilePattern, isRecusive);
        } else if (commandName.equals(MEASURE_COMMAND)) {
            command = new MeasureCommand(templatePaths, attributeName, cl.hasOption('v'));
        } else if (commandName.equals(LIST_COMMAND)) {
            command = new ListCommand(templatePaths, attributeName);
        }
        try {
            command.execute();
            return;
        } catch (FileProcessException e) {
            System.err.println(e.getMessage());
        } catch (IOException e) {
            System.err.println("Errors occur in processing files.");
            System.err.println(e.getMessage());
        }
    } catch (ParseException e) {
        System.err.println("Errors occur in parsing the command arguments.");
        System.err.println(e.getMessage());
        f.printHelp(helpMessage, options);
    }
    System.exit(-1);
}

From source file:de.prozesskraft.pkraft.Clone.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    /*----------------------------
      get options from ini-file//from w  w  w .  ja v a 2 s  .  com
    ----------------------------*/
    java.io.File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Clone.class) + "/" + "../etc/pkraft-clone.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option oinstance = OptionBuilder.withArgName("File").hasArg()
            .withDescription("[mandatory] process you want to clone.")
            //            .isRequired()
            .create("instance");

    Option obasedir = OptionBuilder.withArgName("DIR").hasArg().withDescription(
            "[optional, default: <basedirOfInstance>] base directory you want to place the root directory of the clone. this directory must exist at call time.")
            //            .isRequired()
            .create("basedir");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(oinstance);
    options.addOption(obasedir);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    // parse the command line arguments
    commandline = parser.parse(options, args);

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("clone", options);
        System.exit(0);
    }

    if (commandline.hasOption("v")) {
        System.out.println("author:  alexander.vogel@prozesskraft.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }
    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    if (!(commandline.hasOption("instance"))) {
        System.err.println("option -instance is mandatory");
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/
    String pathToInstance = commandline.getOptionValue("instance");
    java.io.File fileInstance = new java.io.File(pathToInstance);
    java.io.File fileBaseDir = null;

    // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen
    if (!fileInstance.exists()) {
        System.err.println("instance file does not exist.");
        exiter();
    }

    // testen ob eventuell vorhandene angaben basedir
    if (commandline.hasOption("basedir")) {
        fileBaseDir = new java.io.File(commandline.getOptionValue("basedir"));
        if (!fileBaseDir.exists()) {
            System.err.println("error: -basedir: directory does not exist");
            exiter();
        }
        if (!fileBaseDir.isDirectory()) {
            System.err.println("error: -basedir: is not a directory");
            exiter();
        }
    }

    // den main-prozess trotzdem nochmal einlesen um subprozesse extrahieren zu koennen
    Process p1 = new Process();
    p1.setInfilebinary(pathToInstance);
    Process process = p1.readBinary();

    // directories setzen, falls angegeben
    if (fileBaseDir != null) {
        process.setBaseDir(fileBaseDir.getCanonicalPath());
    }

    // den main-prozess ueber die static function klonen
    Process clonedProcess = cloneProcess(process, null);

    // alle steps durchgehen und falls subprocesses existieren auch fuer diese ein cloning durchfuehren
    for (Step actStep : process.getStep()) {
        if (actStep.getSubprocess() != null) {
            Process pDummy = new Process();
            pDummy.setInfilebinary(actStep.getAbsdir() + "/process.pmb");
            Process processInSubprocess = pDummy.readBinary();
            //            System.err.println("info: reading process freshly from file: " + actStep.getAbsdir() + "/process.pmb");
            if (processInSubprocess != null) {
                cloneProcess(processInSubprocess, clonedProcess);
            }
        }
    }
}