Example usage for java.lang String length

List of usage examples for java.lang String length

Introduction

In this page you can find the example usage for java.lang String length.

Prototype

public int length() 

Source Link

Document

Returns the length of this string.

Usage

From source file:example.Publisher.java

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

    String user = env("ACTIVEMQ_USER", "admin");
    String password = env("ACTIVEMQ_PASSWORD", "password");
    String host = env("ACTIVEMQ_HOST", "localhost");
    int port = Integer.parseInt(env("ACTIVEMQ_PORT", "1883"));
    final String destination = arg(args, 0, "/topic/event");

    int messages = 10000;
    int size = 256;

    String DATA = "abcdefghijklmnopqrstuvwxyz";
    String body = "";
    for (int i = 0; i < size; i++) {
        body += DATA.charAt(i % DATA.length());
    }//w w w .  jav a 2s  .c  o m
    Buffer msg = new AsciiBuffer(body);

    MQTT mqtt = new MQTT();
    mqtt.setHost(host, port);
    mqtt.setUserName(user);
    mqtt.setPassword(password);

    FutureConnection connection = mqtt.futureConnection();
    connection.connect().await();

    final LinkedList<Future<Void>> queue = new LinkedList<Future<Void>>();
    UTF8Buffer topic = new UTF8Buffer(destination);
    for (int i = 1; i <= messages; i++) {

        // Send the publish without waiting for it to complete. This allows us
        // to send multiple message without blocking..
        queue.add(connection.publish(topic, msg, QoS.AT_LEAST_ONCE, false));

        // Eventually we start waiting for old publish futures to complete
        // so that we don't create a large in memory buffer of outgoing message.s
        if (queue.size() >= 1000) {
            queue.removeFirst().await();
        }

        if (i % 1000 == 0) {
            System.out.println(String.format("Sent %d messages.", i));
        }
    }

    queue.add(connection.publish(topic, new AsciiBuffer("SHUTDOWN"), QoS.AT_LEAST_ONCE, false));
    while (!queue.isEmpty()) {
        queue.removeFirst().await();
    }

    connection.disconnect().await();

    System.exit(0);
}

From source file:Test.java

License:asdf

public static void main(String[] args) throws IOException {
    String newName = "asdf";
    Path file = Paths.get("/users.txt");
    try (BufferedWriter writer = Files.newBufferedWriter(file, Charset.defaultCharset(),
            StandardOpenOption.APPEND)) {
        writer.newLine();//from w ww. j  av  a 2 s.  c  om
        writer.write(newName, 0, newName.length());
    }

}

From source file:com.redhat.poc.jdg.bankofchina.function.TestCase411RemoteMultiThreadsCustomMarshal.java

public static void main(String[] args) throws Exception {
    CommandLine commandLine;/*w w w  . ja va 2s . c  o m*/
    Options options = new Options();
    options.addOption("s", true, "The start csv file number option");
    options.addOption("e", true, "The end csv file number option");
    BasicParser parser = new BasicParser();
    parser.parse(options, args);
    commandLine = parser.parse(options, args);
    if (commandLine.getOptions().length > 0) {
        if (commandLine.hasOption("s")) {
            String start = commandLine.getOptionValue("s");
            if (start != null && start.length() > 0) {
                csvFileStart = Integer.parseInt(start);
            }
        }
        if (commandLine.hasOption("e")) {
            String end = commandLine.getOptionValue("e");
            if (end != null && end.length() > 0) {
                csvFileEnd = Integer.parseInt(end);
            }
        }
    }

    System.out.println(
            "%%%%%%%%%  csv ?, ?, ?(ms),"
                    + new Date().getTime());

    for (int i = csvFileStart; i <= csvFileEnd; i++) {
        new TestCase411RemoteMultiThreadsCustomMarshal(i).start();
    }
}

From source file:JTextFieldSample.java

public static void main(String args[]) {
    String title = (args.length == 0 ? "TextField Listener Example" : args[0]);
    JFrame frame = new JFrame(title);
    Container content = frame.getContentPane();

    JPanel namePanel = new JPanel(new BorderLayout());
    JLabel nameLabel = new JLabel("Name: ");
    nameLabel.setDisplayedMnemonic(KeyEvent.VK_N);
    JTextField nameTextField = new JTextField();
    nameLabel.setLabelFor(nameTextField);
    namePanel.add(nameLabel, BorderLayout.WEST);
    namePanel.add(nameTextField, BorderLayout.CENTER);
    content.add(namePanel, BorderLayout.NORTH);

    JPanel cityPanel = new JPanel(new BorderLayout());
    JLabel cityLabel = new JLabel("City: ");
    cityLabel.setDisplayedMnemonic(KeyEvent.VK_C);
    JTextField cityTextField = new JTextField();
    cityLabel.setLabelFor(cityTextField);
    cityPanel.add(cityLabel, BorderLayout.WEST);
    cityPanel.add(cityTextField, BorderLayout.CENTER);
    content.add(cityPanel, BorderLayout.SOUTH);

    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            System.out.println("Command: " + actionEvent.getActionCommand());
        }/* w ww .ja va 2 s  . co m*/
    };
    nameTextField.setActionCommand("Yo");
    nameTextField.addActionListener(actionListener);
    cityTextField.addActionListener(actionListener);

    KeyListener keyListener = new KeyListener() {
        public void keyPressed(KeyEvent keyEvent) {
            printIt("Pressed", keyEvent);
        }

        public void keyReleased(KeyEvent keyEvent) {
            printIt("Released", keyEvent);
        }

        public void keyTyped(KeyEvent keyEvent) {
            printIt("Typed", keyEvent);
        }

        private void printIt(String title, KeyEvent keyEvent) {
            int keyCode = keyEvent.getKeyCode();
            String keyText = KeyEvent.getKeyText(keyCode);
            System.out.println(title + " : " + keyText + " / " + keyEvent.getKeyChar());
        }
    };
    nameTextField.addKeyListener(keyListener);
    cityTextField.addKeyListener(keyListener);

    InputVerifier verifier = new InputVerifier() {
        public boolean verify(JComponent input) {
            final JTextComponent source = (JTextComponent) input;
            String text = source.getText();
            if ((text.length() != 0) && !(text.equals("Exit"))) {
                Runnable runnable = new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(source, "Can't leave.", "Error Dialog",
                                JOptionPane.ERROR_MESSAGE);
                    }
                };
                SwingUtilities.invokeLater(runnable);
                return false;
            } else {
                return true;
            }
        }
    };
    nameTextField.setInputVerifier(verifier);
    cityTextField.setInputVerifier(verifier);

    DocumentListener documentListener = new DocumentListener() {
        public void changedUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        public void insertUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        public void removeUpdate(DocumentEvent documentEvent) {
            printIt(documentEvent);
        }

        private void printIt(DocumentEvent documentEvent) {
            DocumentEvent.EventType type = documentEvent.getType();
            String typeString = null;
            if (type.equals(DocumentEvent.EventType.CHANGE)) {
                typeString = "Change";
            } else if (type.equals(DocumentEvent.EventType.INSERT)) {
                typeString = "Insert";
            } else if (type.equals(DocumentEvent.EventType.REMOVE)) {
                typeString = "Remove";
            }
            System.out.print("Type  :   " + typeString + " / ");
            Document source = documentEvent.getDocument();
            int length = source.getLength();
            try {
                System.out.println("Contents: " + source.getText(0, length));
            } catch (BadLocationException badLocationException) {
                System.out.println("Contents: Unknown");
            }
        }
    };
    nameTextField.getDocument().addDocumentListener(documentListener);
    cityTextField.getDocument().addDocumentListener(documentListener);

    frame.setSize(250, 150);
    frame.setVisible(true);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Socket sock = new Socket(args[0], Integer.parseInt(args[1]));
    GZIPOutputStream zip = new GZIPOutputStream(sock.getOutputStream());
    String line;
    BufferedReader bis = new BufferedReader(new FileReader(args[2]));
    while (true) {
        line = bis.readLine();/*from ww  w.j  a  v a2s. c  o m*/
        if (line == null)
            break;
        line = line + "\n";
        zip.write(line.getBytes(), 0, line.length());
    }
    zip.finish();
    zip.close();
    sock.close();
}

From source file:org.eclipse.swt.snippets.Snippet332.java

public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 332");
    GridLayout layout = new GridLayout();
    layout.marginHeight = layout.marginWidth = 10;
    shell.setLayout(layout);//from  w w  w.ja va  2 s  .  c  om
    StyledText text = new StyledText(shell, SWT.MULTI | SWT.BORDER);
    final String segment = "Eclipse";
    String string = "Force RTL direction on this segment \"" + segment + "\".";
    text.setText(string);
    int[] segments = { string.indexOf(segment), segment.length() };
    StyleRange[] ranges = { new StyleRange(0, 0, display.getSystemColor(SWT.COLOR_RED), null) };
    text.setStyleRanges(segments, ranges);
    Font font = new Font(display, "Tahoma", 16, 0);
    text.setFont(font);
    text.addBidiSegmentListener(event -> {
        String string1 = event.lineText;
        int start = string1.indexOf(segment);
        event.segments = new int[] { start, start + segment.length() };
        event.segmentsChars = new char[] { '\u202e', '\u202C' };
    });
    Combo combo = new Combo(shell, SWT.SIMPLE);
    combo.setFont(font);
    combo.setBackground(display.getSystemColor(SWT.COLOR_YELLOW));
    combo.setItems("Option 1...", "Option 2...", "Option 3...", "Option 4...");
    combo.select(1);
    combo.addSegmentListener(event -> {
        event.segments = new int[] { 0, event.lineText.length() };
        event.segmentsChars = new char[] { '\u202e', '\u202c' };
    });
    shell.setSize(500, 250);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    font.dispose();
    display.dispose();
}

From source file:com.example.bigtable.simplecli.Loader.java

public static void main(String argv[]) throws IOException {
    String inputFile = "/tmp/pagecounts-20160101-000000";

    // Connect// w ww . j a v  a 2 s  .c  o  m
    Connection bigTableConnection = ConnectionFactory.createConnection();

    // Load the file, and do stuff each row
    Stream<String> stream = Files.lines(Paths.get(inputFile));
    stream.forEach(row -> {

        String[] splitRow = row.split(" ");
        assert splitRow.length == 4 : "unexpected row " + row;

        String hour = "20160101-000000"; //from file name
        String language = splitRow[0];
        String title = splitRow[1];
        String requests = splitRow[2];
        String size = splitRow[3];

        assert language.length() == 2 : "unexpected language size" + language;

        // create a row key
        // [languageCode]-[title md5]-[hour]
        String rowKey = language + "-" + DigestUtils.md5Hex(title) + "-" + hour;
        System.out.println(rowKey);

        // Put it into Bigtable - [table name]
        try {
            Table table = bigTableConnection.getTable(TableName.valueOf("wikipedia-stats"));

            // Create a new Put request.
            Put put = new Put(Bytes.toBytes(rowKey));

            // Add columns: [column family], [column], [data]
            put.addColumn(Bytes.toBytes("traffic"), Bytes.toBytes("requests"), Bytes.toBytes(requests));
            put.addColumn(Bytes.toBytes("traffic"), Bytes.toBytes("size"), Bytes.toBytes(size));

            // Execute the put on the table.
            table.put(put);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });

    // Clean up
    bigTableConnection.close();
}

From source file:com.github.brandtg.switchboard.FileLogAggregator.java

/** Main. */
public static void main(String[] args) throws Exception {
    Options opts = new Options();
    opts.addOption("h", "help", false, "Prints help message");
    opts.addOption("f", "file", true, "File to output aggregated logs to");
    opts.addOption("s", "separator", true, "Line separator in log");
    CommandLine cli = new GnuParser().parse(opts, args);

    if (cli.getArgs().length == 0 || cli.hasOption("help")) {
        new HelpFormatter().printHelp("usage: [opts] sourceHost:port ...", opts);
        System.exit(1);/*from w ww  .  jav  a 2 s .c  om*/
    }

    // Parse sources
    Set<InetSocketAddress> sources = new HashSet<>();
    for (int i = 0; i < cli.getArgs().length; i++) {
        String[] tokens = cli.getArgs()[i].split(":");
        sources.add(new InetSocketAddress(tokens[0], Integer.valueOf(tokens[1])));
    }

    // Parse output stream
    OutputStream outputStream;
    if (cli.hasOption("file")) {
        outputStream = new FileOutputStream(cli.getOptionValue("file"));
    } else {
        outputStream = System.out;
    }

    // Separator
    String separator = cli.getOptionValue("separator", "\n");
    if (separator.length() != 1) {
        throw new IllegalArgumentException("Separator must only be 1 character");
    }

    final FileLogAggregator fileLogAggregator = new FileLogAggregator(sources, separator.charAt(0),
            outputStream);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                fileLogAggregator.stop();
            } catch (Exception e) {
                LOG.error("Error when stopping log aggregator", e);
            }
        }
    });

    fileLogAggregator.start();
}

From source file:dhtaccess.tools.Put.java

public static void main(String[] args) {
    byte[] secret = null;
    int ttl = 3600;

    // parse properties
    Properties prop = System.getProperties();
    String gateway = prop.getProperty("dhtaccess.gateway");
    if (gateway == null || gateway.length() <= 0) {
        gateway = DEFAULT_GATEWAY;// w  ww . j  a v a  2 s.co m
    }

    // parse options
    Options options = new Options();
    options.addOption("h", "help", false, "print help");
    options.addOption("g", "gateway", true, "gateway URI, list at http://opendht.org/servers.txt");
    options.addOption("s", "secret", true, "can be used to remove the value later");
    options.addOption("t", "ttl", true, "how long (in seconds) to store the value");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println("There is an invalid option.");
        e.printStackTrace();
        System.exit(1);
    }

    String optVal;
    if (cmd.hasOption('h')) {
        usage(COMMAND);
        System.exit(1);
    }
    optVal = cmd.getOptionValue('g');
    if (optVal != null) {
        gateway = optVal;
    }
    optVal = cmd.getOptionValue('s');
    if (optVal != null) {
        try {
            secret = optVal.getBytes(ENCODE);
        } catch (UnsupportedEncodingException e) {
            // NOTREACHED
        }
    }
    optVal = cmd.getOptionValue('t');
    if (optVal != null) {
        ttl = Integer.parseInt(optVal);
    }

    args = cmd.getArgs();

    // parse arguments
    if (args.length < 2) {
        usage(COMMAND);
        System.exit(1);
    }

    for (int index = 0; index + 1 < args.length; index += 2) {
        byte[] key = null, value = null;
        try {
            key = args[index].getBytes(ENCODE);
            value = args[index + 1].getBytes(ENCODE);
        } catch (UnsupportedEncodingException e1) {
            // NOTREACHED
        }

        // prepare for RPC
        DHTAccessor accessor = null;
        try {
            accessor = new DHTAccessor(gateway);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            System.exit(1);
        }

        // RPC
        int res = accessor.put(key, value, ttl, secret);

        String resultString;
        switch (res) {
        case 0:
            resultString = "Success";
            break;
        case 1:
            resultString = "Capacity";
            break;
        case 2:
            resultString = "Again";
            break;
        default:
            resultString = "???";
        }
        System.out.println(resultString + ": " + args[index] + ", " + args[index + 1]);
    }
}

From source file:NewStyle.java

public static void main(String args[]) {

    // Now, list holds references of type String. 
    ArrayList<String> list = new ArrayList<String>();

    list.add("one");
    list.add("two");
    list.add("three");
    list.add("four");

    // Notice that Iterator is also generic. 
    Iterator<String> itr = list.iterator();

    // The following statement will now cause a compile-time eror. 
    //    Iterator<Integer> itr = list.iterator(); // Error! 

    while (itr.hasNext()) {
        String str = itr.next(); // no cast needed 

        // Now, the following line is a compile-time, 
        // rather than runtime, error. 
        //    Integer i = itr.next(); // this won't compile 

        System.out.println(str + " is " + str.length() + " chars long.");
    }//from www . j a v a2s . c  o  m
}