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:dhtaccess.tools.Get.java

public static void main(String[] args) {
    boolean details = false;

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

    // 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("d", "details", false, "print secret hash and TTL");

    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;
    }
    if (cmd.hasOption('d')) {
        details = true;
    }

    args = cmd.getArgs();

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

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

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

        // RPC
        if (args.length > 1) {
            System.out.println(args[index] + ":");
        }

        if (details) {
            Set<DetailedGetResult> results = accessor.getDetails(key);

            for (DetailedGetResult r : results) {
                String valString = null;
                try {
                    valString = new String((byte[]) r.getValue(), ENCODE);
                } catch (UnsupportedEncodingException e) {
                    // NOTREACHED
                }

                BigInteger hashedSecure = new BigInteger(1, (byte[]) r.getHashedSecret());

                System.out.println(valString + " " + r.getTTL() + " " + r.getHashType() + " 0x"
                        + ("0000000" + hashedSecure.toString(16)).substring(0, 8));
            }
        } else {
            Set<byte[]> results = accessor.get(key);

            for (byte[] valBytes : results) {
                try {
                    System.out.println(new String((byte[]) valBytes, ENCODE));
                } catch (UnsupportedEncodingException e) {
                    // NOTREACHED
                }
            }
        }
    } // for (int index = 0...
}

From source file:com.github.projectflink.testPlan.KryoTest.java

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

    // set up the execution environment
    final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

    // get input data
    DataSet<String> text = env.readTextFile(args[0]);
    boolean kryoMode = false;

    if (args[1].equals("kryo")) {
        kryoMode = true;// www .j  a  va  2  s.com
        DataSet<KryoType> ds = text.map(new MapFunction<String, KryoType>() {
            @Override
            public KryoType map(String s) throws Exception {
                KryoType kt = new KryoType();
                kt.elements = new ArrayList<Object>();
                String[] splits = s.split(" ");
                for (String split : splits) {
                    if (split == null || split.length() == 0)
                        continue;
                    if (StringUtils.isNumeric(split)) {
                        try {
                            kt.elements.add(Integer.valueOf(split));
                        } catch (Throwable t) {
                            kt.elements.add(Integer.valueOf(0));
                        }
                    } else {
                        kt.elements.add(split);
                    }
                }
                return kt;
            }
        });
        DataSet<Tuple2<Object, Integer>> ds1 = ds.rebalance()
                .map(new MapFunction<KryoType, Tuple2<Object, Integer>>() {
                    @Override
                    public Tuple2<Object, Integer> map(KryoType valueType) throws Exception {
                        return new Tuple2<Object, Integer>(valueType.elements.iterator().next(),
                                valueType.elements.size());
                    }
                });
        ds1.output(new DiscardingOutputFormat<Tuple2<Object, Integer>>());
    } else {
        DataSet<ValueType> ds = text.map(new MapFunction<String, ValueType>() {
            @Override
            public ValueType map(String s) throws Exception {
                ValueType vt = new ValueType();
                vt.elements = new ArrayList<Object>();
                String[] splits = s.split(" ");
                for (String split : splits) {
                    if (split == null || split.length() == 0)
                        continue;
                    if (StringUtils.isNumeric(split)) {
                        try {
                            vt.elements.add(Integer.valueOf(split));
                        } catch (Throwable t) {
                            vt.elements.add(Integer.valueOf(0));
                        }

                    } else {
                        vt.elements.add(split);
                    }
                }
                return vt;
            }
        });
        DataSet<Tuple2<Object, Integer>> ds1 = ds.rebalance()
                .map(new MapFunction<ValueType, Tuple2<Object, Integer>>() {
                    @Override
                    public Tuple2<Object, Integer> map(ValueType valueType) throws Exception {
                        return new Tuple2<Object, Integer>(valueType.elements.iterator().next(),
                                valueType.elements.size());
                    }
                });
        ds1.output(new DiscardingOutputFormat<Tuple2<Object, Integer>>());
    }

    // execute program
    env.execute("KryoTest kryoMode=" + kryoMode);
}

From source file:SubStringDemo.java

public static void main(String[] av) {
    String a = "Java is great.";
    System.out.println(a);/*from  w  w w  .j a va2 s  .c  o  m*/
    String b = a.substring(5); // b is the String "is great."
    System.out.println(b);
    String c = a.substring(5, 7);// c is the String "is"
    System.out.println(c);
    String d = a.substring(5, a.length());// d is "is great."
    System.out.println(d);
}

From source file:TextVerifyInputFormatDate.java

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout());
    final Text text = new Text(shell, SWT.BORDER);
    text.setText("YYYY/MM/DD");
    ;//from   w w w .  ja  v  a2  s .c o m
    final Calendar calendar = Calendar.getInstance();
    text.addListener(SWT.Verify, new Listener() {
        boolean ignore;

        public void handleEvent(Event e) {
            if (ignore)
                return;
            e.doit = false;
            StringBuffer buffer = new StringBuffer(e.text);
            char[] chars = new char[buffer.length()];
            buffer.getChars(0, chars.length, chars, 0);
            if (e.character == '\b') {
                for (int i = e.start; i < e.end; i++) {
                    switch (i) {
                    case 0: /* [Y]YYY */
                    case 1: /* Y[Y]YY */
                    case 2: /* YY[Y]Y */
                    case 3: /* YYY[Y] */ {
                        buffer.append('Y');
                        break;
                    }
                    case 5: /* [M]M */
                    case 6: /* M[M] */ {
                        buffer.append('M');
                        break;
                    }
                    case 8: /* [D]D */
                    case 9: /* D[D] */ {
                        buffer.append('D');
                        break;
                    }
                    case 4: /* YYYY[/]MM */
                    case 7: /* MM[/]DD */ {
                        buffer.append('/');
                        break;
                    }
                    default:
                        return;
                    }
                }
                text.setSelection(e.start, e.start + buffer.length());
                ignore = true;
                text.insert(buffer.toString());
                ignore = false;
                text.setSelection(e.start, e.start);
                return;
            }

            int start = e.start;
            if (start > 9)
                return;
            int index = 0;
            for (int i = 0; i < chars.length; i++) {
                if (start + index == 4 || start + index == 7) {
                    if (chars[i] == '/') {
                        index++;
                        continue;
                    }
                    buffer.insert(index++, '/');
                }
                if (chars[i] < '0' || '9' < chars[i])
                    return;
                if (start + index == 5 && '1' < chars[i])
                    return; /* [M]M */
                if (start + index == 8 && '3' < chars[i])
                    return; /* [D]D */
                index++;
            }
            String newText = buffer.toString();
            int length = newText.length();
            StringBuffer date = new StringBuffer(text.getText());
            date.replace(e.start, e.start + length, newText);
            calendar.set(Calendar.YEAR, 1901);
            calendar.set(Calendar.MONTH, Calendar.JANUARY);
            calendar.set(Calendar.DATE, 1);
            String yyyy = date.substring(0, 4);
            if (yyyy.indexOf('Y') == -1) {
                int year = Integer.parseInt(yyyy);
                calendar.set(Calendar.YEAR, year);
            }
            String mm = date.substring(5, 7);
            if (mm.indexOf('M') == -1) {
                int month = Integer.parseInt(mm) - 1;
                int maxMonth = calendar.getActualMaximum(Calendar.MONTH);
                if (0 > month || month > maxMonth)
                    return;
                calendar.set(Calendar.MONTH, month);
            }
            String dd = date.substring(8, 10);
            if (dd.indexOf('D') == -1) {
                int day = Integer.parseInt(dd);
                int maxDay = calendar.getActualMaximum(Calendar.DATE);
                if (1 > day || day > maxDay)
                    return;
                calendar.set(Calendar.DATE, day);
            } else {
                if (calendar.get(Calendar.MONTH) == Calendar.FEBRUARY) {
                    char firstChar = date.charAt(8);
                    if (firstChar != 'D' && '2' < firstChar)
                        return;
                }
            }
            text.setSelection(e.start, e.start + length);
            ignore = true;
            text.insert(newText);
            ignore = false;
        }
    });
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

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

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 179");
    shell.setLayout(new GridLayout());
    final Text text = new Text(shell, SWT.BORDER);
    text.setText("YYYY/MM/DD");
    final Calendar calendar = Calendar.getInstance();
    text.addListener(SWT.Verify, new Listener() {
        boolean ignore;

        @Override/*  w  w  w. j  av a  2 s  . com*/
        public void handleEvent(Event e) {
            if (ignore)
                return;
            e.doit = false;
            StringBuilder buffer = new StringBuilder(e.text);
            char[] chars = new char[buffer.length()];
            buffer.getChars(0, chars.length, chars, 0);
            if (e.character == '\b') {
                for (int i = e.start; i < e.end; i++) {
                    switch (i) {
                    case 0: /* [Y]YYY */
                    case 1: /* Y[Y]YY */
                    case 2: /* YY[Y]Y */
                    case 3: /* YYY[Y] */ {
                        buffer.append('Y');
                        break;
                    }
                    case 5: /* [M]M*/
                    case 6: /* M[M] */ {
                        buffer.append('M');
                        break;
                    }
                    case 8: /* [D]D */
                    case 9: /* D[D] */ {
                        buffer.append('D');
                        break;
                    }
                    case 4: /* YYYY[/]MM */
                    case 7: /* MM[/]DD */ {
                        buffer.append('/');
                        break;
                    }
                    default:
                        return;
                    }
                }
                text.setSelection(e.start, e.start + buffer.length());
                ignore = true;
                text.insert(buffer.toString());
                ignore = false;
                text.setSelection(e.start, e.start);
                return;
            }

            int start = e.start;
            if (start > 9)
                return;
            int index = 0;
            for (int i = 0; i < chars.length; i++) {
                if (start + index == 4 || start + index == 7) {
                    if (chars[i] == '/') {
                        index++;
                        continue;
                    }
                    buffer.insert(index++, '/');
                }
                if (chars[i] < '0' || '9' < chars[i])
                    return;
                if (start + index == 5 && '1' < chars[i])
                    return; /* [M]M */
                if (start + index == 8 && '3' < chars[i])
                    return; /* [D]D */
                index++;
            }
            String newText = buffer.toString();
            int length = newText.length();
            StringBuilder date = new StringBuilder(text.getText());
            date.replace(e.start, e.start + length, newText);
            calendar.set(Calendar.YEAR, 1901);
            calendar.set(Calendar.MONTH, Calendar.JANUARY);
            calendar.set(Calendar.DATE, 1);
            String yyyy = date.substring(0, 4);
            if (yyyy.indexOf('Y') == -1) {
                int year = Integer.parseInt(yyyy);
                calendar.set(Calendar.YEAR, year);
            }
            String mm = date.substring(5, 7);
            if (mm.indexOf('M') == -1) {
                int month = Integer.parseInt(mm) - 1;
                int maxMonth = calendar.getActualMaximum(Calendar.MONTH);
                if (0 > month || month > maxMonth)
                    return;
                calendar.set(Calendar.MONTH, month);
            }
            String dd = date.substring(8, 10);
            if (dd.indexOf('D') == -1) {
                int day = Integer.parseInt(dd);
                int maxDay = calendar.getActualMaximum(Calendar.DATE);
                if (1 > day || day > maxDay)
                    return;
                calendar.set(Calendar.DATE, day);
            } else {
                if (calendar.get(Calendar.MONTH) == Calendar.FEBRUARY) {
                    char firstChar = date.charAt(8);
                    if (firstChar != 'D' && '2' < firstChar)
                        return;
                }
            }
            text.setSelection(e.start, e.start + length);
            ignore = true;
            text.insert(newText);
            ignore = false;
        }
    });
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:is.idega.idegaweb.egov.gumbo.webservice.client.business.FJSWSClient.java

public static void main(String args[]) {
    String shipNr = "1002";

    if (shipNr != null && !"".equals(shipNr)) {
        if (shipNr.length() < 4) {
            shipNr = "0000".substring(0, 4 - shipNr.length()) + shipNr;
        }/*from  www.ja  v  a  2  s.  co  m*/
    }

    System.out.println("shipNr = " + shipNr);
}

From source file:examples.mail.IMAPImportMbox.java

public static void main(String[] args) throws IOException {
    if (args.length < 2) {
        System.err.println(// w  w  w .  j av a 2s  .  c o m
                "Usage: IMAPImportMbox imap[s]://user:password@host[:port]/folder/path <mboxfile> [selectors]");
        System.err.println("\tWhere: a selector is a list of numbers/number ranges - 1,2,3-10"
                + " - or a list of strings to match in the initial From line");
        System.exit(1);
    }

    final URI uri = URI.create(args[0]);
    final String file = args[1];

    final File mbox = new File(file);
    if (!mbox.isFile() || !mbox.canRead()) {
        throw new IOException("Cannot read mailbox file: " + mbox);
    }

    String path = uri.getPath();
    if (path == null || path.length() < 1) {
        throw new IllegalArgumentException("Invalid folderPath: '" + path + "'");
    }
    String folder = path.substring(1); // skip the leading /

    List<String> contains = new ArrayList<String>(); // list of strings to find
    BitSet msgNums = new BitSet(); // list of message numbers

    for (int i = 2; i < args.length; i++) {
        String arg = args[i];
        if (arg.matches("\\d+(-\\d+)?(,\\d+(-\\d+)?)*")) { // number,m-n
            for (String entry : arg.split(",")) {
                String[] parts = entry.split("-");
                if (parts.length == 2) { // m-n
                    int low = Integer.parseInt(parts[0]);
                    int high = Integer.parseInt(parts[1]);
                    for (int j = low; j <= high; j++) {
                        msgNums.set(j);
                    }
                } else {
                    msgNums.set(Integer.parseInt(entry));
                }
            }
        } else {
            contains.add(arg); // not a number/number range
        }
    }
    //        System.out.println(msgNums.toString());
    //        System.out.println(java.util.Arrays.toString(contains.toArray()));

    // Connect and login
    final IMAPClient imap = IMAPUtils.imapLogin(uri, 10000, null);

    int total = 0;
    int loaded = 0;
    try {
        imap.setSoTimeout(6000);

        final BufferedReader br = new BufferedReader(new FileReader(file)); // TODO charset?

        String line;
        StringBuilder sb = new StringBuilder();
        boolean wanted = false; // Skip any leading rubbish
        while ((line = br.readLine()) != null) {
            if (line.startsWith("From ")) { // start of message; i.e. end of previous (if any)
                if (process(sb, imap, folder, total)) { // process previous message (if any)
                    loaded++;
                }
                sb.setLength(0);
                total++;
                wanted = wanted(total, line, msgNums, contains);
            } else if (startsWith(line, PATFROM)) { // Unescape ">+From " in body text
                line = line.substring(1);
            }
            // TODO process first Received: line to determine arrival date?
            if (wanted) {
                sb.append(line);
                sb.append(CRLF);
            }
        }
        br.close();
        if (wanted && process(sb, imap, folder, total)) { // last message (if any)
            loaded++;
        }
    } catch (IOException e) {
        System.out.println(imap.getReplyString());
        e.printStackTrace();
        System.exit(10);
        return;
    } finally {
        imap.logout();
        imap.disconnect();
    }
    System.out.println("Processed " + total + " messages, loaded " + loaded);
}

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

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 356");
    FillLayout layout = new FillLayout();
    layout.marginHeight = layout.marginWidth = 10;
    shell.setLayout(layout);/*from   www.ja v a  2s  .  co m*/

    String string = "This is sample text with a link and some other link here.";
    final StyledText styledText = new StyledText(shell, SWT.MULTI | SWT.BORDER);
    styledText.setText(string);

    String link1 = "link";
    String link2 = "here";
    StyleRange style = new StyleRange();
    style.underline = true;
    style.underlineStyle = SWT.UNDERLINE_LINK;

    int[] ranges = { string.indexOf(link1), link1.length(), string.indexOf(link2), link2.length() };
    StyleRange[] styles = { style, style };
    styledText.setStyleRanges(ranges, styles);

    styledText.addListener(SWT.MouseDown, event -> {
        // It is up to the application to determine when and how a link should be activated.
        // In this snippet links are activated on mouse down when the control key is held down
        if ((event.stateMask & SWT.MOD1) != 0) {
            int offset = styledText.getOffsetAtPoint(new Point(event.x, event.y));
            if (offset != -1) {
                StyleRange style1 = null;
                try {
                    style1 = styledText.getStyleRangeAtOffset(offset);
                } catch (IllegalArgumentException e) {
                    // no character under event.x, event.y
                }
                if (style1 != null && style1.underline && style1.underlineStyle == SWT.UNDERLINE_LINK) {
                    System.out.println("Click on a Link");
                }
            }
        }
    });
    shell.setSize(600, 400);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:bixo.tools.LengthenUrlsTool.java

/**
 * @param args - URL to fetch, or path to file of URLs
 *//* ww w.j a v a 2  s. c om*/
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
    try {
        String url = null;
        if (args.length == 0) {
            System.out.print("URL to lengthen: ");
            url = readInputLine();
            if (url.length() == 0) {
                System.exit(0);
            }

            if (!url.startsWith("http://")) {
                url = "http://" + url;
            }
        } else if (args.length != 1) {
            System.out.print("A single URL or filename parameter is allowed");
            System.exit(0);
        } else {
            url = args[0];
        }

        String filename;
        if (!url.startsWith("http://")) {
            // It's a path to a file of URLs
            filename = url;
        } else {
            // We have a URL that we need to write to a temp file.
            File tempFile = File.createTempFile("LengthenUrlsTool", "txt");
            filename = tempFile.getAbsolutePath();
            FileWriter fw = new FileWriter(tempFile);
            IOUtils.write(url, fw);
            fw.close();
        }

        System.setProperty("bixo.root.level", "TRACE");
        // Uncomment this to see the wire log for HttpClient
        // System.setProperty("bixo.http.level", "DEBUG");

        BaseFetcher fetcher = UrlLengthener.makeFetcher(10, ConfigUtils.BIXO_TOOL_AGENT);

        Pipe pipe = new Pipe("urls");
        pipe = new Each(pipe, new UrlLengthener(fetcher));
        pipe = new Each(pipe, new Debug());

        BixoPlatform platform = new BixoPlatform(LengthenUrlsTool.class, Platform.Local);
        BasePath filePath = platform.makePath(filename);
        TextLine textLineLocalScheme = new TextLine(new Fields("url"));
        Tap sourceTap = platform.makeTap(textLineLocalScheme, filePath, SinkMode.KEEP);
        SinkTap sinkTap = new NullSinkTap(new Fields("url"));

        FlowConnector flowConnector = platform.makeFlowConnector();
        Flow flow = flowConnector.connect(sourceTap, sinkTap, pipe);

        flow.complete();
    } catch (Exception e) {
        System.err.println("Exception running tool: " + e.getMessage());
        e.printStackTrace(System.err);
        System.exit(-1);
    }
}

From source file:SparkKMer.java

public static void main(String[] args) throws Exception {
    //Setup//w w  w  .  j  a va  2  s  .  c  o  m
    SparkConf sparkConf = new SparkConf().setAppName("SparkKMer");
    JavaSparkContext jsc = new JavaSparkContext(sparkConf);
    //Agrument parsing
    if (args.length < 2) {
        System.err.println("Usage: SparkKMer <accession> <kmer-length>");
        System.exit(1);
    }
    final String acc = args[0];
    final int KMER_LENGTH = Integer.parseInt(args[1]);

    //Check accession and split
    ReadCollection run = gov.nih.nlm.ncbi.ngs.NGS.openReadCollection(acc);
    long numreads = run.getReadCount();

    //Slice the job
    int chunk = 20000; /** amount of reads per 1 map operation **/
    int slices = (int) (numreads / chunk / 1);
    if (slices == 0)
        slices = 1;
    List<LongRange> sub = new ArrayList<LongRange>();
    for (long first = 1; first <= numreads;) {
        long last = first + chunk - 1;
        if (last > numreads)
            last = numreads;
        sub.add(new LongRange(first, last));
        first = last + 1;
    }
    System.err.println("Prepared ranges: \n" + sub);

    JavaRDD<LongRange> jobs = jsc.parallelize(sub, slices);
    //Map
    //
    JavaRDD<String> kmers = jobs.flatMap(new FlatMapFunction<LongRange, String>() {
        ReadCollection run = null;

        @Override
        public Iterable<String> call(LongRange s) {
            //Executes on task nodes
            List<String> ret = new ArrayList<String>();
            try {
                long first = s.getMinimumLong();
                long last = s.getMaximumLong();
                if (run == null) {
                    run = gov.nih.nlm.ncbi.ngs.NGS.openReadCollection(acc);
                }
                ReadIterator it = run.getReadRange(first, last - first + 1, Read.all);
                while (it.nextRead()) {
                    //iterate through fragments
                    while (it.nextFragment()) {
                        String bases = it.getFragmentBases();
                        //iterate through kmers
                        for (int i = 0; i < bases.length() - KMER_LENGTH; i++) {
                            ret.add(bases.substring(i, i + KMER_LENGTH));
                        }
                    }
                }
            } catch (ErrorMsg x) {
                System.err.println(x.toString());
                x.printStackTrace();
            }
            return ret;
        }
    });
    //Initiate kmer counting;
    JavaPairRDD<String, Integer> kmer_ones = kmers.mapToPair(new PairFunction<String, String, Integer>() {
        @Override
        public Tuple2<String, Integer> call(String s) {
            return new Tuple2<String, Integer>(s, 1);
        }
    });
    //Reduce counts
    JavaPairRDD<String, Integer> counts = kmer_ones.reduceByKey(new Function2<Integer, Integer, Integer>() {
        @Override
        public Integer call(Integer i1, Integer i2) {
            return i1 + i2;
        }
    });
    //Collect the output
    List<Tuple2<String, Integer>> output = counts.collect();
    for (Tuple2<String, Integer> tuple : output) {
        System.out.println(tuple._1() + ": " + tuple._2());
    }
    jsc.stop();
}