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:com.setronica.ucs.server.MessageServer.java

public static void main(String[] args) throws Exception {
    String hostname = System.getProperty("host", "localhost");
    String portStr = System.getProperty("port", "1985");
    Integer port = Integer.valueOf(portStr);
    String zkConnect = System.getProperty("zkConnect");

    if (zkConnect != null && zkConnect.length() > 0) {
        MessageServer server = new MessageServer();
        server.registerService(hostname, port, zkConnect);
    } else {/*from www . j  av  a2s  .  c  o m*/
        ClassPathXmlApplicationContext applicationContext = bootstrapMemory();
        EventLoop eventLoop = createMsgPackRPCServer(applicationContext, hostname, port);
        try {
            eventLoop.join();
        } catch (InterruptedException e) {
            eventLoop.shutdown();
            eventLoop.join();
        }
    }
}

From source file:com.gzj.tulip.jade.statement.SystemInterpreter.java

public static void main(String[] args) throws Exception {
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("table", "my_table_name");
    parameters.put("id", "my_id");
    parameters.put(":1", "first_param");

    final Pattern PATTERN = Pattern.compile("\\{([a-zA-Z0-9_\\.\\:]+)\\}|##\\((.+)\\)");

    String sql = "select form ##(:table) {name} where {id}='{1}'";

    StringBuilder sb = new StringBuilder(sql.length() + 200);
    Matcher matcher = PATTERN.matcher(sql);
    int start = 0;
    while (matcher.find(start)) {
        sb.append(sql.substring(start, matcher.start()));
        String group = matcher.group();
        String key = null;/*from www  .  j a  v  a  2  s.  c om*/
        if (group.startsWith("{")) {
            key = matcher.group(1);
        } else if (group.startsWith("##(")) {
            key = matcher.group(2);
        }
        System.out.println(key);
        if (key == null || key.length() == 0) {
            continue;
        }
        Object value = parameters.get(key); // {paramName}?{:1}?
        if (value == null) {
            if (key.startsWith(":") || key.startsWith("$")) {
                value = parameters.get(key.substring(1)); // {:paramName}
            } else {
                char ch = key.charAt(0);
                if (ch >= '0' && ch <= '9') {
                    value = parameters.get(":" + key); // {1}?
                }
            }
        }
        if (value == null) {
            value = parameters.get(key); // ?
        }
        if (value != null) {
            sb.append(value);
        } else {
            sb.append(group);
        }
        start = matcher.end();
    }
    sb.append(sql.substring(start));
    System.out.println(sb);

}

From source file:com.cyberway.issue.crawler.extractor.ExtractorTool.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(new Option("h", "help", false, "Prints this message and exits."));
    StringBuffer defaultExtractors = new StringBuffer();
    for (int i = 0; i < DEFAULT_EXTRACTORS.length; i++) {
        if (i > 0) {
            defaultExtractors.append(", ");
        }//  w  ww . j a  v  a2 s. c o  m
        defaultExtractors.append(DEFAULT_EXTRACTORS[i]);
    }
    options.addOption(new Option("e", "extractor", true,
            "List of comma-separated extractor class names. " + "Run in order listed. "
                    + "If no extractors listed, runs following: " + defaultExtractors.toString() + "."));
    options.addOption(
            new Option("s", "scratch", true, "Directory to write scratch files to. Default: '/tmp'."));
    PosixParser parser = new PosixParser();
    CommandLine cmdline = parser.parse(options, args, false);
    List cmdlineArgs = cmdline.getArgList();
    Option[] cmdlineOptions = cmdline.getOptions();
    HelpFormatter formatter = new HelpFormatter();
    // If no args, print help.
    if (cmdlineArgs.size() <= 0) {
        usage(formatter, options, 0);
    }

    // Now look at options passed.
    String[] extractors = DEFAULT_EXTRACTORS;
    String scratch = null;
    for (int i = 0; i < cmdlineOptions.length; i++) {
        switch (cmdlineOptions[i].getId()) {
        case 'h':
            usage(formatter, options, 0);
            break;

        case 'e':
            String value = cmdlineOptions[i].getValue();
            if (value == null || value.length() <= 0) {
                // Allow saying NO extractors so we can see
                // how much it costs just reading through
                // ARCs.
                extractors = new String[0];
            } else {
                extractors = value.split(",");
            }
            break;

        case 's':
            scratch = cmdlineOptions[i].getValue();
            break;

        default:
            throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId());
        }
    }

    ExtractorTool tool = new ExtractorTool(extractors, scratch);
    for (Iterator i = cmdlineArgs.iterator(); i.hasNext();) {
        tool.extract((String) i.next());
    }
}

From source file:fuse.okuyamafs.OkuyamaFuse.java

public static void main(String[] args) {

    String fuseArgs[] = new String[args.length - 1];
    System.arraycopy(args, 0, fuseArgs, 0, fuseArgs.length);

    ImdstDefine.valueCompresserLevel = 9;
    try {/*from www  . j a  va  2  s  .  c  o m*/
        String okuyamaStr = args[args.length - 1];

        // Raid0?????????
        if (okuyamaStr.indexOf("#") != -1) {
            stripingDataBlock = true;
            okuyamaStr = okuyamaStr.substring(0, (okuyamaStr.length() - 1));
        }

        String[] masterNodeInfos = null;
        if (okuyamaStr.indexOf(",") != -1) {
            masterNodeInfos = okuyamaStr.split(",");
        } else {
            masterNodeInfos = (okuyamaStr + "," + okuyamaStr).split(",");
        }
        // 1=Memory
        // 2=okuyama
        // 3=LocalCacheOkuyama

        String[] optionParams = { "2", "true" };
        String fsystemMode = optionParams[0].trim();
        boolean singleFlg = new Boolean(optionParams[1].trim()).booleanValue();

        OkuyamaFilesystem.storageType = new Integer(fsystemMode).intValue();
        if (OkuyamaFilesystem.storageType == 1)
            OkuyamaFilesystem.blockSize = OkuyamaFilesystem.blockSize;

        CoreMapFactory.init(new Integer(fsystemMode.trim()).intValue(), masterNodeInfos, stripingDataBlock);
        FilesystemCheckDaemon loopDaemon = new FilesystemCheckDaemon(1, fuseArgs[fuseArgs.length - 1]);
        loopDaemon.start();

        if (OkuyamaFilesystem.storageType == 2) {
            FilesystemCheckDaemon bufferCheckDaemon = new FilesystemCheckDaemon(2, null);
            bufferCheckDaemon.start();
        }

        Runtime.getRuntime().addShutdownHook(new JVMShutdownSequence());
        FuseMount.mount(fuseArgs, new OkuyamaFilesystem(fsystemMode, singleFlg), log);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:HttpGet.java

public static void main(String[] args) {
    SocketChannel server = null; // Channel for reading from server
    FileOutputStream outputStream = null; // Stream to destination file
    WritableByteChannel destination; // Channel to write to it

    try { // Exception handling and channel closing code follows this block

        // Parse the URL. Note we use the new java.net.URI, not URL here.
        URI uri = new URI(args[0]);

        // Now query and verify the various parts of the URI
        String scheme = uri.getScheme();
        if (scheme == null || !scheme.equals("http"))
            throw new IllegalArgumentException("Must use 'http:' protocol");

        String hostname = uri.getHost();

        int port = uri.getPort();
        if (port == -1)
            port = 80; // Use default port if none specified

        String path = uri.getRawPath();
        if (path == null || path.length() == 0)
            path = "/";

        String query = uri.getRawQuery();
        query = (query == null) ? "" : '?' + query;

        // Combine the hostname and port into a single address object.
        // java.net.SocketAddress and InetSocketAddress are new in Java 1.4
        SocketAddress serverAddress = new InetSocketAddress(hostname, port);

        // Open a SocketChannel to the server
        server = SocketChannel.open(serverAddress);

        // Put together the HTTP request we'll send to the server.
        String request = "GET " + path + query + " HTTP/1.1\r\n" + // The request
                "Host: " + hostname + "\r\n" + // Required in HTTP 1.1
                "Connection: close\r\n" + // Don't keep connection open
                "User-Agent: " + HttpGet.class.getName() + "\r\n" + "\r\n"; // Blank
                                                                            // line
                                                                            // indicates
                                                                            // end of
                                                                            // request
                                                                            // headers

        // Now wrap a CharBuffer around that request string
        CharBuffer requestChars = CharBuffer.wrap(request);

        // Get a Charset object to encode the char buffer into bytes
        Charset charset = Charset.forName("ISO-8859-1");

        // Use the charset to encode the request into a byte buffer
        ByteBuffer requestBytes = charset.encode(requestChars);

        // Finally, we can send this HTTP request to the server.
        server.write(requestBytes);//from www  . j  a  v  a  2 s  . c  o  m

        // Set up an output channel to send the output to.
        if (args.length > 1) { // Use a specified filename
            outputStream = new FileOutputStream(args[1]);
            destination = outputStream.getChannel();
        } else
            // Or wrap a channel around standard out
            destination = Channels.newChannel(System.out);

        // Allocate a 32 Kilobyte byte buffer for reading the response.
        // Hopefully we'll get a low-level "direct" buffer
        ByteBuffer data = ByteBuffer.allocateDirect(32 * 1024);

        // Have we discarded the HTTP response headers yet?
        boolean skippedHeaders = false;
        // The code sent by the server
        int responseCode = -1;

        // Now loop, reading data from the server channel and writing it
        // to the destination channel until the server indicates that it
        // has no more data.
        while (server.read(data) != -1) { // Read data, and check for end
            data.flip(); // Prepare to extract data from buffer

            // All HTTP reponses begin with a set of HTTP headers, which
            // we need to discard. The headers end with the string
            // "\r\n\r\n", or the bytes 13,10,13,10. If we haven't already
            // skipped them then do so now.
            if (!skippedHeaders) {
                // First, though, read the HTTP response code.
                // Assume that we get the complete first line of the
                // response when the first read() call returns. Assume also
                // that the first 9 bytes are the ASCII characters
                // "HTTP/1.1 ", and that the response code is the ASCII
                // characters in the following three bytes.
                if (responseCode == -1) {
                    responseCode = 100 * (data.get(9) - '0') + 10 * (data.get(10) - '0')
                            + 1 * (data.get(11) - '0');

                    // If there was an error, report it and quit
                    // Note that we do not handle redirect responses.
                    if (responseCode < 200 || responseCode >= 300) {
                        System.err.println("HTTP Error: " + responseCode);
                        System.exit(1);
                    }
                }

                // Now skip the rest of the headers.
                try {
                    for (;;) {
                        if ((data.get() == 13) && (data.get() == 10) && (data.get() == 13)
                                && (data.get() == 10)) {
                            skippedHeaders = true;
                            break;
                        }
                    }
                } catch (BufferUnderflowException e) {
                    // If we arrive here, it means we reached the end of
                    // the buffer and didn't find the end of the headers.
                    // There is a chance that the last 1, 2, or 3 bytes in
                    // the buffer were the beginning of the \r\n\r\n
                    // sequence, so back up a bit.
                    data.position(data.position() - 3);
                    // Now discard the headers we have read
                    data.compact();
                    // And go read more data from the server.
                    continue;
                }
            }

            // Write the data out; drain the buffer fully.
            while (data.hasRemaining())
                destination.write(data);

            // Now that the buffer is drained, put it into fill mode
            // in preparation for reading more data into it.
            data.clear(); // data.compact() also works here
        }
    } catch (Exception e) { // Report any errors that arise
        System.err.println(e);
        System.err.println("Usage: java HttpGet <URL> [<filename>]");
    } finally { // Close the channels and output file stream, if needed
        try {
            if (server != null && server.isOpen())
                server.close();
            if (outputStream != null)
                outputStream.close();
        } catch (IOException e) {
        }
    }
}

From source file:MainClass.java

public static void main(String args[]) {
    String org = "This is a test. This is, too.";
    String search = "is";
    String sub = "was";
    String result = "";
    int i;//  w  ww .  java2 s .c  om

    do {
        System.out.println(org);
        i = org.indexOf(search);
        if (i != -1) {
            result = org.substring(0, i);
            result = result + sub;
            result = result + org.substring(i + search.length());
            org = result;
        }
    } while (i != -1);

}

From source file:Main.java

License:asdf

public static void main(String[] args) throws Exception {
    RandomAccessFile randomAccessFile = null;

    String line1 = "line\n";
    String line2 = "asdf1234\n";

    // read / write permissions
    randomAccessFile = new RandomAccessFile("yourFile.dat", "rw");

    randomAccessFile.writeBytes(line1);/*from  w w w . j a v a2  s  .  c  o  m*/
    randomAccessFile.writeBytes(line2);

    // Place the file pointer at the end of the first line
    randomAccessFile.seek(line1.length());

    byte[] buffer = new byte[line2.length()];
    randomAccessFile.read(buffer);
    System.out.println(new String(buffer));

    randomAccessFile.close();
}

From source file:TreeCellEditor.java

public static void main(String[] args) {
    final Display display = new Display();
    final Color black = display.getSystemColor(SWT.COLOR_BLACK);
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    final Tree tree = new Tree(shell, SWT.BORDER);
    for (int i = 0; i < 16; i++) {
        TreeItem itemI = new TreeItem(tree, SWT.NONE);
        itemI.setText("Item " + i);
        for (int j = 0; j < 16; j++) {
            TreeItem itemJ = new TreeItem(itemI, SWT.NONE);
            itemJ.setText("Item " + j);
        }// w w w. j  a v a  2s . c om
    }
    final TreeItem[] lastItem = new TreeItem[1];
    final TreeEditor editor = new TreeEditor(tree);
    tree.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event event) {
            final TreeItem item = (TreeItem) event.item;
            if (item != null && item == lastItem[0]) {
                boolean isCarbon = SWT.getPlatform().equals("carbon");
                final Composite composite = new Composite(tree, SWT.NONE);
                if (!isCarbon)
                    composite.setBackground(black);
                final Text text = new Text(composite, SWT.NONE);
                final int inset = isCarbon ? 0 : 1;
                composite.addListener(SWT.Resize, new Listener() {
                    public void handleEvent(Event e) {
                        Rectangle rect = composite.getClientArea();
                        text.setBounds(rect.x + inset, rect.y + inset, rect.width - inset * 2,
                                rect.height - inset * 2);
                    }
                });
                Listener textListener = new Listener() {
                    public void handleEvent(final Event e) {
                        switch (e.type) {
                        case SWT.FocusOut:
                            item.setText(text.getText());
                            composite.dispose();
                            break;
                        case SWT.Verify:
                            String newText = text.getText();
                            String leftText = newText.substring(0, e.start);
                            String rightText = newText.substring(e.end, newText.length());
                            GC gc = new GC(text);
                            Point size = gc.textExtent(leftText + e.text + rightText);
                            gc.dispose();
                            size = text.computeSize(size.x, SWT.DEFAULT);
                            editor.horizontalAlignment = SWT.LEFT;
                            Rectangle itemRect = item.getBounds(), rect = tree.getClientArea();
                            editor.minimumWidth = Math.max(size.x, itemRect.width) + inset * 2;
                            int left = itemRect.x, right = rect.x + rect.width;
                            editor.minimumWidth = Math.min(editor.minimumWidth, right - left);
                            editor.minimumHeight = size.y + inset * 2;
                            editor.layout();
                            break;
                        case SWT.Traverse:
                            switch (e.detail) {
                            case SWT.TRAVERSE_RETURN:
                                item.setText(text.getText());
                                // FALL THROUGH
                            case SWT.TRAVERSE_ESCAPE:
                                composite.dispose();
                                e.doit = false;
                            }
                            break;
                        }
                    }
                };
                text.addListener(SWT.FocusOut, textListener);
                text.addListener(SWT.Traverse, textListener);
                text.addListener(SWT.Verify, textListener);
                editor.setEditor(composite, item);
                text.setText(item.getText());
                text.selectAll();
                text.setFocus();
            }
            lastItem[0] = item;
        }
    });
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:Main.java

License:asdf

public static void main(String[] args) throws Exception {
    RandomAccessFile randomAccessFile = null;

    String line1 = "java2s.com\n";
    String line2 = "asdf1234\n";

    // read / write permissions
    randomAccessFile = new RandomAccessFile("yourFile.dat", "rw");

    randomAccessFile.writeBytes(line1);// w ww. ja va  2s . co m
    randomAccessFile.writeBytes(line2);

    // Place the file pointer at the end of the first line
    randomAccessFile.seek(line1.length());

    byte[] buffer = new byte[line2.length()];
    randomAccessFile.read(buffer);
    System.out.println(new String(buffer));

    randomAccessFile.close();
}

From source file:de.tudarmstadt.lt.lm.app.GenerateNgrams.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options opts = new Options();
    opts.addOption(OptionBuilder.withLongOpt("help").withDescription("Display help message.").create("?"));
    opts.addOption(OptionBuilder.withLongOpt("ptype").withArgName("class").hasArg().withDescription(
            "specify the instance of the language model provider that you want to use: {LtSegProvider, BreakIteratorStringProvider, UimaStringProvider, PreTokenizedStringProvider} (default: LtSegProvider)")
            .create("p"));
    opts.addOption(OptionBuilder.withLongOpt("cardinality").withArgName("ngram-order").hasArg().withDescription(
            "Specify the cardinality of the ngrams (min. 1). Specify a range using 'from-to'. (Examples: 5 = extract 5grams; 1-5 = extract 1grams, 2grams, ..., 5grams; default: 1-5).")
            .create("n"));
    opts.addOption(OptionBuilder.withLongOpt("dir").withArgName("directory").isRequired().hasArg()
            .withDescription(/* w w w.  ja  v a  2s  . co m*/
                    "specify the directory that contains '.txt' files that are used as source for generating ngrams.")
            .create("d"));
    opts.addOption(OptionBuilder.withLongOpt("overwrite").withDescription("Overwrite existing ngram file.")
            .create("w"));

    CommandLine cli = null;
    try {
        cli = new GnuParser().parse(opts, args);
    } catch (Exception e) {
        print_usage(opts, e.getMessage());
    }
    if (cli.hasOption("?"))
        print_usage(opts, null);

    AbstractStringProvider prvdr = null;
    try {
        prvdr = StartLM
                .getStringProviderInstance(cli.getOptionValue("ptype", LtSegProvider.class.getSimpleName()));
    } catch (Exception e) {
        print_usage(opts, String.format("Could not instantiate LmProvider '%s': %s",
                cli.getOptionValue("ptype", LtSegProvider.class.getSimpleName()), e.getMessage()));
    }

    String n_ = cli.getOptionValue("cardinality", "1-5");
    int dash_index = n_.indexOf('-');
    int n_e = Integer.parseInt(n_.substring(dash_index + 1, n_.length()).trim());
    int n_b = n_e;
    if (dash_index == 0)
        n_b = 1;
    if (dash_index > 0)
        n_b = Math.max(1, Integer.parseInt(n_.substring(0, dash_index).trim()));

    final File src_dir = new File(cli.getOptionValue("dir"));
    boolean overwrite = Boolean.parseBoolean(cli.getOptionValue("overwrite", "false"));

    generateNgrams(src_dir, prvdr, n_b, n_e, overwrite);

}