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:org.eclipse.swt.snippets.Snippet146.java

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("Snippet 146");
    final Text text = new Text(shell, SWT.BORDER);
    text.setSize(text.computeSize(150, SWT.DEFAULT));
    shell.pack();/*  www .j a  v a  2  s  .  c om*/
    shell.open();
    new Thread() {
        @Override
        public void run() {
            // wait for shell to be opened
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
            }

            String string = "Love the method.";
            for (int i = 0; i < string.length(); i++) {
                char ch = string.charAt(i);
                boolean shift = Character.isUpperCase(ch);
                ch = Character.toLowerCase(ch);
                if (shift) {
                    Event event = new Event();
                    event.type = SWT.KeyDown;
                    event.keyCode = SWT.SHIFT;
                    display.post(event);
                }
                Event event = new Event();
                event.type = SWT.KeyDown;
                event.character = ch;
                display.post(event);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                }
                event.type = SWT.KeyUp;
                display.post(event);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
                if (shift) {
                    event = new Event();
                    event.type = SWT.KeyUp;
                    event.keyCode = SWT.SHIFT;
                    display.post(event);
                }
            }
        }
    }.start();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:org.alfresco.util.xml.SchemaHelper.java

public static void main(String... args) {
    if (args.length < 2 || !args[0].startsWith("--compile-xsd=") && !args[1].startsWith("--output-dir=")) {
        System.out.println("Usage: SchemaHelper --compile-xsd=<URL> --output-dir=<directory>");
        System.exit(1);//from   ww  w  .  j a  v  a2s. c  om
    }
    final String urlStr = args[0].substring(14);
    if (urlStr.length() == 0) {
        System.out.println("Usage: SchemaHelper --compile-xsd=<URL> --output-dir=<directory>");
        System.exit(1);
    }
    final String dirStr = args[1].substring(13);
    if (dirStr.length() == 0) {
        System.out.println("Usage: SchemaHelper --compile-xsd=<URL> --output-dir=<directory>");
        System.exit(1);
    }
    try {
        URL url = ResourceUtils.getURL(urlStr);
        File dir = new File(dirStr);
        if (!dir.exists() || !dir.isDirectory()) {
            System.out.println("Output directory not found: " + dirStr);
            System.exit(1);
        }

        ErrorListener errorListener = new ErrorListener() {
            public void warning(SAXParseException e) {
                System.out.println("WARNING: " + e.getMessage());
            }

            public void info(SAXParseException e) {
                System.out.println("INFO: " + e.getMessage());
            }

            public void fatalError(SAXParseException e) {
                handleException(urlStr, e);
            }

            public void error(SAXParseException e) {
                handleException(urlStr, e);
            }
        };

        SchemaCompiler compiler = XJC.createSchemaCompiler();
        compiler.setErrorListener(errorListener);
        compiler.parseSchema(new InputSource(url.toExternalForm()));
        S2JJAXBModel model = compiler.bind();
        if (model == null) {
            System.out.println("Failed to produce binding model for URL " + urlStr);
            System.exit(1);
        }
        JCodeModel codeModel = model.generateCode(null, errorListener);
        codeModel.build(dir);
    } catch (Throwable e) {
        handleException(urlStr, e);
        System.exit(1);
    }
}

From source file:com.jabyftw.StringLengthTest.java

public static void main(String[] args) {
    try {// w  ww. j  a  va 2 s .com
        // Make it the range of the password
        for (int length = 4; length <= 26; length++) {
            String string = RandomStringUtils.random(length, true, true);
            String encryptedString = Util.encryptString(string);
            System.out.println("Encrypting a " + length + " string resulted on a " + encryptedString.length()
                    + " encrypted length string: " + string + " -> " + encryptedString);
        }

        // Set variables for testing
        String IN = "N3VIg4dv1FO0LQuauHeuC6",
                PRE_ENCRYPTED_OUT = "4be9cc85bf5abc7cb99019a84256e938fbc4fbafa80598b297dc8bc3e22f11dd";

        // Testing if it is safe on every example
        String encryptionOut = Util.encryptString(IN);
        System.out.println("\nTesting safety: (" + encryptionOut + " == " + PRE_ENCRYPTED_OUT + " )? "
                + encryptionOut.equals(PRE_ENCRYPTED_OUT));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    // Test passed, every encrypted string is 64 letters length
}

From source file:com.sm.test.TestClusterClient.java

public static void main(String[] args) throws Exception {
    String[] opts = new String[] { "-configPath", "-url", "-store", "-times", "-nio", "-size" };
    String[] defaults = new String[] { "", "localhost:7100", "store", "2", "true", "2000" };
    String[] paras = getOpts(args, opts, defaults);

    String configPath = paras[0];
    if (configPath.length() == 0) {
        //logger.error("missing config path or host");
        //throw new RuntimeException("missing -configPath or -host");
    }/*from w ww . ja v  a 2s  .  com*/

    String url = paras[1];
    String store = paras[2];
    int times = Integer.valueOf(paras[3]);
    boolean nio = Boolean.valueOf(paras[4]);
    int size = Integer.valueOf(paras[5]);
    ClusterClientFactory ccf = ClusterClientFactory.connect(url, store, new HessianSerializer(),
            TCPClientFactory.ClientType.Netty);
    ClusterClient client = ccf.getDefaultStore(3000);
    TestClusterClient testClient = new TestClusterClient(client);
    client.put(Key.createKey("test-0"), "test-0");
    testClient.testMultiPut(500);
    testClient.testMultiGet(500);
    testClient.testScan(500);
    testClient.testScanCursor(500);
    Value v = client.get(Key.createKey("test-0"));
    System.out.println(v.getData());
    //ccf.reloadClusterClient();
    client.close();
    ccf.close();
}

From source file:HttpMirror.java

public static void main(String args[]) {
    try {//w ww.  j  a  v a  2  s.co m
        // Get the port to listen on
        int port = Integer.parseInt(args[0]);
        // Create a ServerSocket to listen on that port.
        ServerSocket ss = new ServerSocket(port);
        // Now enter an infinite loop, waiting for & handling connections.
        for (;;) {
            // Wait for a client to connect. The method will block;
            // when it returns the socket will be connected to the client
            Socket client = ss.accept();

            // Get input and output streams to talk to the client
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            PrintWriter out = new PrintWriter(client.getOutputStream());

            // Start sending our reply, using the HTTP 1.1 protocol
            out.print("HTTP/1.1 200 \r\n"); // Version & status code
            out.print("Content-Type: text/plain\r\n"); // The type of data
            out.print("Connection: close\r\n"); // Will close stream
            out.print("\r\n"); // End of headers

            // Now, read the HTTP request from the client, and send it
            // right back to the client as part of the body of our
            // response. The client doesn't disconnect, so we never get
            // an EOF. It does sends an empty line at the end of the
            // headers, though. So when we see the empty line, we stop
            // reading. This means we don't mirror the contents of POST
            // requests, for example. Note that the readLine() method
            // works with Unix, Windows, and Mac line terminators.
            String line;
            while ((line = in.readLine()) != null) {
                if (line.length() == 0)
                    break;
                out.print(line + "\r\n");
            }

            // Close socket, breaking the connection to the client, and
            // closing the input and output streams
            out.close(); // Flush and close the output stream
            in.close(); // Close the input stream
            client.close(); // Close the socket itself
        } // Now loop again, waiting for the next connection
    }
    // If anything goes wrong, print an error message
    catch (Exception e) {
        System.err.println(e);
        System.err.println("Usage: java HttpMirror <port>");
    }
}

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

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 289");
    shell.setLayout(new FillLayout());
    final Combo combo = new Combo(shell, SWT.NONE);
    combo.setItems("1111", "2222", "3333", "4444");
    combo.setText(combo.getItem(0));/*from   w  w  w  . ja  v a  2  s .c  o  m*/
    combo.addVerifyListener(e -> {
        String text = combo.getText();
        String newText = text.substring(0, e.start) + e.text + text.substring(e.end);
        try {
            if (newText.length() != 0)
                Integer.parseInt(newText);
        } catch (NumberFormatException ex) {
            e.doit = false;
        }
    });
    combo.addTraverseListener(e -> {
        if (e.detail == SWT.TRAVERSE_RETURN) {
            e.doit = false;
            e.detail = SWT.TRAVERSE_NONE;
            String newText = combo.getText();
            try {
                Integer.parseInt(newText);
                combo.add(newText);
                combo.setSelection(new Point(0, newText.length()));
            } catch (NumberFormatException ex) {
            }
        }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:MainClass.java

public static void main(String[] a) {
    Display display = new Display();

    // Create the main window
    Shell shell = new Shell(display);

    Text fahrenheit = new Text(shell, SWT.BORDER);
    fahrenheit.setData("Type a temperature in Fahrenheit");
    fahrenheit.setBounds(20, 20, 100, 20);

    fahrenheit.addVerifyListener(new VerifyListener() {
        public void verifyText(VerifyEvent event) {
            // Assume we don't allow it
            event.doit = false;//from   w w  w . j av  a 2 s  .  co m

            // Get the character typed
            char myChar = event.character;
            String text = ((Text) event.widget).getText();

            // Allow '-' if first character
            if (myChar == '-' && text.length() == 0)
                event.doit = true;

            // Allow 0-9
            if (Character.isDigit(myChar))
                event.doit = true;

            // Allow backspace
            if (myChar == '\b')
                event.doit = true;
        }

    });
    shell.open();

    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    display.dispose();
}

From source file:com.blacklocus.qs.worker.RandomStdoutTasksExample.java

public static void main(String[] args) {
    // Mock our source of tasks.
    final BlockingQueue<QSTaskModel> workQueue = new SynchronousQueue<QSTaskModel>();

    // Generates tasks
    new Thread(new ExceptingRunnable() {
        @Override//w ww . jav a2 s.c om
        protected void go() throws Exception {
            while (true) {
                workQueue.put(new QSTaskModel(null, "" + RandomUtils.nextInt(), "stdout", 1,
                        new Params(RandomStringUtils.randomAscii(RandomUtils.nextInt(32)))));
            }
        }
    }).start();

    // All this worker does is log an extra message describing the length of the "message" param.
    QSWorker<Params> worker = new AbstractQSWorker<Params>() {
        @Override
        public String getHandlerName() {
            // This identifies the type of task this worker can handle. In our task generator above, the
            // tasks are created with the same handler identifier "stdout".
            return "stdout";
        }

        @Override
        public TaskKit<Params> convert(TaskKitFactory<Params> factory) throws Exception {
            return factory.newTaskKit(Params.class);
        }

        @Override
        public Object process(TaskKit<Params> kit) throws Exception {
            String msg = kit.params().message;
            kit.log(msg + " is " + msg.length() + " characters long");
            return null;
        }
    };

    QSAssembly.newBuilder()

            // The source of work.
            .taskServices(new BlockingQueueQSTaskService(workQueue))

            // Logging service which records task start, task-specific logging, task end.
            .logService(new SystemOutQSLogService())

            // Service that helps identify the machine completing tasks, this machine.
            .workerIdService(new HostNameQSWorkerIdService())

            // The worker logic observed by this instance.
            .workers(worker)

            // Run it in the current thread.
            .build().run();
}

From source file:com.sm.store.server.ClusterServer.java

public static void main(String[] args) {
    String[] opts = new String[] { "-host", "-configPath", "-dataPath", "-port", "replicaPort", "-start",
            "-freq" };
    String[] defaults = new String[] { "", "", "", "0", "0", "true", "0" };
    String[] paras = getOpts(args, opts, defaults);

    String configPath = paras[1];
    if (configPath.length() == 0) {
        logger.error("missing config path");
        throw new RuntimeException("missing -configPath");
    }//from  ww  w  .j ava2 s .  c  o m
    //set configPath to system properties
    System.setProperty("configPath", configPath);
    NodeConfig nodeConfig = getNodeConfig(configPath + "/node.properties");
    //int clusterNo = Integer.valueOf( paras[0]);
    String dataPath = paras[2];
    if (dataPath.length() == 0) {
        dataPath = "./data";
    }
    int port = Integer.valueOf(paras[3]);
    int replicaPort = Integer.valueOf(paras[4]);
    //get from command line, if not form nodeConfig
    if (port == 0)
        port = nodeConfig.getPort();
    if (port == 0) {
        throw new RuntimeException("port is 0");
    } else {
        if (replicaPort == 0)
            replicaPort = port + 1;
    }
    boolean start = Boolean.valueOf(paras[5]);
    String host = paras[0];
    //get from command line, if not form nodeConfig or from getHost
    if (host.length() == 0)
        host = nodeConfig.getHost();
    if (host.length() == 0)
        host = getLocalHost();
    int freq = Integer.valueOf(paras[6]);
    logger.info("read clusterNode and storeConfig from " + configPath);
    BuildClusterNodes bcn = new BuildClusterNodes(configPath + "/clusters.xml");
    //BuildStoreConfig bsc = new BuildStoreConfig(configPath+"/stores.xml");
    BuildRemoteConfig brc = new BuildRemoteConfig(configPath + "/stores.xml");
    List<ClusterNodes> clusterNodesList = bcn.build();
    short clusterNo = findClusterNo(host + ":" + port, clusterNodesList);
    logger.info("create cluster server config for cluster " + clusterNo + " host " + host + " port " + port
            + " replica port " + replicaPort);
    ClusterServerConfig serverConfig = new ClusterServerConfig(clusterNodesList, brc.build().getConfigList(),
            clusterNo, dataPath, configPath, port, replicaPort, host);
    //over write config from command line if freq > 0
    if (freq > 0)
        serverConfig.setFreq(freq);
    logger.info("create cluster server");
    ClusterStoreServer cs = new ClusterStoreServer(serverConfig, new HessianSerializer());
    // start replica server
    cs.startReplicaServer();
    logger.info("hookup jvm shutdown process");
    cs.hookShutdown();
    if (start) {
        logger.info("server is starting " + cs.getServerConfig().toString());
        cs.start();
    } else
        logger.warn("server is staged and wait to be started");

    List list = new ArrayList();
    //add jmx metric
    List<String> stores = cs.getAllStoreNames();
    for (String store : stores) {
        list.add(cs.getStore(store));
    }
    list.add(cs);
    stores.add("ClusterServer");
    JmxService jms = new JmxService(list, stores);
}

From source file:bariopendatalab.ImportData.java

/**
 * @param args the command line arguments
 *///from ww w .  j ava 2s. c o  m
public static void main(String[] args) {
    int i = 0;
    try {
        MongoClient client = new MongoClient("localhost", 27017);
        DBAccess dbaccess = new DBAccess(client);
        dbaccess.dropDB();
        dbaccess.createDB();
        FileReader reader = new FileReader(new File(args[0]));
        Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().withIgnoreEmptyLines().withDelimiter(',')
                .parse(reader);
        i = 2;
        for (CSVRecord record : records) {
            String type = record.get("Tipologia");
            if (type == null || type.length() == 0) {
                Logger.getLogger(ImportData.class.getName()).log(Level.WARNING, "No type in line {0}", i);
            }

            String description = record.get("Nome");
            if (description != null && description.length() == 0) {
                description = null;
            }

            String address = record.get("Indirizzo");
            if (address != null && address.length() == 0) {
                address = null;
            }

            String civ = record.get("Civ");
            if (civ != null && civ.length() == 0) {
                civ = null;
            }

            if (address != null && civ != null) {
                address += ", " + civ;
            }

            String note = record.get("Note");
            if (note != null && note.length() == 0) {
                note = null;
            }

            String longitudine = record.get("Longitudine");
            String latitudine = record.get("Latitudine");
            if (longitudine != null && latitudine != null) {
                if (longitudine.length() > 0 && latitudine.length() > 0) {
                    try {
                        dbaccess.insert(type, description, address, note, Utils
                                .get2DPoint(Double.parseDouble(latitudine), Double.parseDouble(longitudine)));
                    } catch (NumberFormatException nex) {
                        dbaccess.insert(type, description, address, note, null);
                    }
                } else {
                    dbaccess.insert(type, description, address, note, null);
                }
            } else {
                dbaccess.insert(type, description, address, note, null);
            }
            i++;
        }
        reader.close();
    } catch (Exception ex) {
        Logger.getLogger(ImportData.class.getName()).log(Level.SEVERE, "Error line " + i, ex);
    }
}