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

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

Introduction

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

Prototype

BasicParser

Source Link

Usage

From source file:com.svds.genericconsumer.main.GenericConsumerGroup.java

/**
 * Given command-line arguments, create GenericConsumerGroup
 * //from ww  w.ja  va2s  .  c o m
 * @param args  command-line arguments to parse
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    LOG.info("HELLO from main");

    Options options = new Options();
    options.addOption(OptionBuilder.isRequired().withLongOpt(ZOOKEEPER).withDescription("Zookeeper servers")
            .hasArg().create());

    options.addOption(OptionBuilder.isRequired().withLongOpt(GROUPID).withDescription("Kafka group id").hasArg()
            .create());

    options.addOption(OptionBuilder.isRequired().withLongOpt(TOPICNAME).withDescription("Kafka topic name")
            .hasArg().create());

    options.addOption(OptionBuilder.isRequired().withLongOpt(THREADS).withType(Number.class)
            .withDescription("Number of threads").hasArg().create());

    options.addOption(OptionBuilder.isRequired().withLongOpt(CONSUMERCLASS)
            .withDescription("Consumer Class from processing topic name").hasArg().create());

    options.addOption(OptionBuilder.withLongOpt(PARAMETERS)
            .withDescription("Parameters needed for the consumer Class if needed").hasArgs()
            .withValueSeparator(',').create());

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        LOG.error(e.getMessage(), e);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("GenericConsumerGroup.main", options);
        throw new IOException(e);
    }

    try {
        GenericConsumerGroup consumerGroupExample = new GenericConsumerGroup();
        consumerGroupExample.doWork(cmd);
    } catch (ParseException ex) {
        LOG.error("Error parsing command-line args");
        throw new IOException(ex);
    }
}

From source file:ed.manager.Manager.java

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

    HttpMonitor.setApplicationType("System Manager");

    Options o = new Options();
    o.addOption("v", "verbose", false, "Verbose");
    o.addOption("c", "config", true, "config file for TextConfigApplicationFactory");

    CommandLine cl = (new BasicParser()).parse(o, args);

    ApplicationFactory factory = null;//from  w w w .  j a  v a 2 s  .c  o  m
    if (cl.hasOption("config"))
        factory = new TextConfigApplicationFactory(new File(cl.getOptionValue("config", null)));
    else
        factory = new GridConfigApplicationFactory();

    Manager m = new Manager(factory, cl.hasOption("v"));
    m.start();
    m.join();
}

From source file:com.example.geomesa.authorizations.AuthorizationsTutorial.java

/**
 * Main entry point. Executes queries against an existing GDELT dataset.
 *
 * @param args//from  w  w  w  . j  a v  a 2s .  com
 *
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    // read command line options - this contains the connection to accumulo and the table to query
    CommandLineParser parser = new BasicParser();
    Options options = SetupUtil.getGeomesaDataStoreOptions();
    CommandLine cmd = parser.parse(options, args);

    // verify that we can see this Accumulo destination in a GeoTools manner
    Map<String, String> dsConf = SetupUtil.getAccumuloDataStoreConf(cmd);

    // get an instance of the data store that uses the default authorizations provider, which will use whatever auths the connector has available
    System.setProperty(AuthorizationsProvider.AUTH_PROVIDER_SYS_PROPERTY,
            DefaultAuthorizationsProvider.class.getName());
    DataStore authDataStore = DataStoreFinder.getDataStore(dsConf);
    assert authDataStore != null;

    // get another instance of the data store that uses our authorizations provider that always returns empty auths
    System.setProperty(AuthorizationsProvider.AUTH_PROVIDER_SYS_PROPERTY,
            EmptyAuthorizationsProvider.class.getName());
    DataStore noAuthDataStore = DataStoreFinder.getDataStore(dsConf);

    // create the simple feature type for our test
    String simpleFeatureTypeName = cmd.getOptionValue(SetupUtil.FEATURE_NAME);
    SimpleFeatureType simpleFeatureType = GdeltFeature.buildGdeltFeatureType(simpleFeatureTypeName);

    // execute the query, with and without visibilities
    System.out.println("\nExecuting query with AUTHORIZED data store: auths are '"
            + ((AccumuloDataStore) authDataStore).config().authProvider().getAuthorizations() + "'");
    executeQuery(simpleFeatureTypeName, authDataStore);
    System.out.println("Executing query with UNAUTHORIZED data store: auths are '"
            + ((AccumuloDataStore) noAuthDataStore).config().authProvider().getAuthorizations() + "'");
    executeQuery(simpleFeatureTypeName, noAuthDataStore);
}

From source file:geomesa.tutorial.AuthorizationsTutorial.java

/**
 * Main entry point. Executes queries against an existing GDELT dataset.
 *
 * @param args// ww w.  j  a va2 s. c  om
 *
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    // read command line options - this contains the connection to accumulo and the table to query
    CommandLineParser parser = new BasicParser();
    Options options = SetupUtil.getGeomesaDataStoreOptions();
    CommandLine cmd = parser.parse(options, args);

    // verify that we can see this Accumulo destination in a GeoTools manner
    Map<String, String> dsConf = SetupUtil.getAccumuloDataStoreConf(cmd);

    // get an instance of the data store that uses the default authorizations provider, which will use whatever auths the connector has available
    System.setProperty(AuthorizationsProvider.AUTH_PROVIDER_SYS_PROPERTY,
            DefaultAuthorizationsProvider.class.getName());
    DataStore authDataStore = DataStoreFinder.getDataStore(dsConf);
    assert authDataStore != null;

    // get another instance of the data store that uses our authorizations provider that always returns empty auths
    System.setProperty(AuthorizationsProvider.AUTH_PROVIDER_SYS_PROPERTY,
            EmptyAuthorizationsProvider.class.getName());
    DataStore noAuthDataStore = DataStoreFinder.getDataStore(dsConf);

    // create the simple feature type for our test
    String simpleFeatureTypeName = cmd.getOptionValue(SetupUtil.FEATURE_NAME);
    SimpleFeatureType simpleFeatureType = GdeltFeature.buildGdeltFeatureType(simpleFeatureTypeName);

    // execute the query, with and without visibilities
    System.out.println("\nExecuting query with AUTHORIZED data store: auths are '"
            + ((AccumuloDataStore) authDataStore).authorizationsProvider().getAuthorizations() + "'");
    executeQuery(simpleFeatureTypeName, authDataStore);
    System.out.println("Executing query with UNAUTHORIZED data store: auths are '"
            + ((AccumuloDataStore) noAuthDataStore).authorizationsProvider().getAuthorizations() + "'");
    executeQuery(simpleFeatureTypeName, noAuthDataStore);
}

From source file:com.esri.geoevent.test.tools.RunTcpInBdsOutTest.java

public static void main(String args[]) {

    // Example Command line args
    //-n 10000 -g w12ags104a.jennings.home -i 5565 -m https://w12ags104a.jennings.home/arcgis/rest/services/Hosted/FAA-Stream/MapServer/0 -f D:\github\performance-test-harness-for-geoevent\app\simulations\faa-stream.csv -r 1000,3000,1000

    int numberEvents = 10000; // Number of Events    
    String gisServer = "w12ags104a.jennings.home"; // GIS Server
    int inputTcpPort = 5565; // TCP Input Port       

    String msLayerUrl = "http://w12ags104a.jennings.home/arcgis/rest/services/Hosted/FAA-Stream/MapServer/0";

    String EventsInputFile = "D:\\github\\performance-test-harness-for-geoevent\\app\\simulations\\faa-stream.csv"; // Events input File        

    int start_rate = 5000;
    int end_rate = 5005;
    int rate_step = 1;

    Options opts = new Options();
    opts.addOption("n", true, "Number of Events");
    opts.addOption("g", true, "GIS Server");
    opts.addOption("i", true, "Input TCP Port");
    opts.addOption("m", true, "Map Service Layer URL");
    opts.addOption("f", true, "File with GeoEvents to Send");
    opts.addOption("r", true, "Rates to test Start,End,Step");
    opts.addOption("h", false, "Help");

    try {/*w ww . jav a2s  .  co m*/

        CommandLineParser parser = new BasicParser();
        CommandLine cmd = null;

        try {
            cmd = parser.parse(opts, args, false);
        } catch (org.apache.commons.cli.ParseException ignore) {
            System.err.println(ignore.getMessage());
        }

        String cmdInputErrorMsg = "";

        if (cmd.getOptions().length == 0 || cmd.hasOption("h")) {
            throw new org.apache.commons.cli.ParseException("Show Help");
        }

        if (cmd.hasOption("n")) {
            String val = cmd.getOptionValue("n");
            try {
                numberEvents = Integer.valueOf(val);
            } catch (NumberFormatException e) {
                cmdInputErrorMsg += "Invalid value for n. Must be integer.\n";
            }
        }

        if (cmd.hasOption("g")) {
            gisServer = cmd.getOptionValue("g");
        }

        if (cmd.hasOption("i")) {
            String val = cmd.getOptionValue("i");
            try {
                inputTcpPort = Integer.valueOf(val);
            } catch (NumberFormatException e) {
                cmdInputErrorMsg += "Invalid value for i. Must be integer.\n";
            }
        }

        if (cmd.hasOption("m")) {
            msLayerUrl = cmd.getOptionValue("m");
        }

        if (cmd.hasOption("f")) {
            EventsInputFile = cmd.getOptionValue("f");
        }

        if (cmd.hasOption("r")) {
            String val = cmd.getOptionValue("r");
            try {
                String parts[] = val.split(",");
                if (parts.length == 3) {
                    start_rate = Integer.parseInt(parts[0]);
                    end_rate = Integer.parseInt(parts[1]);
                    rate_step = Integer.parseInt(parts[2]);
                } else if (parts.length == 1) {
                    // Run single rate
                    start_rate = Integer.parseInt(parts[0]);
                    end_rate = start_rate;
                    rate_step = start_rate;
                } else {
                    throw new org.apache.commons.cli.ParseException(
                            "Rate must be three comma seperated values or a single value");
                }

            } catch (org.apache.commons.cli.ParseException e) {
                cmdInputErrorMsg += e.getMessage();
            } catch (NumberFormatException e) {
                cmdInputErrorMsg += "Invalid value for r. Must be integers.\n";
            }
        }

        if (!cmdInputErrorMsg.equalsIgnoreCase("")) {
            throw new org.apache.commons.cli.ParseException(cmdInputErrorMsg);
        }

        // Assuming the ES port is 9220 
        RunTcpInBdsOutTest t = new RunTcpInBdsOutTest();
        DecimalFormat df = new DecimalFormat("##0");

        if (start_rate == end_rate) {
            // Single Rate Test
            System.out.println("*********************************");
            System.out.println("Incremental testing at requested rate: " + start_rate);
            System.out.println("Count,Incremental Rate");

            t.runTest(numberEvents, start_rate, gisServer, inputTcpPort, EventsInputFile, msLayerUrl, true);
            if (t.send_rate < 0 || t.rcv_rate < 0) {
                throw new Exception("Test Run Failed!");
            }
            System.out.println("Overall Average Send Rate, Received Rate");
            System.out.println(df.format(t.send_rate) + "," + df.format(t.rcv_rate));

        } else {
            System.out.println("*********************************");
            System.out.println("rateRqstd,avgSendRate,avgRcvdRate");

            for (int rate = start_rate; rate <= end_rate; rate += rate_step) {

                t.runTest(numberEvents, rate, gisServer, inputTcpPort, EventsInputFile, msLayerUrl, false);
                if (t.send_rate < 0 || t.rcv_rate < 0) {
                    throw new Exception("Test Run Failed!");
                }
                System.out.println(
                        Integer.toString(rate) + "," + df.format(t.send_rate) + "," + df.format(t.rcv_rate));
                Thread.sleep(3 * 1000);
            }

        }

    } catch (ParseException e) {
        System.out.println("Invalid Command Options: ");
        System.out.println(e.getMessage());
        System.out.println(
                "Command line options: -n NumberOfEvents -g GISServer -i InputTCPPort -m MapServerLayerURL -f FileWithEvents -r StartRate,EndRate,Step");

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

From source file:de.uniwue.info2.main.CommandLineInterpreter.java

@SuppressWarnings("static-access")
public static void main(String[] args) {

    /*-------------------------------------------------------- */
    /*---------------SETTING TARGET LANGUAGE------------------ */
    /*-------------------------------------------------------- */
    LanguageFactory languageFactory = new LanguageFactory();

    CommandLine line = null;//from w ww  .  j  a  v a 2s  .c  o  m
    CommandLineParser parser = new BasicParser();
    Options options = new Options();
    // options to display in the help page
    Options options_short = new Options();

    // add help option
    Option help_option = new Option(HELP_OPTION_SHORT, HELP_OPTION, false, HELP_DESCRIPTION);
    options.addOption(help_option);
    options_short.addOption(help_option);
    // add extended help option
    Option help2_option = new Option(HELP2_OPTION_SHORT, HELP2_OPTION, false, HELP2_DESCRIPTION);
    options.addOption(help2_option);
    options_short.addOption(help2_option);
    // add optional operations option
    options.addOption(new Option(OPTIONAL_OPTION_SHORT, OPTIONAL_OPTION, false, OPTIONAL_DESCRIPTION));
    options.addOption(new Option(BIG_ENDIAN_OPTION_SHORT, BIG_ENDIAN_OPTION, false, BIG_ENDIAN_DESCRIPTION));
    options.addOption(
            new Option(LITTLE_ENDIAN_OPTION_SHORT, LITTLE_ENDIAN_OPTION, false, LITTLE_ENDIAN_DESCRIPTION));
    // add optional operations config option
    options.addOption(OptionBuilder.withLongOpt(OPTIONAL_FUNCTIONS_CONFIG_OPTION)
            .withArgName(OPTIONAL_FUNCTIONS_CONFIG_ARGUMENT)
            .withDescription(OPTIONAL_FUNCTIONS_CONFIG_DESCRIPTION).hasArg()
            .create(OPTIONAL_FUNCTIONS_CONFIG_SHORT));
    // add dsl option
    Option dsl_option = OptionBuilder.withLongOpt(DSL_OPTION).withArgName(DSL_ARGUMENT)
            .withDescription(DSL_DESCRIPTION).hasArg().isRequired().create(DSL_OPTION_SHORT);
    options.addOption(dsl_option);
    options_short.addOption(dsl_option);
    // add output-folder option
    Option output_option = OptionBuilder.withLongOpt(OUTPUT_OPTION).isRequired().withArgName(OUTPUT_ARGUMENT)
            .withDescription(OUTPUT_DESCRIPTION).hasArg().create(OUTPUT_OPTION_SHORT);
    options.addOption(output_option);
    options_short.addOption(output_option);

    // count possible language-specifications
    short optionCounter = 1;

    // get all possible language-specifications from language-factory and iterate through them
    List<LanguageSpecification> lSpecs = languageFactory.getAvailableLanguageSpecifications_();

    for (LanguageSpecification lSpec : lSpecs) {
        // get all possible unit-specifications for current language and iterate through them
        List<UnitTestLibrarySpecification> uSpecs = languageFactory
                .getAvailableUnitTestLibraries_(lSpec.getOptionName());
        String languageDescriptionAll = LANGUAGE_SPECIFICATION + lSpec.getLanguageName();
        String languageCounter = "s" + INDEX.format(optionCounter++);

        for (UnitTestLibrarySpecification uSpec : uSpecs) {
            // get all possible arithmetic-library-specifications for current language and iterate through
            // them
            List<ArithmeticLibrarySpecification> aSpecs = languageFactory
                    .getAvailableArithmeticLibraries_(lSpec.getOptionName());
            for (ArithmeticLibrarySpecification aSpec : aSpecs) {
                String languageDescription = "Generate unit-test for " + lSpec.getLanguageName() + "\n*["
                        + uSpec.getLibraryName() + " - " + uSpec.getVersion() + "]\n*[" + aSpec.getLibraryName()
                        + " - " + aSpec.getVersion() + "]";

                // if there is more than one option, generate suitable option-names and add them all to
                // commandline options
                if (uSpecs.size() > 1 || aSpecs.size() > 1) {
                    options.addOption(OptionBuilder
                            .withLongOpt(lSpec.getOptionName() + "_" + uSpec.getOptionName() + "_"
                                    + aSpec.getOptionName())
                            .withDescription(languageDescription).hasArg(false)
                            .create("s" + INDEX.format(optionCounter++)));
                } else {
                    // if there is only one option, use language-name as option-name
                    languageDescriptionAll = languageDescription;
                }
            }
            // add specifications to options
            options.addOption(OptionBuilder.withLongOpt(lSpec.getOptionName())
                    .withDescription(languageDescriptionAll).hasArg(false).create(languageCounter));
        }
    }

    /*-------------------------------------------------------- */
    /*-------------------PARSE USER INPUT--------------------- */
    /*-------------------------------------------------------- */
    try {
        // manual search for help-arguments
        for (String arg : args) {
            arg = arg.trim().replace("-", "");
            if (arg.equals(HELP_OPTION_SHORT) || arg.equals(HELP_OPTION)) {
                printHelp(options_short);
                return;
            }
            if (arg.equals(HELP2_OPTION_SHORT) || arg.equals(HELP2_OPTION)) {
                printExtendedHelp(options);
                return;
            }
        }

        // parse arguments   
        line = parser.parse(options, args);

        File dsl_file = null;
        File output_folder = null;
        File optional_config = null;
        Properties optional_operations = null;
        Boolean optional = false;
        Boolean little_endian = null;
        ArrayList<String> optional_exceptions = new ArrayList<String>();

        // if help-option found print help
        if (line.hasOption(HELP2_OPTION_SHORT) || args.length == 0) {
            printExtendedHelp(options);
            return;
        }

        // if help-option found print help
        if (line.hasOption(HELP_OPTION_SHORT) || args.length == 0) {
            System.out.println("\n");
            printHelp(options_short);
            return;
        }

        if (line.hasOption(OPTIONAL_OPTION_SHORT)) {
            optional = true;
        }

        if (line.hasOption(LITTLE_ENDIAN_OPTION)) {
            little_endian = true;
        }

        if (line.hasOption(BIG_ENDIAN_OPTION)) {
            little_endian = false;
        }

        // if dsl-option found, check if file exists and is readable
        // print help if error occurs
        if (line.hasOption(DSL_OPTION_SHORT)) {
            dsl_file = new File(line.getOptionValue(DSL_OPTION_SHORT));
            if (!dsl_file.exists()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - DSL-file doesn't exist:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (dsl_file.isDirectory()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - DSL-file is a directory:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (!dsl_file.canRead()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Need read-permission for DSL-file:\n"
                        + dsl_file + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            }
        }

        // if output-option found, check if folder exists and if write-permission was granted
        // print help if error occurs
        if (line.hasOption(OUTPUT_OPTION_SHORT)) {
            output_folder = new File(line.getOptionValue(OUTPUT_OPTION_SHORT));
            if (!output_folder.exists()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Output-folder doesn't exist:\n"
                        + output_folder + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (!output_folder.isDirectory()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Output-folder is not a directory:\n"
                        + output_folder + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (!output_folder.canWrite() || !output_folder.canRead()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Missing permissions for output-folder:\n"
                        + output_folder + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            }
        }

        if (line.hasOption(OPTIONAL_FUNCTIONS_CONFIG_SHORT)) {
            optional_config = new File(line.getOptionValue(OPTIONAL_FUNCTIONS_CONFIG_OPTION));
            if (!dsl_file.exists()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - config-file doesn't exist:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printExtendedHelp(options);
                return;
            } else if (dsl_file.isDirectory()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - config-file is a directory:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printExtendedHelp(options);
                return;
            } else if (!dsl_file.canRead()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Need read-permission for config-file:\n"
                        + dsl_file + "\n" + SEPERATOR + "\n");
                printExtendedHelp(options);
                return;
            }
        }

        if (optional_config != null) {
            optional_operations = new Properties();
            BufferedInputStream stream = new BufferedInputStream(new FileInputStream(optional_config));
            optional_operations.load(stream);
            stream.close();
            String optional_prop = optional_operations.getProperty("GENERATE_OPTIONAL");
            if (optional_prop != null) {
                if (optional_prop.trim().toLowerCase().equals("true")) {
                    optional = true;
                } else if (optional_prop.trim().toLowerCase().equals("false")) {
                    optional = false;
                } else if (!optional_prop.trim().isEmpty()) {
                    System.err.println("\n" + SEPERATOR + "\n"
                            + "ERROR - Syntax incorrect in config-file:\nUse \"true\" or \"false\" for \"GENERATE_OPTIONAL\"\n"
                            + SEPERATOR + "\n");
                    printExtendedHelp(options);
                    return;
                }
            }
            String exceptions = optional_operations.getProperty("EXCLUSIONS");
            if (exceptions != null) {
                for (String exc : optional_operations.getProperty("EXCLUSIONS").split(";")) {
                    optional_exceptions.add(exc.trim());
                }
            }
        }

        /*-------------------------------------------------------- */
        /*-------------------START GENERATING--------------------- */
        /*-------------------------------------------------------- */

        // instantiate generator for unit-tests
        TestcaseGenerator mainGenerator = new TestcaseGenerator(dsl_file, output_folder);

        boolean overrideDefaultSpecs = false;

        // check if user input contains a language-specifications
        // if user specified language, set overrideDefaultSpecs to true, so that only given specifications
        // are used
        for (int i = 1; i <= optionCounter; i++) {
            String opt = "s" + INDEX.format(i);
            if (line.hasOption(opt)) {
                LanguageSpecification targetSpecification = languageFactory
                        .getLanguageSpecification(options.getOption(opt).getLongOpt());
                String output = (GENERATING_DIALOG + targetSpecification.getLanguageName());

                // finally generate unit-test for current language-specification
                boolean successful = mainGenerator.generateUnitTest(targetSpecification, optional,
                        optional_exceptions, little_endian);

                if (successful) {
                    System.out.println(output + "\n--> Successfully generated.");
                } else {
                    System.err.println(output + "\n--> ERROR - see logfile");
                }
                overrideDefaultSpecs = true;
            }
        }

        // skip, if user already defined one language-specification
        // if user did not define language-specification, generate unit-tests for all
        // possible language-specifications (default)
        if (!overrideDefaultSpecs) {
            for (int i = 0; i < lSpecs.size(); i++) {
                LanguageSpecification specification = languageFactory
                        .getLanguageSpecification(lSpecs.get(i).getOptionName());

                String output = INDEX.format(i + 1) + " - " + GENERATING_DIALOG
                        + specification.getLanguageName();

                // finally generate unit-test for current language-specification
                boolean successful = mainGenerator.generateUnitTest(specification, optional,
                        optional_exceptions, little_endian);

                if (successful) {
                    System.out.println(output + "\n--> Successfully generated.");
                } else {
                    System.err.println(output + "\n--> ERROR - see logfile");
                }
            }
        }

    } catch (ParseException | IOException p) {
        System.err.println("\n" + SEPERATOR + "\n" + "ERROR - WRONG ARGUMENTS:\n" + p.getMessage() + "\n"
                + SEPERATOR + "\n");
        printHelp(options_short);
        System.out.println("\n");
    }
}

From source file:com.genentech.retrival.SDFExport.SDFSDFExporter.java

public static void main(String[] args) throws ParseException, JDOMException, IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option("sqlFile", true, "sql-xml file");
    opt.setRequired(false);//from   w w w  .  ja v a 2s . c o  m
    options.addOption(opt);

    opt = new Option("sqlName", true, "name of SQL element in xml file, Default sql.xml in 'sdfExport' config");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("selectStatement", true, "select statement to execute");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("paramTypes", true,
            "'|' separated list of parameter types to pass tostatment int,float,string,date");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("o", "out", true, "output file");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("i", "in", true,
            "input file, oe or .tab each record executes the query once. Use '.tab' to read from stdin");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("queryTags", true, "'|' separetaed list of tags whose values is passt to the sql.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("newLineReplacement", true,
            "If given newlines in fields will be replaced by this string.");
    options.addOption(opt);

    opt = new Option("filterIfNoRecords", false,
            "If no rows are returned by the query that record is filtered out.");
    options.addOption(opt);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }

    String outFile = cmd.getOptionValue("o");
    String inFile = cmd.getOptionValue("i");
    String sqlFile = cmd.getOptionValue("sqlFile");
    String sqlName = cmd.getOptionValue("sqlName");
    String selStr = cmd.getOptionValue("selectStatement");
    String pTypes = cmd.getOptionValue("paramTypes");
    String newLineReplacement = cmd.getOptionValue("newLineReplacement");
    boolean printIfNoRecord = !cmd.hasOption("filterIfNoRecords");
    String[] tagStr = cmd.getOptionValue("queryTags").trim().split("\\|");

    try {
        SDFSDFExporter exporter = null;
        if ((sqlFile != null && sqlFile.length() > 0) || (sqlName != null && sqlName.length() > 0)) {
            if ((selStr != null && selStr.length() > 0) || (pTypes != null && pTypes.length() > 0)) {
                System.err.println("sqlFile and sqlName may not be used with selectStatement and paramTypes");
                exitWithHelp(options);
            }

            exporter = createFromFile(sqlFile, sqlName, inFile, outFile, tagStr, printIfNoRecord,
                    newLineReplacement);

        } else if (selStr == null || selStr.length() == 0 || pTypes == null || pTypes.length() == 0) {
            System.err.println("sqlFile and sqlName or selectStatement and paramTypes must be given");
            exitWithHelp(options);

        } else {
            exporter = createFromStatementStr(selStr, pTypes, inFile, outFile, tagStr, printIfNoRecord,
                    newLineReplacement);
        }

        exporter.export();
        exporter.close();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println();
        exitWithHelp(options);
    }

}

From source file:com.jakev.dexdumpsql.App.java

public static void main(String[] args) {

    int rtn = 0;/*from www.  ja  v  a 2 s .  c  om*/

    String dexFileName = "";
    String dexDbName = "";
    int sdkVersion = 0;

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;

    gOptions.addOption("a", true, "Android API level to use.");
    gOptions.addOption("d", false, "Show debugging information.");
    gOptions.addOption("h", false, "Show help screen.");
    gOptions.addOption("i", true, "Input DEX/ODEX file.");
    gOptions.addOption("o", true, "Output DB file.");

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

        if (cmd.hasOption("h")) {
            usage();
            System.exit(0);
        }

        if (cmd.hasOption("d"))
            gDebug = true;

        if (!cmd.hasOption("i") || !cmd.hasOption("o") || !cmd.hasOption("a")) {
            System.err.println("[ERROR] Input, output, and API level parameters are required!");
            usage();
            System.exit(-1);
        }

    } catch (ParseException e) {
        System.err.println("[ERROR] Unable to parse command line properties: " + e);
        System.exit(-1);
    }

    dexFileName = cmd.getOptionValue("i");
    dexDbName = cmd.getOptionValue("o");

    try {
        sdkVersion = Integer.parseInt(cmd.getOptionValue("a"));
    } catch (NumberFormatException e) {
        System.err.println("[ERROR] Numeric API level required!");
        System.exit(-2);
    }

    if (!isFile(dexFileName)) {
        System.err.println("[ERROR] File '" + dexFileName + "' does not exist!");
        System.exit(-3);
    }

    if (gDebug) {
        System.out.println("Loading DEX into object.");
    }
    try {
        gDexFile = DexFileFactory.loadDexFile(dexFileName, sdkVersion);
    } catch (IOException e) {
        System.err.println("[ERROR] Unable to load DEX file!");
        System.exit(-4);
    }

    if (gDebug) {
        System.out.println("Creating DexDbHelper.");
    }
    gDexDb = new DexDbHelper(dexDbName);

    if (gDebug) {
        System.out.println("Droping data from DB (if exists).");
    }
    rtn = gDexDb.dropTables();
    if (rtn != 0) {
        System.err.println("[ERROR] Error dropping tables!");
        System.exit(rtn);
    }

    if (gDebug) {
        System.out.println("About to create tables...");
    }
    rtn = gDexDb.createTables();
    if (rtn != 0) {
        System.err.println("[ERROR] Error creating tables!");
        System.exit(rtn);
    }

    if (gDebug) {
        System.out.println("About to process DEX...");
    }
    rtn = processDex();
    if (rtn != 0) {
        System.err.println("[ERROR] Error processing dex!");
    }

    /* Close it down. */
    if (gDebug) {
        System.out.println("Closing database.");
    }
    rtn = gDexDb.closeDatabase();
    if (rtn != 0) {
        System.err.println("[ERROR] Could not close database!");
        System.exit(rtn);
    }
    System.exit(rtn);
}

From source file:com.github.r351574nc3.amex.assignment2.App.java

public static void main(final String... args) {
    if (args.length < 1) {
        printUsage();/*from   www. j a va  2 s. c  o m*/
        System.exit(0);
    }

    final Options options = new Options();
    options.addOption(OptionBuilder.withArgName("test").hasArg(true).isRequired(true)
            .withDescription("Path for ARFF test data").create("t"));
    options.addOption(OptionBuilder.withArgName("output").hasArg(true).isRequired(true)
            .withDescription("Path for ARFF output").create("o"));
    options.addOption(OptionBuilder.withArgName("input").hasArg(true).isRequired(true)
            .withDescription("Path for ARFF input").create("i"));

    final CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        printUsage();
        System.exit(0);
    }

    final String outputName = cmd.getOptionValue("o");
    final String inputName = cmd.getOptionValue("i");
    final String testName = cmd.getOptionValue("t");

    final App app = new App();
    try {
        if (args.length > 0) {
            app.setTrained(app.load(testName));
            app.setTest(app.load(testName));
        }
    } catch (Exception e) {
        error("There was an exception loading training and test datasets: %s", e.getMessage());
    }

    try {
        app.train();
        app.test();
    } catch (Exception e) {
        error("There was an exception testing the model: %s", e.getMessage());
    }

    try {
        app.predict(inputName, outputName);
    } catch (Exception e) {
        error("There was an exception predicting MPG: %s", e.getMessage());
        e.printStackTrace();
    }

    System.exit(0);

}

From source file:com.example.geomesa.kafka.KafkaLoadTester.java

public static void main(String[] args) throws Exception {
    // read command line args for a connection to Kafka
    CommandLineParser parser = new BasicParser();
    Options options = getCommonRequiredOptions();
    CommandLine cmd = parser.parse(options, args);
    String visibility = getVisibility(cmd);
    Integer delay = getDelay(cmd);

    if (visibility == null) {
        System.out.println("visibility: null");
    } else {/*from w  w w .j a va2 s  .  c  om*/
        System.out.println("visibility: '" + visibility + "'");
    }

    // create the producer and consumer KafkaDataStore objects
    Map<String, String> dsConf = getKafkaDataStoreConf(cmd);
    System.out.println("KDS config: " + dsConf);
    dsConf.put("kafka.consumer.count", "0");
    DataStore producerDS = DataStoreFinder.getDataStore(dsConf);
    dsConf.put("kafka.consumer.count", "1");
    DataStore consumerDS = DataStoreFinder.getDataStore(dsConf);

    // verify that we got back our KafkaDataStore objects properly
    if (producerDS == null) {
        throw new Exception("Null producer KafkaDataStore");
    }
    if (consumerDS == null) {
        throw new Exception("Null consumer KafkaDataStore");
    }

    try {
        // create the schema which creates a topic in Kafka
        // (only needs to be done once)
        final String sftName = "KafkaStressTest";
        final String sftSchema = "name:String,age:Int,step:Double,lat:Double,dtg:Date,*geom:Point:srid=4326";
        SimpleFeatureType sft = SimpleFeatureTypes.createType(sftName, sftSchema);
        producerDS.createSchema(sft);

        System.out.println("Register KafkaDataStore in GeoServer (Press enter to continue)");
        System.in.read();

        // the live consumer must be created before the producer writes features
        // in order to read streaming data.
        // i.e. the live consumer will only read data written after its instantiation
        SimpleFeatureStore producerFS = (SimpleFeatureStore) producerDS.getFeatureSource(sftName);
        SimpleFeatureSource consumerFS = consumerDS.getFeatureSource(sftName);

        // creates and adds SimpleFeatures to the producer every 1/5th of a second
        System.out.println("Writing features to Kafka... refresh GeoServer layer preview to see changes");

        SimpleFeatureBuilder builder = new SimpleFeatureBuilder(sft);

        Integer numFeats = getLoad(cmd);

        System.out.println("Building a list of " + numFeats + " SimpleFeatures.");
        List<SimpleFeature> features = IntStream.range(1, numFeats)
                .mapToObj(i -> createFeature(builder, i, visibility)).collect(Collectors.toList());

        // set variables to estimate feature production rate
        Long startTime = null;
        Long featuresSinceStartTime = 0L;
        int cycle = 0;
        int cyclesToSkip = 50000 / numFeats; // collect enough features
                                             // to get an accurate rate estimate

        while (true) {
            // write features
            features.forEach(feat -> {
                try {
                    DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();
                    featureCollection.add(feat);
                    producerFS.addFeatures(featureCollection);
                } catch (Exception e) {
                    System.out.println("Caught an exception while writing features.");
                    e.printStackTrace();
                }
                updateFeature(feat);
            });

            // count features written
            Integer consumerSize = consumerFS.getFeatures().size();
            cycle++;
            featuresSinceStartTime += consumerSize;
            System.out.println("At " + new Date() + " wrote " + consumerSize + " features");

            // if we've collected enough features, calculate the rate
            if (cycle >= cyclesToSkip || startTime == null) {
                Long endTime = System.currentTimeMillis();
                if (startTime != null) {
                    Long diffTime = endTime - startTime;
                    Double rate = (featuresSinceStartTime.doubleValue() * 1000.0) / diffTime.doubleValue();
                    System.out.printf("%.1f feats/sec (%d/%d)\n", rate, featuresSinceStartTime, diffTime);
                }
                cycle = 0;
                startTime = endTime;
                featuresSinceStartTime = 0L;
            }

            // sleep before next write
            if (delay != null) {
                System.out.printf("Sleeping for %d ms\n", delay);
                Thread.sleep(delay);
            }
        }

    } finally {
        producerDS.dispose();
        consumerDS.dispose();
    }
}