Example usage for java.lang CharSequence subSequence

List of usage examples for java.lang CharSequence subSequence

Introduction

In this page you can find the example usage for java.lang CharSequence subSequence.

Prototype

CharSequence subSequence(int start, int end);

Source Link

Document

Returns a CharSequence that is a subsequence of this sequence.

Usage

From source file:org.cleverbus.common.Strings.java

private static void append(StringBuilder buffer, CharSequence s, int from, int to) {
    if (s instanceof StringBuilder) {
        buffer.append(s, from, to);//from w w  w  .j  a  v  a2  s. c  o m
    } else if (s instanceof StringBuffer) {
        buffer.append(s, from, to);
    } else {
        buffer.append(s.subSequence(from, to));
    }
}

From source file:io.github.hidroh.materialistic.AppUtils.java

private static CharSequence trim(CharSequence charSequence) {
    if (TextUtils.isEmpty(charSequence)) {
        return charSequence;
    }/*from   w ww  .  j  ava  2 s  .c om*/
    int end = charSequence.length() - 1;
    while (Character.isWhitespace(charSequence.charAt(end))) {
        end--;
    }
    return charSequence.subSequence(0, end + 1);
}

From source file:com.taobao.android.object.DexDiffInfo.java

private static String getParamsType(List<? extends CharSequence> parameterTypes) {
    StringBuilder params = new StringBuilder();
    for (CharSequence charSequence : parameterTypes) {
        boolean isArray = false;
        String s = null;//from   w ww. j av a2s . c  o m
        if (charSequence.toString().startsWith("[")) {
            s = charSequence.subSequence(1, charSequence.length()).toString();
            isArray = true;
        } else {
            s = charSequence.toString();
        }
        if (!APatchTool.mappingMap.containsValue(s)) {
            params.append(isArray ? "[" + s + "|" : s + "|");
            continue;
        } else {
            for (Map.Entry<String, String> entry : APatchTool.mappingMap.entrySet()) {
                if (entry.getValue().equals(charSequence.toString())) {
                    params.append(isArray ? "[" + entry.getKey() + "|" : entry.getKey() + "|");
                }
            }

        }
    }
    if (params.length() > 1) {
        return "[" + params.substring(0, params.length() - 1).toString() + "]";
    } else {
        return "[" + params.toString() + "]";
    }
}

From source file:com.gmail.walles.johan.batterylogger.BatteryPlotFragment.java

private static CharSequence trimTrailingWhitespace(CharSequence source) {
    int i = source.length();

    // loop back to the first non-whitespace character
    while (--i >= 0 && Character.isWhitespace(source.charAt(i))) {
        // This block intentionally left blank
    }//ww  w . j  a  v a  2s .c o m

    return source.subSequence(0, i + 1);
}

From source file:com.kstenschke.shifter.utils.UtilsTextual.java

/**
 * Get word at caret offset out of given text
 *
 * @param   text           The full text
 * @param   cursorOffset   Character offset of caret
 * @return                 The extracted word or null
 *//*from  w w  w.  j  ava 2 s.c o  m*/
public static String getWordAtOffset(CharSequence text, int cursorOffset) {
    if (text.length() == 0 || cursorOffset >= text.length())
        return null;

    if (cursorOffset > 0 && !Character.isJavaIdentifierPart(text.charAt(cursorOffset))
            && Character.isJavaIdentifierPart(text.charAt(cursorOffset - 1))) {
        cursorOffset--;
    }

    if (Character.isJavaIdentifierPart(text.charAt(cursorOffset))) {
        int start = cursorOffset;
        int end = cursorOffset;

        while (start > 0 && Character.isJavaIdentifierPart(text.charAt(start - 1))) {
            start--;
        }

        while (end < text.length() && Character.isJavaIdentifierPart(text.charAt(end))) {
            end++;
        }

        return text.subSequence(start, end).toString();
    }

    return null;
}

From source file:org.apache.hadoop.hive.cli.CliDriver.java

public static Completer[] getCommandCompleter() {
    // StringsCompleter matches against a pre-defined wordlist
    // We start with an empty wordlist and build it up
    List<String> candidateStrings = new ArrayList<String>();

    // We add Hive function names
    // For functions that aren't infix operators, we add an open
    // parenthesis at the end.
    for (String s : FunctionRegistry.getFunctionNames()) {
        if (s.matches("[a-z_]+")) {
            candidateStrings.add(s + "(");
        } else {/*w ww .  ja  v  a2  s  .c om*/
            candidateStrings.add(s);
        }
    }

    // We add Hive keywords, including lower-cased versions
    for (String s : HiveParser.getKeywords()) {
        candidateStrings.add(s);
        candidateStrings.add(s.toLowerCase());
    }

    StringsCompleter strCompleter = new StringsCompleter(candidateStrings);

    // Because we use parentheses in addition to whitespace
    // as a keyword delimiter, we need to define a new ArgumentDelimiter
    // that recognizes parenthesis as a delimiter.
    ArgumentDelimiter delim = new AbstractArgumentDelimiter() {
        @Override
        public boolean isDelimiterChar(CharSequence buffer, int pos) {
            char c = buffer.charAt(pos);
            return (Character.isWhitespace(c) || c == '(' || c == ')' || c == '[' || c == ']');
        }
    };

    // The ArgumentCompletor allows us to match multiple tokens
    // in the same line.
    final ArgumentCompleter argCompleter = new ArgumentCompleter(delim, strCompleter);
    // By default ArgumentCompletor is in "strict" mode meaning
    // a token is only auto-completed if all prior tokens
    // match. We don't want that since there are valid tokens
    // that are not in our wordlist (eg. table and column names)
    argCompleter.setStrict(false);

    // ArgumentCompletor always adds a space after a matched token.
    // This is undesirable for function names because a space after
    // the opening parenthesis is unnecessary (and uncommon) in Hive.
    // We stack a custom Completor on top of our ArgumentCompletor
    // to reverse this.
    Completer customCompletor = new Completer() {
        @Override
        public int complete(String buffer, int offset, List completions) {
            List<String> comp = completions;
            int ret = argCompleter.complete(buffer, offset, completions);
            // ConsoleReader will do the substitution if and only if there
            // is exactly one valid completion, so we ignore other cases.
            if (completions.size() == 1) {
                if (comp.get(0).endsWith("( ")) {
                    comp.set(0, comp.get(0).trim());
                }
            }
            return ret;
        }
    };

    List<String> vars = new ArrayList<String>();
    for (HiveConf.ConfVars conf : HiveConf.ConfVars.values()) {
        vars.add(conf.varname);
    }

    StringsCompleter confCompleter = new StringsCompleter(vars) {
        @Override
        public int complete(final String buffer, final int cursor, final List<CharSequence> clist) {
            int result = super.complete(buffer, cursor, clist);
            if (clist.isEmpty() && cursor > 1 && buffer.charAt(cursor - 1) == '=') {
                HiveConf.ConfVars var = HiveConf.getConfVars(buffer.substring(0, cursor - 1));
                if (var == null) {
                    return result;
                }
                if (var.getValidator() instanceof Validator.StringSet) {
                    Validator.StringSet validator = (Validator.StringSet) var.getValidator();
                    clist.addAll(validator.getExpected());
                } else if (var.getValidator() != null) {
                    clist.addAll(Arrays.asList(var.getValidator().toDescription(), ""));
                } else {
                    clist.addAll(Arrays.asList("Expects " + var.typeString() + " type value", ""));
                }
                return cursor;
            }
            if (clist.size() > DELIMITED_CANDIDATE_THRESHOLD) {
                Set<CharSequence> delimited = new LinkedHashSet<CharSequence>();
                for (CharSequence candidate : clist) {
                    Iterator<String> it = Splitter.on(".")
                            .split(candidate.subSequence(cursor, candidate.length())).iterator();
                    if (it.hasNext()) {
                        String next = it.next();
                        if (next.isEmpty()) {
                            next = ".";
                        }
                        candidate = buffer != null ? buffer.substring(0, cursor) + next : next;
                    }
                    delimited.add(candidate);
                }
                clist.clear();
                clist.addAll(delimited);
            }
            return result;
        }
    };

    StringsCompleter setCompleter = new StringsCompleter("set") {
        @Override
        public int complete(String buffer, int cursor, List<CharSequence> clist) {
            return buffer != null && buffer.equals("set") ? super.complete(buffer, cursor, clist) : -1;
        }
    };

    ArgumentCompleter propCompleter = new ArgumentCompleter(setCompleter, confCompleter) {
        @Override
        public int complete(String buffer, int offset, List<CharSequence> completions) {
            int ret = super.complete(buffer, offset, completions);
            if (completions.size() == 1) {
                completions.set(0, ((String) completions.get(0)).trim());
            }
            return ret;
        }
    };
    return new Completer[] { propCompleter, customCompletor };
}

From source file:cn.edu.zjnu.acm.judge.security.password.LengthLimitedPasswordEncoder.java

private CharSequence limit(CharSequence orignPassword) {
    return orignPassword == null || orignPassword.length() <= length ? orignPassword
            : orignPassword.subSequence(0, length);
}

From source file:org.sipfoundry.sipxconfig.bulk.csv.CsvParserImpl.java

private void addField(List row, CharSequence line, int startIndex, int endIndex) {
    String field = line.subSequence(startIndex, endIndex).toString();
    row.add(field);/*from  w  w w.j a va  2  s  .co  m*/
}

From source file:org.apache.bval.jsr.util.PathNavigation.java

/**
 * Handles an index/key. If the text contained between [] is surrounded by a pair of " or ', it will be treated as a
 * string which may contain Java escape sequences.
 * //www  .  ja  v a 2  s  .  com
 * @param path
 * @param pos
 * @throws Exception
 */
private static void handleIndex(CharSequence path, PathPosition pos) throws Exception {
    int len = path.length();
    int start = pos.getIndex();
    if (start < len) {
        char first = path.charAt(pos.getIndex());
        if (first == '"' || first == '\'') {
            String s = parseQuotedString(path, pos);
            if (s != null && path.charAt(pos.getIndex()) == ']') {
                pos.handleIndexOrKey(s);
                pos.next();
                return;
            }
        }
        // no quoted string; match ] greedily
        while (pos.getIndex() < len) {
            int here = pos.getIndex();
            try {
                if (path.charAt(here) == ']') {
                    if (here == start) {
                        pos.handleGenericInIterable();
                    } else {
                        pos.handleIndexOrKey(path.subSequence(start, here).toString());
                    }
                    return;
                }
            } finally {
                pos.next();
            }
        }
    }
    throw new IllegalStateException(String.format("Position %s: unparsable index", start));
}

From source file:com.cloudera.oryx.kmeans.serving.web.AssignServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    CharSequence pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No path");
        return;//from  ww  w.  jav a  2  s .  co  m
    }
    String line = pathInfo.subSequence(1, pathInfo.length()).toString();
    Generation generation = getGenerationManager().getCurrentGeneration();
    if (generation == null) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "API method unavailable until model has been built and loaded");
        return;
    }

    RealVector vec = generation.toVector(DelimitedDataUtils.decode(line));
    if (vec == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Wrong column count");
        return;
    }

    int assignment = DistanceToNearestServlet.findClosest(generation, vec).getClosestCenterId();
    response.getWriter().write(Integer.toString(assignment));
}