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:com.novadart.silencedetect.SilenceDetect.java

public static void main(String[] args) {

    // create the parser
    CommandLineParser parser = new BasicParser();
    try {// w  w w  . j  ava2s  .  c  o m
        // parse the command line arguments
        CommandLine line = parser.parse(OPTIONS, args);

        if (line.hasOption("h")) {

            printHelp();

        } else {

            String decibels = "-10";
            if (line.hasOption("b")) {
                decibels = "-" + line.getOptionValue("b");
            } else {
                throw new RuntimeException();
            }

            String videoFile = null;

            if (line.hasOption("i")) {

                videoFile = line.getOptionValue("i");

                Boolean debug = line.hasOption("d");

                if (line.hasOption("t")) {

                    System.out.println(printAudioTracksList(videoFile, debug));

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

                    int trackNumber = Integer.parseInt(line.getOptionValue("s"));
                    System.out.println(printAudioTrackSilenceDuration(videoFile, trackNumber, decibels, debug));

                } else {

                    printHelp();

                }

            } else if (line.hasOption("-j")) {

                // choose file
                final JFileChooser fc = new JFileChooser();
                fc.setVisible(true);
                int returnVal = fc.showOpenDialog(null);
                if (returnVal == JFileChooser.APPROVE_OPTION) {

                    videoFile = fc.getSelectedFile().getAbsolutePath();

                } else {
                    return;
                }

                JTextArea tracks = new JTextArea();
                tracks.setText(printAudioTracksList(videoFile, true));
                JSpinner trackNumber = new JSpinner();
                trackNumber.setValue(1);
                final JComponent[] inputs = new JComponent[] { new JLabel("Audio Tracks"), tracks,
                        new JLabel("Track to analyze"), trackNumber };
                JOptionPane.showMessageDialog(null, inputs, "Select Audio Track", JOptionPane.PLAIN_MESSAGE);

                JTextArea results = new JTextArea();
                results.setText(printAudioTrackSilenceDuration(videoFile, (int) trackNumber.getValue(),
                        decibels, false));
                final JComponent[] resultsInputs = new JComponent[] { new JLabel("Results"), results };
                JOptionPane.showMessageDialog(null, resultsInputs, "RESULTS!", JOptionPane.PLAIN_MESSAGE);

            } else {
                printHelp();
                return;
            }

        }

    } catch (ParseException | IOException | InterruptedException exp) {
        // oops, something went wrong
        System.out.println("There was a problem :(\nReason: " + exp.getMessage());
    }
}

From source file:com.amazonaws.services.kinesis.samples.datavis.HttpReferrerStreamWriter.java

/**
 * Start a number of threads and send randomly generated {@link HttpReferrerPair}s to a Kinesis Stream until the
 * program is terminated.// w ww.j a  va 2s.  co  m
 *
 * @param args Expecting 3 arguments: A numeric value indicating the number of threads to use to send
 *        data to Kinesis and the name of the stream to send records to, and the AWS region in which these resources
 *        exist or should be created.
 * @throws InterruptedException If this application is interrupted while sending records to Kinesis.
 */
public static void main(String[] args) throws InterruptedException {
    if (args.length != 3) {
        System.err.println("Usage: " + HttpReferrerStreamWriter.class.getSimpleName()
                + " <number of threads> <stream name> <region>");
        System.exit(1);
    }

    int numberOfThreads = Integer.parseInt(args[0]);
    String streamName = args[1];
    Region region = SampleUtils.parseRegion(args[2]);

    AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain();
    ClientConfiguration clientConfig = SampleUtils.configureUserAgentForSample(new ClientConfiguration());
    AmazonKinesis kinesis = new AmazonKinesisClient(credentialsProvider, clientConfig);
    kinesis.setRegion(region);

    // The more resources we declare the higher write IOPS we need on our DynamoDB table.
    // We write a record for each resource every interval.
    // If interval = 500ms, resource count = 7 we need: (1000/500 * 7) = 14 write IOPS minimum.
    List<String> resources = new ArrayList<>();
    resources.add("/index.html");

    // These are the possible referrers to use when generating pairs
    List<String> referrers = new ArrayList<>();
    referrers.add("http://www.amazon.com");
    referrers.add("http://www.google.com");
    referrers.add("http://www.yahoo.com");
    referrers.add("http://www.bing.com");
    referrers.add("http://www.stackoverflow.com");
    referrers.add("http://www.reddit.com");

    HttpReferrerPairFactory pairFactory = new HttpReferrerPairFactory(resources, referrers);

    // Creates a stream to write to with 2 shards if it doesn't exist
    StreamUtils streamUtils = new StreamUtils(kinesis);
    streamUtils.createStreamIfNotExists(streamName, 2);
    LOG.info(String.format("%s stream is ready for use", streamName));

    final HttpReferrerKinesisPutter putter = new HttpReferrerKinesisPutter(pairFactory, kinesis, streamName);

    ExecutorService es = Executors.newCachedThreadPool();

    Runnable pairSender = new Runnable() {
        @Override
        public void run() {
            try {
                putter.sendPairsIndefinitely(DELAY_BETWEEN_RECORDS_IN_MILLIS, TimeUnit.MILLISECONDS);
            } catch (Exception ex) {
                LOG.warn(
                        "Thread encountered an error while sending records. Records will no longer be put by this thread.",
                        ex);
            }
        }
    };

    for (int i = 0; i < numberOfThreads; i++) {
        es.submit(pairSender);
    }

    LOG.info(String.format("Sending pairs with a %dms delay between records with %d thread(s).",
            DELAY_BETWEEN_RECORDS_IN_MILLIS, numberOfThreads));

    es.shutdown();
    es.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}

From source file:com.anhth12.kafka.ulti.ProduceData.java

public static void main(String[] args) throws InterruptedException {
    int howMany = Integer.parseInt(args[0]);
    int intervalMsec = Integer.parseInt(args[1]);
    String topic = args[2];/* w  w  w  .j  a va 2  s .  c o  m*/
    int zkPort = Integer.parseInt(args[3]);
    int kafkaPort = Integer.parseInt(args[4]);
    String host = args[5];

    ProduceData producer = new ProduceData(new SampleALSUpdateGenerator(), zkPort, kafkaPort, topic, howMany,
            intervalMsec, host);
    producer.start();
}

From source file:ee.ria.xroad.proxy.opmonitoring.OpMonitoringBufferMemoryUsage.java

/**
 * Main function.//from  w  w  w .j a  va2  s. co  m
 * @param args args
 * @throws Exception if something goes wrong.
 */
public static void main(String args[]) throws Exception {

    CommandLine cmd = parseCommandLine(args);

    if (cmd.hasOption("help")) {
        usage();

        System.exit(0);
    }

    int count = cmd.getOptionValue("count") != null ? Integer.parseInt(cmd.getOptionValue("count"))
            : DEFAULT_COUNT;

    int shortStrLen = cmd.getOptionValue("short-string-length") != null
            ? Integer.parseInt(cmd.getOptionValue("short-string-length"))
            : DEFAULT_SHORT_LONG_STRING_LENGTH;

    int longStrLen = cmd.getOptionValue("long-string-length") != null
            ? Integer.parseInt(cmd.getOptionValue("long-string-length"))
            : DEFAULT_LONG_STRING_LENGTH;

    Runtime runtime = Runtime.getRuntime();

    long before = getUsedBytes(runtime);

    createBuffer(count, shortStrLen, longStrLen);

    long after = getUsedBytes(runtime);

    log.info("Records count {}, used heap {}MB", count, (after - before) / MB);
}

From source file:com.omertron.slackbot.SlackBot.java

public static void main(String[] args) throws Exception {
    LOG.info("Starting {} v{} ...", Constants.BOT_NAME, Constants.BOT_VERSION);

    // Load the properties
    PropertiesUtil.setPropertiesStreamName(DEFAULT_PROPERTIES_FILE);

    LOG.info("Starting session...");
    SlackSession session;/*from   w w w .ja  v a  2 s  .  c o  m*/

    String proxyURL = PropertiesUtil.getProperty(Constants.PROXY_HOST);
    if (StringUtils.isNotBlank(proxyURL)) {
        int proxyPort = Integer.parseInt(PropertiesUtil.getProperty(Constants.PROXY_PORT, "80"));
        session = SlackSessionFactory.getSlackSessionBuilder(Constants.BOT_TOKEN)
                .withProxy(Proxy.Type.HTTP, proxyURL, proxyPort).build();
    } else {
        session = SlackSessionFactory
                .createWebSocketSlackSession(PropertiesUtil.getProperty(Constants.BOT_TOKEN));
    }

    session.connect();

    // Populate the BOT admins
    populateBotAdmins(session);

    // Notify BOT admins
    notifyStartup(session);

    // Add the listeners to the session
    addListeners(session);

    LOG.info("Session connected: {}", session.isConnected());
    LOG.info("\tConnected to {} ({})", session.getTeam().getName(), session.getTeam().getId());
    LOG.info("\tFound {} channels and {} users", session.getChannels().size(), session.getUsers().size());

    outputBotAdminsMessage();

    LOG.info("Starting the Task Executor");
    executor = new BotTaskExecutor(session);

    LOG.info("Checking for users welcomed list");
    BotWelcome.readFile();

    LOG.info("Checking for stats file");
    BotStatistics.readFile();
    LOG.info("Stats read:\n{}", BotStatistics.generateStatistics(false, true));

    Thread.sleep(Long.MAX_VALUE);
}

From source file:com.mozilla.bagheera.consumer.KafkaHBaseConsumer.java

public static void main(String[] args) {
    OptionFactory optFactory = OptionFactory.getInstance();
    Options options = KafkaConsumer.getOptions();
    options.addOption(optFactory.create("tbl", "table", true, "HBase table name.").required());
    options.addOption(optFactory.create("f", "family", true, "Column family."));
    options.addOption(optFactory.create("q", "qualifier", true, "Column qualifier."));
    options.addOption(/*  ww  w . j a  va  2s.com*/
            optFactory.create("b", "batchsize", true, "Batch size (number of messages per HBase flush)."));
    options.addOption(optFactory.create("pd", "prefixdate", false, "Prefix key with salted date."));

    CommandLineParser parser = new GnuParser();
    ShutdownHook sh = ShutdownHook.getInstance();
    try {
        // Parse command line options
        CommandLine cmd = parser.parse(options, args);

        final KafkaConsumer consumer = KafkaConsumer.fromOptions(cmd);
        sh.addFirst(consumer);

        // Create a sink for storing data
        SinkConfiguration sinkConfig = new SinkConfiguration();
        if (cmd.hasOption("numthreads")) {
            sinkConfig.setInt("hbasesink.hbase.numthreads", Integer.parseInt(cmd.getOptionValue("numthreads")));
        }
        if (cmd.hasOption("batchsize")) {
            sinkConfig.setInt("hbasesink.hbase.batchsize", Integer.parseInt(cmd.getOptionValue("batchsize")));
        }
        sinkConfig.setString("hbasesink.hbase.tablename", cmd.getOptionValue("table"));
        sinkConfig.setString("hbasesink.hbase.column.family", cmd.getOptionValue("family", "data"));
        sinkConfig.setString("hbasesink.hbase.column.qualifier", cmd.getOptionValue("qualifier", "json"));
        sinkConfig.setBoolean("hbasesink.hbase.rowkey.prefixdate", cmd.hasOption("prefixdate"));
        KeyValueSinkFactory sinkFactory = KeyValueSinkFactory.getInstance(HBaseSink.class, sinkConfig);
        sh.addLast(sinkFactory);

        // Set the sink factory for consumer storage
        consumer.setSinkFactory(sinkFactory);

        prepareHealthChecks();

        // Initialize metrics collection, reporting, etc.
        final MetricsManager manager = MetricsManager.getDefaultMetricsManager();

        // Begin polling
        consumer.poll();
    } catch (ParseException e) {
        LOG.error("Error parsing command line options", e);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(KafkaHBaseConsumer.class.getName(), options);
    }
}

From source file:RedPenRunner.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("h", "help", false, "help");
    options.addOption("v", "version", false, "print the version information and exit");

    OptionBuilder.withLongOpt("port");
    OptionBuilder.withDescription("port number");
    OptionBuilder.hasArg();//from ww w. j a v  a  2s . c  om
    OptionBuilder.withArgName("PORT");
    options.addOption(OptionBuilder.create("p"));

    OptionBuilder.withLongOpt("key");
    OptionBuilder.withDescription("stop key");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("STOP_KEY");
    options.addOption(OptionBuilder.create("k"));

    OptionBuilder.withLongOpt("conf");
    OptionBuilder.withDescription("configuration file");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("CONFIG_FILE");
    options.addOption(OptionBuilder.create("c"));

    OptionBuilder.withLongOpt("lang");
    OptionBuilder.withDescription("Language of error messages");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("LANGUAGE");
    options.addOption(OptionBuilder.create("L"));

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

    try {
        commandLine = parser.parse(options, args);
    } catch (Exception e) {
        printHelp(options);
        System.exit(-1);
    }

    int portNum = 8080;
    String language = "en";
    if (commandLine.hasOption("h")) {
        printHelp(options);
        System.exit(0);
    }
    if (commandLine.hasOption("v")) {
        System.out.println(RedPen.VERSION);
        System.exit(0);
    }
    if (commandLine.hasOption("p")) {
        portNum = Integer.parseInt(commandLine.getOptionValue("p"));
    }
    if (commandLine.hasOption("L")) {
        language = commandLine.getOptionValue("L");
    }
    if (isPortTaken(portNum)) {
        System.err.println("port is taken...");
        System.exit(1);
    }

    // set language
    if (language.equals("ja")) {
        Locale.setDefault(new Locale("ja", "JA"));
    } else {
        Locale.setDefault(new Locale("en", "EN"));
    }

    final String contextPath = System.getProperty("redpen.home", "/");

    Server server = new Server(portNum);
    ProtectionDomain domain = RedPenRunner.class.getProtectionDomain();
    URL location = domain.getCodeSource().getLocation();

    HandlerList handlerList = new HandlerList();
    if (commandLine.hasOption("key")) {
        // Add Shutdown handler only when STOP_KEY is specified
        ShutdownHandler shutdownHandler = new ShutdownHandler(commandLine.getOptionValue("key"));
        handlerList.addHandler(shutdownHandler);
    }

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath(contextPath);
    if (location.toExternalForm().endsWith("redpen-server/target/classes/")) {
        // use redpen-server/target/redpen-server instead, because target/classes doesn't contain web resources.
        webapp.setWar(location.toExternalForm() + "../redpen-server/");
    } else {
        webapp.setWar(location.toExternalForm());
    }
    if (commandLine.hasOption("c")) {
        webapp.setInitParameter("redpen.conf.path", commandLine.getOptionValue("c"));
    }

    handlerList.addHandler(webapp);
    server.setHandler(handlerList);

    server.start();
    server.join();
}

From source file:com.aerospike.examples.pk.StorePrimaryKey.java

public static void main(String[] args) throws AerospikeException {
    try {//from www .j ava2 s .  c o  m
        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("s", "set", true, "Set (default: demo)");
        options.addOption("u", "usage", false, "Print usage.");

        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;
        }

        StorePrimaryKey as = new StorePrimaryKey(host, port, namespace, set);

        as.work();

    } catch (Exception e) {
        log.error("Critical error", e);
    }
}

From source file:net.securnetwork.itebooks.downloader.EbookDownloader.java

/**
 * Program main method.//from  www  .ja  va  2 s .c om
 * 
 * @param args the program arguments
 */
public static void main(String[] args) {
    if (validateArguments(args)) {
        int start = MIN_EBOOK_INDEX;
        int end = getLastEbookIndex();
        String destinationFolder = null;
        // Check if resume mode
        if (args.length == 1 && args[0].equals(RESUME_ARG)) {
            start = Integer.parseInt(prefs.get(LAST_SAVED_EBOOK_PREF, MIN_EBOOK_INDEX - 1 + "")) + 1; //$NON-NLS-1$
            destinationFolder = prefs.get(OUTPUT_FOLDER_PREF, null);
        } else {
            destinationFolder = getDestinationFolder(args);
        }

        if (destinationFolder == null) {
            System.err.println(Messages.getString("EbookDownloader.NoDestinationFolderFound")); //$NON-NLS-1$
            return;
        } else {
            // Possibly fix the destination folder path
            destinationFolder = destinationFolder.replace("\\", "/");
            if (!destinationFolder.endsWith("/")) {
                destinationFolder += "/";
            }
            prefs.put(OUTPUT_FOLDER_PREF, destinationFolder);
        }

        if (args.length == 3) {
            start = getStartIndex(args);
            end = getEndIndex(args);
        }
        try {
            for (int i = start; i <= end; i++) {
                String ebookPage = BASE_EBOOK_URL + i + SLASH;
                Source sourceHTML = new Source(new URL(ebookPage));
                List<Element> allTables = sourceHTML.getAllElements(HTMLElementName.TABLE);
                Element detailsTable = allTables.get(0);
                // Try to build an info bean for the ebook
                String bookTitle = EbookPageParseUtils.getTitle(detailsTable);
                if (bookTitle != null) {
                    EbookInfo ebook = createEbookInfo(bookTitle, i, detailsTable);
                    String filename = destinationFolder + Misc.getValidFilename(ebook.getTitle(),
                            ebook.getSubTitle(), ebook.getYear(), ebook.getFileFormat());
                    System.out.print(MessageFormat.format(Messages.getString("EbookDownloader.InfoDownloading"), //$NON-NLS-1$
                            new Object[] { ebook.getSiteId() }));
                    try {
                        URL ebookPageURL = new URL(ebook.getDownloadLink());
                        HttpURLConnection con = (HttpURLConnection) ebookPageURL.openConnection();
                        con.setRequestMethod("GET");
                        con.setRequestProperty("Referer", ebookPage);
                        InputStream conIS = con.getInputStream();
                        FileUtils.copyInputStreamToFile(conIS, new File(filename));
                        System.out.println(Messages.getString("EbookDownloader.DownloadingOK")); //$NON-NLS-1$
                        prefs.put(LAST_SAVED_EBOOK_PREF, i + ""); //$NON-NLS-1$
                        conIS.close();
                    } catch (Exception e) {
                        System.out.println(Messages.getString("EbookDownloader.DownloadingKO")); //$NON-NLS-1$
                    }
                }
            }

        } catch (Exception e) {
            System.err.println(Messages.getString("EbookDownloader.FatalError")); //$NON-NLS-1$
            e.printStackTrace();
        }
    } else {
        printHelp();
    }
}

From source file:Main.java

/** Simple command-line based search demo. */
public static void main(String[] args) throws Exception {
    String usage = "Usage:\tjava SearchFiles [-index dir] [-field f] [-repeat n] [-queries file] [-query string] [-raw] [-paging hitsPerPage]\n\nSee http://lucene.apache.org/core/4_1_0/demo/ for details.";
    if (args.length > 0 && ("-h".equals(args[0]) || "-help".equals(args[0]))) {
        System.out.println(usage);
        System.exit(0);//w w  w.j  a  va 2 s  .  c om
    }

    String index = "index";
    String field = "contents";
    String queries = null;
    int repeat = 0;
    boolean raw = false;
    String queryString = null;
    int hitsPerPage = 10;

    for (int i = 0; i < args.length; i++) {
        if ("-index".equals(args[i])) {
            index = args[i + 1];
            i++;
        } else if ("-field".equals(args[i])) {
            field = args[i + 1];
            i++;
        } else if ("-queries".equals(args[i])) {
            queries = args[i + 1];
            i++;
        } else if ("-query".equals(args[i])) {
            queryString = args[i + 1];
            i++;
        } else if ("-repeat".equals(args[i])) {
            repeat = Integer.parseInt(args[i + 1]);
            i++;
        } else if ("-raw".equals(args[i])) {
            raw = true;
        } else if ("-paging".equals(args[i])) {
            hitsPerPage = Integer.parseInt(args[i + 1]);
            if (hitsPerPage <= 0) {
                System.err.println("There must be at least 1 hit per page.");
                System.exit(1);
            }
            i++;
        }
    }

    IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(index)));
    IndexSearcher searcher = new IndexSearcher(reader);
    // :Post-Release-Update-Version.LUCENE_XY:
    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_4_10_0);

    BufferedReader in = null;
    if (queries != null) {
        in = new BufferedReader(new InputStreamReader(new FileInputStream(queries), StandardCharsets.UTF_8));
    } else {
        in = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
    }
    // :Post-Release-Update-Version.LUCENE_XY:
    QueryParser parser = new QueryParser(Version.LUCENE_4_10_0, field, analyzer);
    while (true) {
        if (queries == null && queryString == null) { // prompt the user
            System.out.println("Enter query: ");
        }

        String line = queryString != null ? queryString : in.readLine();

        if (line == null || line.length() == -1) {
            break;
        }

        line = line.trim();
        if (line.length() == 0) {
            break;
        }

        Query query = parser.parse(line);
        System.out.println("Searching for: " + query.toString(field));

        if (repeat > 0) { // repeat & time as benchmark
            Date start = new Date();
            for (int i = 0; i < repeat; i++) {
                searcher.search(query, null, 100);
            }
            Date end = new Date();
            System.out.println("Time: " + (end.getTime() - start.getTime()) + "ms");
        }

        doPagingSearch(in, searcher, query, hitsPerPage, raw, queries == null && queryString == null);

        if (queryString != null) {
            break;
        }
    }
    reader.close();
}