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

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

Introduction

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

Prototype

HelpFormatter

Source Link

Usage

From source file:eu.scape_project.pc.droid.cli.DroidCli.java

public static void main(String[] args) {
    // Static for command line option parsing
    DroidCli tc = new DroidCli();

    CommandLineParser cmdParser = new PosixParser();
    try {//from   w w  w  .j a v  a2s .  co  m
        CommandLine cmd = cmdParser.parse(OPTIONS, args);
        if ((args.length == 0) || (cmd.hasOption(HELP_OPT))) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(Constants.USAGE, OPTIONS, true);
            System.exit(0);
        } else {
            if (cmd.hasOption(DIR_OPT) && cmd.getOptionValue(DIR_OPT) != null) {
                String dirStr = cmd.getOptionValue(DIR_OPT);
                logger.info("Directory: " + dirStr);

                // *** start timer
                long startClock = System.currentTimeMillis();
                try {
                    tc.processFiles(new File(dirStr));

                } catch (FileNotFoundException ex) {
                    logger.error("File not found", ex);
                } catch (IOException ex) {
                    logger.error("I/O Exception", ex);
                }

                // *** stop timer
                long elapsedTimeMillis = System.currentTimeMillis() - startClock;
                logger.info("Identification finished after " + elapsedTimeMillis + " milliseconds");

            } else {
                logger.error("No directory given.");
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp(Constants.USAGE, OPTIONS, true);
                System.exit(1);
            }
        }
    } catch (ParseException ex) {
        logger.error("Problem parsing command line arguments.", ex);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Constants.USAGE, OPTIONS, true);
        System.exit(1);
    }
}

From source file:com.fiveclouds.jasper.JasperRunner.java

public static void main(String[] args) {

    // Set-up the options for the utility
    Options options = new Options();
    Option report = new Option("report", true, "jasper report to run (i.e. /path/to/report.jrxml)");
    options.addOption(report);// w w  w  .java  2  s. c  o  m

    Option driver = new Option("driver", true, "the jdbc driver class (i.e. com.mysql.jdbc.Driver)");
    driver.setRequired(true);
    options.addOption(driver);

    options.addOption("jdbcurl", true, "database jdbc url (i.e. jdbc:mysql://localhost:3306/database)");
    options.addOption("excel", true, "Will override the PDF default and export to Microsoft Excel");
    options.addOption("username", true, "database username");
    options.addOption("password", true, "database password");
    options.addOption("output", true, "the output filename (i.e. path/to/report.pdf");
    options.addOption("help", false, "print this message");

    Option propertyOption = OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator()
            .withDescription("use value as report property").create("D");

    options.addOption(propertyOption);

    // Parse the options and build the report
    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("jasper-runner", options);
        } else {

            System.out.println("Building report " + cmd.getOptionValue("report"));
            try {
                Class.forName(cmd.getOptionValue("driver"));
                Connection connection = DriverManager.getConnection(cmd.getOptionValue("jdbcurl"),
                        cmd.getOptionValue("username"), cmd.getOptionValue("password"));
                System.out.println("Connected to " + cmd.getOptionValue("jdbcurl"));
                JasperReport jasperReport = JasperCompileManager.compileReport(cmd.getOptionValue("report"));

                JRPdfExporter pdfExporter = new JRPdfExporter();

                Properties properties = cmd.getOptionProperties("D");
                Map<String, Object> parameters = new HashMap<String, Object>();

                Map<String, JRParameter> reportParameters = new HashMap<String, JRParameter>();

                for (JRParameter param : jasperReport.getParameters()) {
                    reportParameters.put(param.getName(), param);
                }

                for (Object propertyKey : properties.keySet()) {
                    String parameterName = String.valueOf(propertyKey);
                    String parameterValue = String.valueOf(properties.get(propertyKey));
                    JRParameter reportParam = reportParameters.get(parameterName);

                    if (reportParam != null) {
                        if (reportParam.getValueClass().equals(String.class)) {
                            System.out.println(
                                    "Property " + parameterName + " set to String = " + parameterValue);
                            parameters.put(parameterName, parameterValue);
                        } else if (reportParam.getValueClass().equals(Integer.class)) {
                            System.out.println(
                                    "Property " + parameterName + " set to Integer = " + parameterValue);
                            parameters.put(parameterName, Integer.parseInt(parameterValue));
                        } else {
                            System.err.print("Unsupported type for property " + parameterName);
                            System.exit(1);

                        }
                    } else {
                        System.out.println("Property " + parameterName + " not found in the report! IGNORING");

                    }
                }

                JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, connection);

                pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
                pdfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, cmd.getOptionValue("output"));
                System.out.println("Exporting report to " + cmd.getOptionValue("output"));
                pdfExporter.exportReport();
            } catch (JRException e) {
                System.err.print("Unable to parse report file (" + cmd.getOptionValue("r") + ")");
                e.printStackTrace();
                System.exit(1);
            } catch (ClassNotFoundException e) {
                System.err.print("Unable to find the database driver,  is it on the classpath?");
                e.printStackTrace();
                System.exit(1);
            } catch (SQLException e) {
                System.err.print("An SQL exception has occurred (" + e.getMessage() + ")");
                e.printStackTrace();
                System.exit(1);
            }
        }
    } catch (ParseException e) {
        System.err.print("Unable to parse command line options (" + e.getMessage() + ")");
        System.exit(1);
    }
}

From source file:com.jolbox.benchmark.BenchmarkLaunch.java

/**
 * @param args//  w  ww  .j av  a2s  . co m
 * @throws ClassNotFoundException 
 * @throws PropertyVetoException 
 * @throws SQLException 
 * @throws NoSuchMethodException 
 * @throws InvocationTargetException 
 * @throws IllegalAccessException 
 * @throws InterruptedException 
 * @throws SecurityException 
 * @throws IllegalArgumentException 
 * @throws NamingException 
 * @throws ParseException 
 * @throws IOException 
 */
public static void main(String[] args) throws ClassNotFoundException, SQLException, PropertyVetoException,
        IllegalArgumentException, SecurityException, InterruptedException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, NamingException, ParseException, IOException {

    Options options = new Options();
    options.addOption("t", "threads", true, "Max number of threads");
    options.addOption("s", "stepping", true, "Stepping of threads");
    options.addOption("p", "poolsize", true, "Pool size");
    options.addOption("h", "help", false, "Help");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("benchmark.jar", options);
        System.exit(1);
    }

    BenchmarkTests.threads = 400;
    BenchmarkTests.stepping = 5;
    BenchmarkTests.pool_size = 200;
    if (cmd.hasOption("t")) {
        BenchmarkTests.threads = Integer.parseInt(cmd.getOptionValue("t", "400"));
    }
    if (cmd.hasOption("s")) {
        BenchmarkTests.stepping = Integer.parseInt(cmd.getOptionValue("s", "20"));
    }
    if (cmd.hasOption("p")) {
        BenchmarkTests.pool_size = Integer.parseInt(cmd.getOptionValue("p", "200"));
    }

    System.out.println("Starting benchmark tests with " + BenchmarkTests.threads + " threads (stepping "
            + BenchmarkTests.stepping + ") using pool size of " + BenchmarkTests.pool_size + " connections");

    new MockJDBCDriver();
    BenchmarkTests tests = new BenchmarkTests();

    plotLineGraph(tests.testMultiThreadedConstantDelay(0), 0, false);
    plotLineGraph(tests.testMultiThreadedConstantDelay(10), 10, false);
    plotLineGraph(tests.testMultiThreadedConstantDelay(25), 25, false);
    plotLineGraph(tests.testMultiThreadedConstantDelay(50), 50, false);
    plotLineGraph(tests.testMultiThreadedConstantDelay(75), 75, false);

    plotBarGraph("Single Thread", "bonecp-singlethread-poolsize-" + BenchmarkTests.pool_size + "-threads-"
            + BenchmarkTests.threads + ".png", tests.testSingleThread());
    plotBarGraph(
            "Prepared Statement\nSingle Threaded", "bonecp-preparedstatement-single-poolsize-"
                    + BenchmarkTests.pool_size + "-threads-" + BenchmarkTests.threads + ".png",
            tests.testPreparedStatementSingleThread());
    plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(0), 0, true);
    plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(10), 10, true);
    plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(25), 25, true);
    plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(50), 50, true);
    plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(75), 75, true);

}

From source file:gov.lanl.adore.djatoka.DjatokaExtract.java

/**
 * Uses apache commons cli to parse input args. Passes parsed
 * parameters to IExtract implementation.
 * @param args command line parameters to defined input,output,etc.
 */// www .ja  va 2s  . c o m
public static void main(String[] args) {
    // create the command line parser
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();
    options.addOption("i", "input", true, "Filepath of the input file.");
    options.addOption("o", "output", true, "Filepath of the output file.");
    options.addOption("l", "level", true, "Resolution level to extract.");
    options.addOption("d", "reduce", true, "Resolution levels to subtract from max resolution.");
    options.addOption("r", "region", true, "Format: Y,X,H,W. ");
    options.addOption("c", "cLayer", true, "Compositing Layer Index.");
    options.addOption("s", "scale", true,
            "Format: Option 1. Define a long-side dimension (e.g. 96); Option 2. Define absolute w,h values (e.g. 1024,768); Option 3. Define a single dimension (e.g. 1024,0) with or without Level Parameter; Option 4. Use a single decimal scaling factor (e.g. 0.854)");
    options.addOption("t", "rotate", true, "Number of degrees to rotate image (i.e. 90, 180, 270).");
    options.addOption("f", "format", true,
            "Mimetype of the image format to be provided as response. Default: image/jpeg");
    options.addOption("a", "AltImpl", true, "Alternate IExtract Implemenation");

    try {
        if (args.length == 0) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("gov.lanl.adore.djatoka.DjatokaExtract", options);
            System.exit(0);
        }

        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String input = line.getOptionValue("i");
        String output = line.getOptionValue("o");

        DjatokaDecodeParam p = new DjatokaDecodeParam();
        String level = line.getOptionValue("l");
        if (level != null)
            p.setLevel(Integer.parseInt(level));
        String reduce = line.getOptionValue("d");
        if (level == null && reduce != null)
            p.setLevelReductionFactor(Integer.parseInt(reduce));
        String region = line.getOptionValue("r");
        if (region != null)
            p.setRegion(region);
        String cl = line.getOptionValue("c");
        if (cl != null) {
            int clayer = Integer.parseInt(cl);
            if (clayer > 0)
                p.setCompositingLayer(clayer);
        }
        String scale = line.getOptionValue("s");
        if (scale != null) {
            String[] v = scale.split(",");
            if (v.length == 1) {
                if (v[0].contains("."))
                    p.setScalingFactor(Double.parseDouble(v[0]));
                else {
                    int[] dims = new int[] { -1, Integer.parseInt(v[0]) };
                    p.setScalingDimensions(dims);
                }
            } else if (v.length == 2) {
                int[] dims = new int[] { Integer.parseInt(v[0]), Integer.parseInt(v[1]) };
                p.setScalingDimensions(dims);
            }
        }
        String rotate = line.getOptionValue("t");
        if (rotate != null)
            p.setRotationDegree(Integer.parseInt(rotate));
        String format = line.getOptionValue("f");
        if (format == null)
            format = "image/jpeg";
        String alt = line.getOptionValue("a");
        if (output == null)
            output = input + ".jpg";

        long x = System.currentTimeMillis();
        IExtract ex = new KduExtractExe();
        if (alt != null)
            ex = (IExtract) Class.forName(alt).newInstance();
        DjatokaExtractProcessor e = new DjatokaExtractProcessor(ex);
        e.extractImage(input, output, p, format);
        logger.info("Extraction Time: " + ((double) (System.currentTimeMillis() - x) / 1000) + " seconds");

    } catch (ParseException e) {
        logger.error("Parse exception:" + e.getMessage(), e);
    } catch (DjatokaException e) {
        logger.error("djatoka Extraction exception:" + e.getMessage(), e);
    } catch (InstantiationException e) {
        logger.error("Unable to initialize alternate implemenation:" + e.getMessage(), e);
    } catch (Exception e) {
        logger.error("Unexpected exception:" + e.getMessage(), e);
    }
}

From source file:de.topobyte.livecg.LiveCG.java

public static void main(String[] args) {
    // @formatter:off
    Options options = new Options();
    OptionHelper.add(options, OPTION_CONFIG, true, false, "path", "config file");
    // @formatter:on

    CommandLineParser clp = new GnuParser();

    CommandLine line = null;/*from  w w w  . java2s  .  c om*/
    try {
        line = clp.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Parsing command line failed: " + e.getMessage());
        new HelpFormatter().printHelp(HELP_MESSAGE, options);
        System.exit(1);
    }

    StringOption config = ArgumentHelper.getString(line, OPTION_CONFIG);
    if (config.hasValue()) {
        String configPath = config.getValue();
        LiveConfig.setPath(configPath);
    }

    Configuration configuration = PreferenceManager.getConfiguration();
    String lookAndFeel = configuration.getSelectedLookAndFeel();
    if (lookAndFeel == null) {
        lookAndFeel = UIManager.getSystemLookAndFeelClassName();
    }
    try {
        UIManager.setLookAndFeel(lookAndFeel);
    } catch (Exception e) {
        logger.error("error while setting look and feel '" + lookAndFeel + "': " + e.getClass().getSimpleName()
                + ", message: " + e.getMessage());
    }

    Content content = null;
    String filename = "res/presets/Startup.geom";

    String[] extra = line.getArgs();
    if (extra.length > 0) {
        filename = extra[0];
    }

    ContentReader reader = new ContentReader();
    InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
    try {
        content = reader.read(input);
    } catch (Exception e) {
        logger.info("unable to load startup geometry file", e);
        logger.info("Exception: " + e.getClass().getSimpleName());
        logger.info("Message: " + e.getMessage());
    }

    final LiveCG runner = new LiveCG();
    final Content c = content;

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            runner.setup(true, c);
        }
    });
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            runner.frame.requestFocus();
        }
    });
}

From source file:com.mebigfatguy.roomstore.RoomStore.java

public static void main(String[] args) {
    Options options = createOptions();/*w w  w.j a  v  a2  s . c  om*/

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cmdLine = parser.parse(options, args);
        String nickname = cmdLine.getOptionValue(NICK_NAME);
        String server = cmdLine.getOptionValue(IRCSERVER);
        String[] channels = cmdLine.getOptionValues(CHANNELS);
        String[] endPoints = cmdLine.getOptionValues(ENDPOINTS);
        String rf = cmdLine.getOptionValue(RF);

        if ((endPoints == null) || (endPoints.length == 0)) {
            endPoints = new String[] { "127.0.0.1" };
        }

        int replicationFactor;
        try {
            replicationFactor = Integer.parseInt(rf);
        } catch (Exception e) {
            replicationFactor = 1;
        }

        final IRCConnector connector = new IRCConnector(nickname, server, channels);

        Cluster cluster = new Cluster.Builder().addContactPoints(endPoints).build();
        final Session session = cluster.connect();

        CassandraWriter writer = new CassandraWriter(session, replicationFactor);
        connector.setWriter(writer);

        connector.startRecording();

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                connector.stopRecording();
                session.close();
            }
        }));

    } catch (ParseException pe) {
        System.out.println("Parse Error on command line options:");
        System.out.println(commandLineRepresentation(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("roomstore", options);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

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

    /*----------------------------
      get options from ini-file/*w  w  w .  j  a v a  2  s  .  co m*/
    ----------------------------*/
    File inifile = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Checkconsistency.class) + "/"
            + "../etc/pkraft-checkconsistency.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 odefinition = OptionBuilder.withArgName("definition").hasArg()
            .withDescription("[mandatory] process model in xml format.")
            //            .isRequired()
            .create("definition");

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

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(odefinition);

    /*----------------------------
      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("startinstance", 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("definition"))) {
        System.out.println("option -definition 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
    ----------------------------*/

    Process p1 = new Process();

    p1.setInfilexml(commandline.getOptionValue("definition"));
    Process p2;
    try {
        p2 = p1.readXml();

        if (p2.isProcessConsistent()) {
            System.out.println("process structure is consistent.");
        } else {
            System.out.println("process structure is NOT consistent.");
        }

        p2.printLog();

    } catch (JAXBException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

From source file:cnxchecker.Client.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("H", "host", true, "Remote IP address");
    options.addOption("p", "port", true, "Remote TCP port");
    options.addOption("s", "size", true, "Packet size in bytes (1 KiB)");
    options.addOption("f", "freq", true, "Packets per seconds  (1 Hz)");
    options.addOption("w", "workers", true, "Number of Workers (1)");
    options.addOption("d", "duration", true, "Duration of the test in seconds (60 s)");
    options.addOption("h", "help", false, "Print help");
    CommandLineParser parser = new GnuParser();
    try {/*from w w w  .  j a  v  a 2  s . c om*/
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("h")) {
            HelpFormatter hf = new HelpFormatter();
            hf.printHelp("client", options);
            System.exit(0);
        }

        // host
        InetAddress ia = null;
        if (cmd.hasOption("H")) {
            String host = cmd.getOptionValue("H");

            try {
                ia = InetAddress.getByName(host);
            } catch (UnknownHostException e) {
                printAndExit("Unknown host: " + host);
            }
        } else {
            printAndExit("Host option is mandatory");
        }

        // port
        int port = 0;
        if (cmd.hasOption("p")) {
            try {
                port = Integer.parseInt(cmd.getOptionValue("p"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid port number " + cmd.getOptionValue("p"));
            }

            if (port < 0 || port > 65535) {
                printAndExit("Invalid port number " + port);
            }
        }

        // size
        int size = 1024;
        if (cmd.hasOption("s")) {
            try {
                size = Integer.parseInt(cmd.getOptionValue("s"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid packet size " + cmd.getOptionValue("s"));
            }

            if (size < 0) {
                printAndExit("Invalid packet size: " + port);
            }
        }

        // freq
        double freq = 1;
        if (cmd.hasOption("f")) {
            try {
                freq = Double.parseDouble(cmd.getOptionValue("f"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid frequency: " + cmd.getOptionValue("f"));
            }

            if (freq <= 0) {
                printAndExit("Invalid frequency: " + freq);
            }
        }

        // workers
        int workers = 1;
        if (cmd.hasOption("w")) {
            try {
                workers = Integer.parseInt(cmd.getOptionValue("w"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid number of workers: " + cmd.getOptionValue("w"));
            }

            if (workers < 0) {
                printAndExit("Invalid number of workers: " + workers);
            }
        }

        // duration
        int duration = 60000;
        if (cmd.hasOption("d")) {
            try {
                duration = Integer.parseInt(cmd.getOptionValue("d")) * 1000;
            } catch (NumberFormatException e) {
                printAndExit("Invalid duration: " + cmd.getOptionValue("d"));
            }

            if (duration < 0) {
                printAndExit("Invalid duration: " + duration);
            }
        }

        Client client = new Client(ia, port, size, freq, workers, duration);
        client.doit();
    } catch (ParseException e) {
        printAndExit("Failed to parse options: " + e.getMessage());
    }

    System.exit(0);
}

From source file:io.druid.server.sql.SQLRunner.java

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

    Options options = new Options();
    options.addOption("h", "help", false, "help");
    options.addOption("v", false, "verbose");
    options.addOption("e", "host", true, "endpoint [hostname:port]");

    CommandLine cmd = new GnuParser().parse(options, args);

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("SQLRunner", options);
        System.exit(2);//from   w w w . java2 s  . co  m
    }

    String hostname = cmd.getOptionValue("e", "localhost:8080");
    String sql = cmd.getArgs().length > 0 ? cmd.getArgs()[0] : STATEMENT;

    ObjectMapper objectMapper = new DefaultObjectMapper();
    ObjectWriter jsonWriter = objectMapper.writerWithDefaultPrettyPrinter();

    CharStream stream = new ANTLRInputStream(sql);
    DruidSQLLexer lexer = new DruidSQLLexer(stream);
    TokenStream tokenStream = new CommonTokenStream(lexer);
    DruidSQLParser parser = new DruidSQLParser(tokenStream);
    lexer.removeErrorListeners();
    parser.removeErrorListeners();

    lexer.addErrorListener(ConsoleErrorListener.INSTANCE);
    parser.addErrorListener(ConsoleErrorListener.INSTANCE);

    try {
        DruidSQLParser.QueryContext queryContext = parser.query();
        if (parser.getNumberOfSyntaxErrors() > 0)
            throw new IllegalStateException();
        //      parser.setBuildParseTree(true);
        //      System.err.println(q.toStringTree(parser));
    } catch (Exception e) {
        String msg = e.getMessage();
        if (msg != null)
            System.err.println(e);
        System.exit(1);
    }

    final Query query;
    final TypeReference typeRef;
    boolean groupBy = false;
    if (parser.groupByDimensions.isEmpty()) {
        query = Druids.newTimeseriesQueryBuilder().dataSource(parser.getDataSource())
                .aggregators(new ArrayList<AggregatorFactory>(parser.aggregators.values()))
                .postAggregators(parser.postAggregators).intervals(parser.intervals)
                .granularity(parser.granularity).filters(parser.filter).build();

        typeRef = new TypeReference<List<Result<TimeseriesResultValue>>>() {
        };
    } else {
        query = GroupByQuery.builder().setDataSource(parser.getDataSource())
                .setAggregatorSpecs(new ArrayList<AggregatorFactory>(parser.aggregators.values()))
                .setPostAggregatorSpecs(parser.postAggregators).setInterval(parser.intervals)
                .setGranularity(parser.granularity).setDimFilter(parser.filter)
                .setDimensions(new ArrayList<DimensionSpec>(parser.groupByDimensions.values())).build();

        typeRef = new TypeReference<List<Row>>() {
        };
        groupBy = true;
    }

    String queryStr = jsonWriter.writeValueAsString(query);
    if (cmd.hasOption("v"))
        System.err.println(queryStr);

    URL url = new URL(String.format("http://%s/druid/v2/?pretty", hostname));
    final URLConnection urlConnection = url.openConnection();
    urlConnection.addRequestProperty("content-type", MediaType.APPLICATION_JSON);
    urlConnection.getOutputStream().write(StringUtils.toUtf8(queryStr));
    BufferedReader stdInput = new BufferedReader(
            new InputStreamReader(urlConnection.getInputStream(), Charsets.UTF_8));

    Object res = objectMapper.readValue(stdInput, typeRef);

    Joiner tabJoiner = Joiner.on("\t");

    if (groupBy) {
        List<Row> rows = (List<Row>) res;
        Iterable<String> dimensions = Iterables.transform(parser.groupByDimensions.values(),
                new Function<DimensionSpec, String>() {
                    @Override
                    public String apply(@Nullable DimensionSpec input) {
                        return input.getOutputName();
                    }
                });

        System.out.println(
                tabJoiner.join(Iterables.concat(Lists.newArrayList("timestamp"), dimensions, parser.fields)));
        for (final Row r : rows) {
            System.out.println(tabJoiner.join(Iterables.concat(
                    Lists.newArrayList(parser.granularity.toDateTime(r.getTimestampFromEpoch())),
                    Iterables.transform(parser.groupByDimensions.values(),
                            new Function<DimensionSpec, String>() {
                                @Override
                                public String apply(@Nullable DimensionSpec input) {
                                    return Joiner.on(",").join(r.getDimension(input.getOutputName()));
                                }
                            }),
                    Iterables.transform(parser.fields, new Function<String, Object>() {
                        @Override
                        public Object apply(@Nullable String input) {
                            return r.getFloatMetric(input);
                        }
                    }))));
        }
    } else {
        List<Result<TimeseriesResultValue>> rows = (List<Result<TimeseriesResultValue>>) res;
        System.out.println(tabJoiner.join(Iterables.concat(Lists.newArrayList("timestamp"), parser.fields)));
        for (final Result<TimeseriesResultValue> r : rows) {
            System.out.println(tabJoiner.join(Iterables.concat(Lists.newArrayList(r.getTimestamp()),
                    Lists.transform(parser.fields, new Function<String, Object>() {
                        @Override
                        public Object apply(@Nullable String input) {
                            return r.getValue().getMetric(input);
                        }
                    }))));
        }
    }

    CloseQuietly.close(stdInput);
}

From source file:net.mmberg.nadia.processor.NadiaProcessor.java

/**
 * @param args/*  w w w.  ja  va2  s.  co  m*/
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {

    Class<? extends UserInterface> ui_class = ConsoleInterface.class; //default UI
    String dialog_file = default_dialog; //default dialogue

    //process command line args
    Options cli_options = new Options();
    cli_options.addOption("h", "help", false, "print this message");
    cli_options.addOption(OptionBuilder.withLongOpt("interface").withDescription("select user interface")
            .hasArg(true).withArgName("console, rest").create("i"));
    cli_options.addOption("f", "file", true, "specify dialogue path and file, e.g. -f /res/dialogue1.xml");
    cli_options.addOption("r", "resource", true, "load dialogue (by name) from resources, e.g. -r dialogue1");
    cli_options.addOption("s", "store", true, "load dialogue (by name) from internal store, e.g. -s dialogue1");

    CommandLineParser parser = new org.apache.commons.cli.BasicParser();
    try {
        CommandLine cmd = parser.parse(cli_options, args);

        //Help
        if (cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("nadia", cli_options, true);
            return;
        }

        //UI
        if (cmd.hasOption("i")) {
            String interf = cmd.getOptionValue("i");
            if (interf.equals("console"))
                ui_class = ConsoleInterface.class;
            else if (interf.equals("rest"))
                ui_class = RESTInterface.class;
        }

        //load dialogue from path file
        if (cmd.hasOption("f")) {
            dialog_file = "file:///" + cmd.getOptionValue("f");
        }
        //load dialogue from resources
        if (cmd.hasOption("r")) {
            dialog_file = config.getProperty(NadiaProcessorConfig.DIALOGUEDIR) + "/" + cmd.getOptionValue("r")
                    + ".xml";
        }
        //load dialogue from internal store
        if (cmd.hasOption("s")) {
            Dialog store_dialog = DialogStore.getInstance().getDialogFromStore((cmd.getOptionValue("s")));
            store_dialog.save();
            dialog_file = config.getProperty(NadiaProcessorConfig.DIALOGUEDIR) + "/" + cmd.getOptionValue("s")
                    + ".xml";
        }

    } catch (ParseException e1) {
        logger.severe("NADIA: loading by main-method failed. " + e1.getMessage());
        e1.printStackTrace();
    }

    //start Nadia with selected UI
    default_dialog = dialog_file;
    NadiaProcessor nadia = new NadiaProcessor();
    try {
        ui = ui_class.newInstance();
        ui.register(nadia);
        ui.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}