Example usage for java.lang Integer parseInt

List of usage examples for java.lang Integer parseInt

Introduction

In this page you can find the example usage for java.lang Integer parseInt.

Prototype

public static int parseInt(String s) throws NumberFormatException 

Source Link

Document

Parses the string argument as a signed decimal integer.

Usage

From source file:HelloSmartsheet.java

public static void main(String[] args) {
    HttpURLConnection connection = null;
    StringBuilder response = new StringBuilder();

    //We are using Jackson JSON parser to deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome
    //Feel free to use which ever library you prefer.
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    try {//from   w ww. ja  v  a 2 s .co m

        System.out.println("STARTING HelloSmartsheet...");
        //Create a BufferedReader to read user input.
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter Smartsheet API access token:");
        String accessToken = in.readLine();
        System.out.println("Fetching list of your sheets...");
        //Create a connection and fetch the list of sheets
        connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        //Read the response line by line.
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        //Use Jackson to conver the JSON string to a List of Sheets
        List<Sheet> sheets = mapper.readValue(response.toString(), new TypeReference<List<Sheet>>() {
        });
        if (sheets.size() == 0) {
            System.out.println("You don't have any sheets.  Goodbye!");
            return;
        }
        System.out.println("Total sheets: " + sheets.size());
        int i = 1;
        for (Sheet sheet : sheets) {
            System.out.println(i++ + ": " + sheet.name);
        }
        System.out.print("Enter the number of the sheet you want to share: ");

        //Prompt the user to provide the sheet number, the email address, and the access level
        Integer sheetNumber = Integer.parseInt(in.readLine().trim()); //NOTE: for simplicity, error handling and input validation is neglected.
        Sheet chosenSheet = sheets.get(sheetNumber - 1);

        System.out.print("Enter an email address to share " + chosenSheet.getName() + " to: ");
        String email = in.readLine();

        System.out.print("Choose an access level (VIEWER, EDITOR, EDITOR_SHARE, ADMIN) for " + email + ": ");
        String accessLevel = in.readLine();

        //Create a share object
        Share share = new Share();
        share.setEmail(email);
        share.setAccessLevel(accessLevel);

        System.out.println("Sharing " + chosenSheet.name + " to " + email + " as " + accessLevel + ".");

        //Create a connection. Note the SHARE_SHEET_URL uses /sheet as opposed to /sheets (with an 's')
        connection = (HttpURLConnection) new URL(SHARE_SHEET_URL.replace(SHEET_ID, "" + chosenSheet.getId()))
                .openConnection();
        connection.setDoOutput(true);
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        //Serialize the Share object
        writer.write(mapper.writeValueAsString(share));
        writer.close();

        //Read the response and parse the JSON
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }

        Result result = mapper.readValue(response.toString(), Result.class);
        System.out.println("Sheet shared successfully, share ID " + result.result.id);
        System.out.println("Press any key to quit.");
        in.read();

    } catch (IOException e) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(((HttpURLConnection) connection).getErrorStream()));
        String line;
        try {
            response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            Result result = mapper.readValue(response.toString(), Result.class);
            System.out.println(result.message);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

    } catch (Exception e) {
        System.out.println("Something broke: " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:cn.heroes.ud.protocol.ElementalReverseProxy.java

public static void main(final String[] args) throws Exception {
    if (args.length < 1) {
        System.err.println("Please specified target hostname and port");
        System.exit(1);/*from   ww  w .  ja v a  2  s.c om*/
    }
    final String hostname = args[0];
    int port = 80;
    if (args.length > 1) {
        port = Integer.parseInt(args[1]);
    }
    final HttpHost target = new HttpHost(hostname, port);

    final Thread t = new RequestListenerThread(8888, target);
    t.setDaemon(false);
    t.start();
}

From source file:io.amient.kafka.metrics.DiscoveryTool.java

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

    OptionParser parser = new OptionParser();

    parser.accepts("help", "Print usage help");
    OptionSpec<String> zookeeper = parser.accepts("zookeeper", "Address of the seed zookeeper server")
            .withRequiredArg().required();
    OptionSpec<String> dashboard = parser
            .accepts("dashboard", "Grafana dashboard name to be used in all generated configs")
            .withRequiredArg().required();
    OptionSpec<String> dashboardPath = parser
            .accepts("dashboard-path", "Grafana location, i.e. `./instance/.data/grafana/dashboards`")
            .withRequiredArg();// w  ww.  j a  v  a 2 s. c o  m
    OptionSpec<String> topic = parser.accepts("topic", "Name of the metrics topic to consume measurements from")
            .withRequiredArg();
    OptionSpec<String> influxdb = parser
            .accepts("influxdb", "InfluxDB connect URL (including user and password)").withRequiredArg();
    OptionSpec<String> interval = parser.accepts("interval", "JMX scanning interval in seconds")
            .withRequiredArg().defaultsTo("10");
    //TODO --influxdb-database (DEFAULT_DATABASE)
    //TODO --dashboard-datasource (DEFAULT_DATASOURCE)

    if (args.length == 0 || args[0] == "-h" || args[0] == "--help") {
        parser.printHelpOn(System.err);
        System.exit(0);
    }

    OptionSet opts = parser.parse(args);

    try {

        DiscoveryTool tool = new DiscoveryTool(opts.valueOf(zookeeper));

        try {
            List<String> topics = tool.getKafkaTopics();
            List<Broker> brokers = tool.getKafkaBrokers();
            int interval_s = Integer.parseInt(opts.valueOf(interval));

            if (opts.has(dashboard) && opts.has(dashboardPath)) {
                tool.generateDashboard(opts.valueOf(dashboard), brokers, topics, DEFAULT_DATASOURCE,
                        opts.valueOf(dashboardPath), interval_s).save();
            }

            if (opts.has(topic)) {
                //producer/reporter settings
                System.out.println("kafka.metrics.topic=" + opts.valueOf(topic));
                System.out.println("kafka.metrics.polling.interval=" + interval_s + "s");
                //TODO --producer-bootstrap for truly non-intrusive agent deployment,
                // i.e. when producing to a different cluster from the one being discovered
                System.out.println("kafka.metrics.bootstrap.servers=" + brokers.get(0).hostPort());
                //consumer settings
                System.out.println("consumer.topic=" + opts.valueOf(topic));
                System.out.println("consumer.zookeeper.connect=" + opts.valueOf(zookeeper));
                System.out.println("consumer.group.id=kafka-metrics-" + opts.valueOf(dashboard));
            }

            if (!opts.has(influxdb) || !opts.has(topic)) {
                tool.generateScannerConfig(brokers, opts.valueOf(dashboard), interval_s).list(System.out);
            }

            if (opts.has(influxdb)) {
                URL url = new URL(opts.valueOf(influxdb));
                System.out.println("influxdb.database=" + DEFAULT_DATABASE);
                System.out.println("influxdb.url=" + url.toString());
                if (url.getUserInfo() != null) {
                    System.out.println("influxdb.username=" + url.getUserInfo().split(":")[0]);
                    if (url.getUserInfo().contains(":")) {
                        System.out.println("influxdb.password=" + url.getUserInfo().split(":")[1]);
                    }
                }
            }

            System.out.flush();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(3);
        } finally {
            tool.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(2);
    }

}

From source file:CircularGenerator.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options helpOptions = new Options();
    helpOptions.addOption("h", "help", false, "show this help page");
    Options options = new Options();
    options.addOption("h", "help", false, "show this help page");
    options.addOption(OptionBuilder.withLongOpt("input").withArgName("INPUT")
            .withDescription("the input FastA File").isRequired().hasArg().create("i"));
    options.addOption(OptionBuilder.withLongOpt("elongation").withArgName("ELONGATION")
            .withDescription("the elongation factor [INT]").isRequired().hasArg().create("e"));
    options.addOption(OptionBuilder.withLongOpt("seq").withArgName("SEQ")
            .withDescription("the names of the sequences that should to be elongated").isRequired().hasArg()
            .hasOptionalArgs().hasArg().create("s"));
    HelpFormatter helpformatter = new HelpFormatter();
    CommandLineParser parser = new BasicParser();
    try {/*from   w w w  .j  a  v  a2s . c o  m*/
        CommandLine cmd = parser.parse(helpOptions, args);
        if (cmd.hasOption('h')) {
            helpformatter.printHelp(CLASS_NAME + "v" + VERSION, options);
            System.exit(0);
        }
    } catch (ParseException e1) {
    }
    String input = "";
    String tmpElongation = "";
    Integer elongation = 0;
    String[] names = new String[0];
    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption('i')) {
            input = cmd.getOptionValue('i');
        }
        if (cmd.hasOption('e')) {
            tmpElongation = cmd.getOptionValue('e');
            try {
                elongation = Integer.parseInt(tmpElongation);
            } catch (Exception e) {
                System.err.println("elongation not an Integer: " + tmpElongation);
                System.exit(0);
            }
        }
        if (cmd.hasOption('s')) {
            names = cmd.getOptionValues('s');
        }
    } catch (ParseException e) {
        helpformatter.printHelp(CLASS_NAME, options);
        System.err.println(e.getMessage());
        System.exit(0);
    }

    CircularGenerator cg = new CircularGenerator(elongation);
    File f = new File(input);
    for (String s : names) {
        cg.keys_to_treat_circular.add(s);
    }
    cg.extendFastA(f);

}

From source file:com.aerospike.examples.frequencycap.FrequencyCap.java

public static void main(String[] args) throws AerospikeException {
    try {/*from  w ww. ja  v  a  2s.com*/
        Options options = new Options();
        options.addOption("h", "host", true, "Server hostname (default: 172.28.128.6)");
        options.addOption("p", "port", true, "Server port (default: 3000)");
        options.addOption("n", "namespace", true, "Namespace (default: test)");
        options.addOption("u", "usage", false, "Print usage.");

        options.addOption("l", "load", false, "Load data.");

        CommandLineParser parser = new PosixParser();
        CommandLine cl = parser.parse(options, args, false);

        String host = cl.getOptionValue("h", "172.28.128.6");
        String portString = cl.getOptionValue("p", "3000");
        int port = Integer.parseInt(portString);
        String namespace = cl.getOptionValue("n", "test");
        String set = cl.getOptionValue("s", "demo");
        log.debug("Host: " + host);
        log.debug("Port: " + port);
        log.debug("Namespace: " + namespace);
        log.debug("Set: " + set);

        @SuppressWarnings("unchecked")
        List<String> cmds = cl.getArgList();
        if (cmds.size() == 0 && cl.hasOption("u")) {
            logUsage(options);
            return;
        }

        FrequencyCap as = new FrequencyCap(host, port, namespace, set);
        if (cl.hasOption("l")) {
            as.generateDataDateInKey();
            as.generateDataDateInBin();
        } else {
            as.simulateWorkDateInKey();
            as.simulateWorkDateInBin();
        }
    } catch (Exception e) {
        log.error("Critical error", e);
    }
}

From source file:org.sonews.Application.java

/**
 * The main entrypoint./*w w w.  j  a  v a 2  s  .  c o  m*/
 *
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    System.out.println(VERSION);
    Thread.currentThread().setName("Mainthread");

    // Command line arguments
    boolean async = false;
    boolean feed = false; // Enable feeding?
    boolean purger = false; // Enable message purging?
    int port = -1;

    for (int n = 0; n < args.length; n++) {
        switch (args[n]) {
        case "-async": {
            async = true;
            break;
        }
        case "-c":
        case "-config": {
            Config.inst().set(Config.LEVEL_CLI, Config.CONFIGFILE, args[++n]);
            System.out.println("Using config file " + args[n]);
            break;
        }
        case "-C":
        case "-context": {
            // FIXME: Additional context files
            n++;
            break;
        }
        case "-dumpjdbcdriver": {
            System.out.println("Available JDBC drivers:");
            Enumeration<Driver> drvs = DriverManager.getDrivers();
            while (drvs.hasMoreElements()) {
                System.out.println(drvs.nextElement());
            }
            return;
        }
        case "-feed": {
            feed = true;
            break;
        }
        case "-h":
        case "-help": {
            printArguments();
            return;
        }
        case "-p": {
            port = Integer.parseInt(args[++n]);
            break;
        }
        case "-plugin-storage": {
            System.out.println("Warning: -plugin-storage is not implemented!");
            break;
        }
        case "-purger": {
            purger = true;
            break;
        }
        case "-v":
        case "-version":
            // Simply return as the version info is already printed above
            return;
        }
    }

    ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
    context = new FileSystemXmlApplicationContext(new String[] { "sonews.xml" }, context);

    // Enable storage backend
    StorageProvider sprov = context.getBean("storageProvider", StorageProvider.class);
    StorageManager.enableProvider(sprov);

    ChannelLineBuffers.allocateDirect();

    // Add shutdown hook
    Runtime.getRuntime().addShutdownHook(new ShutdownHook());

    // Start the listening daemon
    if (port <= 0) {
        port = Config.inst().get(Config.PORT, 119);
    }

    NNTPDaemon daemon = context.getBean(NNTPDaemon.class);
    daemon.setPort(port);
    daemon.start();

    // Start Connections purger thread...
    Connections.getInstance().start();

    // Start feeds
    if (feed) {
        FeedManager.startFeeding();
    }

    if (purger) {
        Purger purgerDaemon = new Purger();
        purgerDaemon.start();
    }

    // Wait for main thread to exit (setDaemon(false))
    daemon.join();
}

From source file:cz.muni.fi.crocs.EduHoc.Main.java

/**
 * @param args the command line arguments
 *//*from  w w  w.  j  a  v  a2s  .com*/
public static void main(String[] args) {
    System.out.println("JeeTool \n");

    Options options = OptionsMain.createOptions();

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println("cannot parse parameters");
        OptionsMain.printHelp(options);
        System.err.println(ex.toString());
        return;
    }
    boolean silent = cmd.hasOption("s");
    boolean verbose = cmd.hasOption("v");

    if (!silent) {
        System.out.println(ANSI_GREEN + "EduHoc home is: " + System.getenv("EDU_HOC_HOME") + "\n" + ANSI_RESET);
    }

    //help
    if (cmd.hasOption("h")) {
        OptionsMain.printHelp(options);
        return;
    }

    String filepath;
    //path to config list of nodes
    if (cmd.hasOption("a")) {
        filepath = cmd.getOptionValue("a");
    } else {
        filepath = System.getenv("EDU_HOC_HOME") + "/config/motePaths.txt";
    }

    //create motelist
    MoteList moteList = new MoteList(filepath);
    if (verbose) {
        moteList.setVerbose();
    }
    if (silent) {
        moteList.setSilent();
    }

    if (verbose) {
        System.out.println("reading motelist from file " + filepath);
    }

    if (cmd.hasOption("i")) {
        List<Integer> ids = new ArrayList<Integer>();
        String arg = cmd.getOptionValue("i");
        String[] IdArgs = arg.split(",");
        for (String s : IdArgs) {
            if (s.contains("-")) {
                int start = Integer.parseInt(s.substring(0, s.indexOf("-")));
                int end = Integer.parseInt(s.substring(s.indexOf("-") + 1, s.length()));
                for (int i = start; i <= end; i++) {
                    ids.add(i);
                }
            } else {
                ids.add(Integer.parseInt(s));
            }
        }
        moteList.setIds(ids);
    }

    moteList.readFile();

    if (cmd.hasOption("d")) {
        //only detect nodes
        return;
    }

    //if make
    if (cmd.hasOption("m") || cmd.hasOption("c") || cmd.hasOption("u")) {
        UploadMain upload = new UploadMain(moteList, cmd);
        upload.runMake();
    }

    //if execute command
    if (cmd.hasOption("E")) {
        try {
            ExecuteShellCommand com = new ExecuteShellCommand();
            if (verbose) {
                System.out.println("Executing shell command " + cmd.getOptionValue("E"));
            }

            com.executeCommand(cmd.getOptionValue("E"));
        } catch (IOException ex) {
            System.err.println("Execute command " + cmd.getOptionValue("E") + " failed");
        }
    }

    //if serial
    if (cmd.hasOption("l") || cmd.hasOption("w")) {
        SerialMain serial = new SerialMain(cmd, moteList);
        if (silent) {
            serial.setSilent();
        }
        if (verbose) {
            serial.setVerbose();
        }
        serial.startSerial();
    }

}

From source file:net.sf.mpaxs.test.ImpaxsExecution.java

/**
 *
 * @param args/* w w w .j a  v a  2  s. com*/
 */
public static void main(String[] args) {
    Options options = new Options();
    Option[] optionArray = new Option[] {
            OptionBuilder.withArgName("nhosts").hasArg()
                    .withDescription("Number of hosts for parallel processing").create("n"),
            OptionBuilder.withArgName("mjobs").hasArg().withDescription("Number of jobs to run in parallel")
                    .create("m"),
            OptionBuilder.withArgName("runmode").hasArg()
                    .withDescription("The mode in which to operate: one of <ALL,LOCAL,DISTRIBUTED>")
                    .create("r"), //            OptionBuilder.withArgName("gui").
            //            withDescription("Create gui for distributed execution").create("g")
    };
    for (Option opt : optionArray) {
        options.addOption(opt);
    }
    if (args.length == 0) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(StartUp.class.getCanonicalName(), options, true);
        System.exit(1);
    }
    GnuParser gp = new GnuParser();
    int nhosts = 1;
    int mjobs = 10;
    boolean gui = false;
    Mode mode = Mode.ALL;
    try {
        CommandLine cl = gp.parse(options, args);
        if (cl.hasOption("n")) {
            nhosts = Integer.parseInt(cl.getOptionValue("n"));
        }
        if (cl.hasOption("m")) {
            mjobs = Integer.parseInt(cl.getOptionValue("m"));
        }
        if (cl.hasOption("r")) {
            mode = Mode.valueOf(cl.getOptionValue("r"));
        }
        //            if (cl.hasOption("g")) {
        //                gui = true;
        //            }
    } catch (Exception ex) {
        Logger.getLogger(StartUp.class.getName()).log(Level.SEVERE, null, ex);
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(StartUp.class.getCanonicalName(), options, true);
        System.exit(1);
    }

    String version;
    try {
        version = net.sf.mpaxs.api.Version.getVersion();
        System.out.println("Running mpaxs " + version);
        File computeHostJarLocation = new File(System.getProperty("user.dir"), "mpaxs.jar");
        if (!computeHostJarLocation.exists() || !computeHostJarLocation.isFile()) {
            throw new IOException("Could not locate mpaxs.jar in " + System.getProperty("user.dir"));
        }
        final PropertiesConfiguration cfg = new PropertiesConfiguration();
        //set default execution type
        cfg.setProperty(ConfigurationKeys.KEY_EXECUTION_MODE, ExecutionType.DRMAA);
        //set location of compute host jar
        cfg.setProperty(ConfigurationKeys.KEY_PATH_TO_COMPUTEHOST_JAR, computeHostJarLocation);
        //do not exit to console when master server shuts down
        cfg.setProperty(ConfigurationKeys.KEY_MASTER_SERVER_EXIT_ON_SHUTDOWN, false);
        //limit the number of used compute hosts
        cfg.setProperty(ConfigurationKeys.KEY_MAX_NUMBER_OF_CHOSTS, nhosts);
        cfg.setProperty(ConfigurationKeys.KEY_NATIVE_SPEC, "");
        cfg.setProperty(ConfigurationKeys.KEY_GUI_MODE, gui);
        cfg.setProperty(ConfigurationKeys.KEY_SILENT_MODE, true);
        cfg.setProperty(ConfigurationKeys.KEY_SCHEDULE_WAIT_TIME, "500");
        final int maxJobs = mjobs;
        final int maxThreads = nhosts;
        final Mode runMode = mode;
        printMessage("Run mode: " + runMode);
        Executors.newSingleThreadExecutor().submit(new Runnable() {
            @Override
            public void run() {
                if (runMode == Mode.ALL || runMode == Mode.LOCAL) {
                    printMessage("Running Within VM Execution");
                    /*
                     * LOCAL within VM execution
                     */
                    WithinVmExecution lhe = new WithinVmExecution(maxJobs, maxThreads);
                    try {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.INFO,
                                "Sum is: " + lhe.call());
                    } catch (Exception ex) {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                if (runMode == Mode.ALL || runMode == Mode.DISTRIBUTED) {
                    printMessage("Running Distributed Host RMI Execution");
                    /*
                     * Grid Engine (DRMAA API) or local host distributed RMI execution
                     */
                    DistributedRmiExecution de = new DistributedRmiExecution(cfg, maxJobs);
                    try {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.INFO,
                                "Sum is: " + de.call());
                    } catch (Exception ex) {
                        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                System.exit(0);
            }
        });
    } catch (IOException ex) {
        Logger.getLogger(ImpaxsExecution.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.lfv.lanzius.Main.java

public static void main(String[] args) {

    /*//ww w .  j  ava2s. com
     * debug levels:
     * error - Runtime errors or unexpected conditions. Expect these to be immediately visible on a status console. See also Internationalization.
     * warn  - Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". Expect these to be immediately visible on a status console. See also Internationalization.
     * info  - Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum. See also Internationalization.
     * debug - detailed information on the flow through the system. Expect these to be written to logs only.
     */

    Log log = null;
    DOMConfigurator conf = new DOMConfigurator();
    DOMConfigurator.configure("data/properties/loggingproperties.xml");
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

    try {
        if (args.length >= 1) {
            // Help
            if (args[0].startsWith("-h")) {
                printUsage();
                return;
            }
            // List devices
            else if (args[0].startsWith("-l")) {
                AudioTest.listDevices();
                return;
            }
            // Test seleted device
            else if (args[0].startsWith("-d")) {
                System.setProperty("org.apache.commons.logging.Log",
                        "org.apache.commons.logging.impl.SimpleLog");
                System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "warn");
                try {
                    String option = "all";
                    if (args.length >= 4)
                        option = args[3];

                    if (option.equals("loop:direct"))
                        AudioTest.testDevicesDirect(Integer.parseInt(args[1]), Integer.parseInt(args[2]));
                    else {
                        if (option.indexOf("debug") != -1)
                            System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "debug");

                        AudioTest.testDevices(Integer.parseInt(args[1]), Integer.parseInt(args[2]), option,
                                (args.length >= 5) ? args[4] : null, (args.length >= 6) ? args[5] : null,
                                (args.length >= 7) ? args[6] : null);
                    }
                } catch (Exception ex) {
                    System.out.println();
                    System.out.println(Config.VERSION);
                    System.out.println();
                    System.out.println("Usage:");
                    System.out.println(
                            "  yada.jar -d output_device input_device <option> <jitter_buffer> <output_buffer> <input_buffer>");
                    System.out.println("  option:");
                    System.out.println("    all(default)");
                    System.out.println("    clip");
                    System.out.println("    loop:jspeex");
                    System.out.println("    loop:null");
                    System.out.println("    loop:direct");
                    System.out.println("    loopdebug:jspeex");
                    System.out.println("    loopdebug:null");
                    System.out.println("  jitter_buffer:");
                    System.out.println("    size of jitter buffer in packets (1-20)");
                    System.out.println("  output_buffer:");
                    System.out.println("    size of output buffer in packets (1.0-4.0)");
                    System.out.println("  input_buffer:");
                    System.out.println("    size of input buffer in packets (1.0-4.0)");
                    System.out.println();
                    if (AudioTest.showStackTrace && !(ex instanceof ArrayIndexOutOfBoundsException))
                        ex.printStackTrace();
                }
                //System.out.println("Exiting...");
                return;
            } else if (args[0].startsWith("-m")) {
                System.setProperty("org.apache.commons.logging.Log",
                        "org.apache.commons.logging.impl.SimpleLog");
                System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "warn");
                try {
                    AudioTest.testMicrophoneLevel(Integer.parseInt(args[1]));
                } catch (Exception ex) {
                    System.out.println();
                    System.out.println(Config.VERSION);
                    System.out.println();
                    System.out.println("Usage:");
                    System.out.println("  yada.jar -m input_device");
                    System.out.println();
                    if (AudioTest.showStackTrace && !(ex instanceof ArrayIndexOutOfBoundsException))
                        ex.printStackTrace();
                }
                return;
            } else if (args[0].startsWith("-s")) {
                Packet.randomSeed = 9182736455L ^ System.currentTimeMillis();
                if (args.length > 2 && args[1].startsWith("-configuration")) {
                    String configFilename = args[2];
                    if (args.length > 4 && args[3].startsWith("-exercise")) {
                        String exerciseFilename = args[4];

                        LanziusServer.start(configFilename, exerciseFilename);
                    } else {
                        LanziusServer.start(configFilename);
                    }
                } else {
                    LanziusServer.start();
                }
                return;
            } else if (args[0].startsWith("-f")) {
                System.setProperty("org.apache.commons.logging.Log",
                        "org.apache.commons.logging.impl.SimpleLog");
                System.setProperty(
                        "org.apache.commons.logging.simplelog.log.com.lfv.lanzius.application.FootSwitchController",
                        "debug");
                try {
                    System.out.println("Starting footswitch controller test using device " + args[1]);
                    try {
                        boolean inverted = false;
                        if (args.length >= 3)
                            inverted = args[2].toLowerCase().startsWith("inv");
                        FootSwitchController c = new FootSwitchController(null, args[1],
                                Constants.PERIOD_FTSW_CONNECTED, inverted);
                        c.start();
                        Thread.sleep(30000);
                    } catch (UnsatisfiedLinkError err) {
                        if (args.length > 1)
                            System.out.println("UnsatisfiedLinkError: " + err.getMessage());
                        else
                            throw new ArrayIndexOutOfBoundsException();
                        System.out.println("Missing ftsw library (ftsw.dll or libftsw.so)");
                        if (!args[1].equalsIgnoreCase("ftdi"))
                            System.out
                                    .println("Missing rxtxSerial library (rxtxSerial.dll or librxtxSerial.so)");
                        if (AudioTest.showStackTrace)
                            err.printStackTrace();
                    }
                } catch (Exception ex) {
                    if (ex instanceof NoSuchPortException)
                        System.out.println("The serial port " + args[1] + " does not exist!");
                    else if (ex instanceof PortInUseException)
                        System.out.println("The serial port " + args[1] + " is already in use!");
                    System.out.println();
                    System.out.println(Config.VERSION);
                    System.out.println();
                    System.out.println("Usage:");
                    System.out.println("  yada.jar -f interface <invert>");
                    System.out.println("  interface:");
                    System.out.println("    ftdi");
                    System.out.println("    comport (COMx or /dev/ttyx)");
                    System.out.println("  invert:");
                    System.out.println("    true");
                    System.out.println("    false (default)");
                    System.out.println();
                    if (AudioTest.showStackTrace && !(ex instanceof ArrayIndexOutOfBoundsException))
                        ex.printStackTrace();
                }
                return;
            } else if (args[0].startsWith("-c")) {
                Packet.randomSeed = 7233103157L ^ System.currentTimeMillis();
                if (args.length >= 2) {
                    try {
                        int id = Integer.valueOf(args[1]);
                        if (id <= 0)
                            throw new NumberFormatException();
                        Controller c = Controller.getInstance();
                        if (args.length >= 3) {
                            if (args[2].equalsIgnoreCase("test")) {
                                c.setAutoTester(true);
                            }
                        }
                        c.init(id);
                        return;
                    } catch (NumberFormatException ex) {
                        printUsage();
                    }
                } else {
                    Controller.getInstance().init(0);
                }
            } else
                printUsage();
        } else
            printUsage();
    } catch (Throwable t) {
        if (log == null)
            log = LogFactory.getLog(Main.class);
        log.error("Unhandled exception or error", t);
    }
}

From source file:gobblin.restli.throttling.LocalStressTest.java

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

    CommandLine cli = StressTestUtils.parseCommandLine(OPTIONS, args);

    int stressorThreads = Integer.parseInt(
            cli.getOptionValue(STRESSOR_THREADS.getOpt(), Integer.toString(DEFAULT_STRESSOR_THREADS)));
    int processorThreads = Integer.parseInt(
            cli.getOptionValue(PROCESSOR_THREADS.getOpt(), Integer.toString(DEFAULT_PROCESSOR_THREADS)));
    int artificialLatency = Integer.parseInt(
            cli.getOptionValue(ARTIFICIAL_LATENCY.getOpt(), Integer.toString(DEFAULT_ARTIFICIAL_LATENCY)));
    long targetQps = Integer.parseInt(cli.getOptionValue(QPS.getOpt(), Integer.toString(DEFAULT_TARGET_QPS)));

    Configuration configuration = new Configuration();
    StressTestUtils.populateConfigFromCli(configuration, cli);

    String resourceLimited = LocalStressTest.class.getSimpleName();

    Map<String, String> configMap = Maps.newHashMap();

    ThrottlingPolicyFactory factory = new ThrottlingPolicyFactory();
    SharedLimiterKey res1key = new SharedLimiterKey(resourceLimited);
    configMap.put(BrokerConfigurationKeyGenerator.generateKey(factory, res1key, null,
            ThrottlingPolicyFactory.POLICY_KEY), QPSPolicy.FACTORY_ALIAS);
    configMap.put(BrokerConfigurationKeyGenerator.generateKey(factory, res1key, null, QPSPolicy.QPS),
            Long.toString(targetQps));

    ThrottlingGuiceServletConfig guiceServletConfig = new ThrottlingGuiceServletConfig();
    guiceServletConfig.initialize(ConfigFactory.parseMap(configMap));
    LimiterServerResource limiterServer = guiceServletConfig.getInjector()
            .getInstance(LimiterServerResource.class);

    RateComputingLimiterContainer limiterContainer = new RateComputingLimiterContainer();

    Class<? extends Stressor> stressorClass = configuration.getClass(StressTestUtils.STRESSOR_CLASS,
            StressTestUtils.DEFAULT_STRESSOR_CLASS, Stressor.class);

    ExecutorService executorService = Executors.newFixedThreadPool(stressorThreads);

    SharedResourcesBroker broker = guiceServletConfig.getInjector().getInstance(
            Key.get(SharedResourcesBroker.class, Names.named(LimiterServerResource.BROKER_INJECT_NAME)));
    ThrottlingPolicy policy = (ThrottlingPolicy) broker.getSharedResource(new ThrottlingPolicyFactory(),
            new SharedLimiterKey(resourceLimited));
    ScheduledExecutorService reportingThread = Executors.newSingleThreadScheduledExecutor();
    reportingThread.scheduleAtFixedRate(new Reporter(limiterContainer, policy), 0, 15, TimeUnit.SECONDS);

    Queue<Future<?>> futures = new LinkedList<>();
    MockRequester requester = new MockRequester(limiterServer, artificialLatency, processorThreads);

    requester.start();//from  w  w  w  .j av  a2  s . co m
    for (int i = 0; i < stressorThreads; i++) {
        RestliServiceBasedLimiter restliLimiter = RestliServiceBasedLimiter.builder()
                .resourceLimited(resourceLimited).requestSender(requester).serviceIdentifier("stressor" + i)
                .build();

        Stressor stressor = stressorClass.newInstance();
        stressor.configure(configuration);
        futures.add(executorService
                .submit(new StressorRunner(limiterContainer.decorateLimiter(restliLimiter), stressor)));
    }
    int stressorFailures = 0;
    for (Future<?> future : futures) {
        try {
            future.get();
        } catch (ExecutionException ee) {
            stressorFailures++;
        }
    }
    requester.stop();

    executorService.shutdownNow();

    if (stressorFailures > 0) {
        log.error("There were " + stressorFailures + " failed stressor threads.");
    }
    System.exit(stressorFailures);
}