Example usage for java.lang CharSequence charAt

List of usage examples for java.lang CharSequence charAt

Introduction

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

Prototype

char charAt(int index);

Source Link

Document

Returns the char value at the specified index.

Usage

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

/**
 * This code was copied from Apache Wicket.
 * Converts a Java String to an HTML markup String by replacing illegal characters with HTML
 * entities where appropriate. Spaces are converted to non-breaking spaces (<nbsp>) if
 * escapeSpaces is true, tabs are converted to four non-breaking spaces, less than signs are
 * converted to < entities and greater than signs to > entities.
 *
 * @param s the string to escape/* w  ww .  j av  a 2  s .co  m*/
 * @param escapeSpaces true to replace ' ' with nonbreaking space
 * @param convertToHtmlUnicodeEscapes true to convert non-7 bit characters to unicode HTML (&#...)
 * @return the escaped string
 */
public static CharSequence escapeMarkup(CharSequence s, boolean escapeSpaces,
        boolean convertToHtmlUnicodeEscapes) {
    if (s == null) {
        return null;
    } else {
        int len = s.length();
        final StringBuilder sb = new StringBuilder((int) (len * 1.1));

        for (int i = 0; i < len; i++) {
            final char c = s.charAt(i);

            switch (c) {
            case '\t':
                if (escapeSpaces) {
                    // Assumption is four space tabs (sorry, but that's
                    // just how it is!)
                    sb.append("&nbsp;&nbsp;&nbsp;&nbsp;");
                } else {
                    sb.append(c);
                }
                break;

            case ' ':
                if (escapeSpaces) {
                    sb.append("&nbsp;");
                } else {
                    sb.append(c);
                }
                break;

            case '<':
                sb.append("&lt;");
                break;

            case '>':
                sb.append("&gt;");
                break;

            case '&':

                sb.append(AMP_XML);
                break;

            case '"':
                sb.append("&quot;");
                break;

            case '\'':
                sb.append("&#039;");
                break;

            default:

                int ci = 0xffff & c;
                if (ci < 0x20) {
                    // http://en.wikipedia.org/wiki/Valid_characters_in_XML
                    if ((ci != 0x09) && (ci != 0x0A) && (ci != 0x0D)) {
                        sb.append("&#");
                        sb.append(Integer.toString(ci));
                        sb.append(';');
                        break;
                    }
                }

                if (convertToHtmlUnicodeEscapes) {
                    if (ci < 160) {
                        // nothing special only 7 Bit
                        sb.append(c);
                    } else {
                        // Not 7 Bit use the unicode system
                        sb.append("&#");
                        sb.append(Integer.toString(ci));
                        sb.append(';');
                    }
                } else {
                    sb.append(c);
                }

                break;
            }
        }

        return sb;
    }
}

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

/**
 * @param input the {@link CharSequence} to be trimmed
 * @return the trimmed char sequence//from www .j  a v a2s .  c  o m
 * @since 3.8.2
 */
@Nullable
public static CharSequence trim(@Nullable CharSequence input) {
    if (input == null) {
        return null;
    }

    if (input.length() == 0) {
        return input;
    }

    if (input instanceof String) {
        return ((String) input).trim();
    }

    int count = input.length();
    int len = count;
    int st = 0;
    int off = 0;

    while ((st < len) && (input.charAt(off + st) <= ' ')) {
        st++;
    }
    while ((st < len) && (input.charAt((off + len) - 1) <= ' ')) {
        len--;
    }

    if ((st == 0) && (input instanceof StringBuilder)) {
        ((StringBuilder) input).setLength(len);
        return input;
    }

    return ((st > 0) || (len < count)) ? input.subSequence(st, len) : input;
}

From source file:com.perl5.lang.perl.lexer.RegexBlock.java

/**
 * Parses guaranteed opened regex block//  w ww  . j  a v  a2s  .c  o  m
 *
 * @param buffer      Input characters stream
 * @param startOffset Start parsing offset
 * @param bufferEnd   Buffer last offset
 * @param openingChar Opener character
 * @return Parsed regex block or null if failed
 */
public static RegexBlock parseBlock(CharSequence buffer, int startOffset, int bufferEnd, char openingChar,
        boolean isSecondBlock) {
    char closingChar = getQuoteCloseChar(openingChar);

    boolean isEscaped = false;
    boolean isCharGroup = false;
    boolean isQuotesDiffers = closingChar != openingChar;

    int braceLevel = 0;
    int parenLevel = 0;
    int delimiterLevel = 0;

    RegexBlock newBlock = null;
    int currentOffset = startOffset;

    while (true) {
        if (currentOffset >= bufferEnd) {
            break;
        }

        char currentChar = buffer.charAt(currentOffset);

        if (delimiterLevel == 0 && braceLevel == 0 && !isCharGroup && !isEscaped && parenLevel == 0
                && closingChar == currentChar) {
            newBlock = new RegexBlock(buffer, startOffset, currentOffset + 1, openingChar, closingChar);
            break;
        }

        if (!isSecondBlock) {
            if (!isEscaped && !isCharGroup && currentChar == '[') {
                Matcher m = POSIX_CHAR_CLASS_PATTERN.matcher(buffer.subSequence(currentOffset, bufferEnd));
                if (m.lookingAt()) {
                    currentOffset += m.toMatchResult().group(0).length();
                    continue;
                } else {
                    isCharGroup = true;
                }
            } else if (!isEscaped && isCharGroup && currentChar == ']') {
                isCharGroup = false;
            }

            // @todo this is buggy, sometimes bare is allowed. See example from `redo` doc
            //            if (!isEscaped && !isCharGroup && currentChar == '{')
            //               braceLevel++;
            //            else if (!isEscaped && !isCharGroup && braceLevel > 0 && currentChar == '}')
            //               braceLevel--;
            //
            //            if (!isEscaped && !isCharGroup && currentChar == '(')
            //               parenLevel++;
            //            else if (!isEscaped && !isCharGroup && parenLevel > 0 && currentChar == ')')
            //               parenLevel--;
        }

        if (!isEscaped && isQuotesDiffers && !isCharGroup) {
            if (currentChar == openingChar) {
                delimiterLevel++;
            } else if (currentChar == closingChar && delimiterLevel > 0) {
                delimiterLevel--;
            }
        }

        isEscaped = !isEscaped && closingChar != '\\' && currentChar == '\\';

        currentOffset++;
    }
    return newBlock;
}

From source file:org.renjin.parser.NumericLiterals.java

private static int findImaginaryStart(CharSequence s) {
    // cannot be the last character
    int index = s.length() - 2;
    while (index >= 0) {
        char c = s.charAt(index);
        if (c == '+' || c == '-') {
            return index;
        }//w  w  w.jav  a2s.  com
        index--;
    }
    return -1;
}

From source file:com.fuseim.webapp.ProxyServlet.java

/**
 * Encodes characters in the query or fragment part of the URI.
 *
 * <p>Unfortunately, an incoming URI sometimes has characters disallowed by the spec. HttpClient
 * insists that the outgoing proxied request has a valid URI because it uses Java's {@link URI}.
 * To be more forgiving, we must escape the problematic characters. See the URI class for the
 * spec.//from   w w w  .j av  a2s.  c o  m
 *
 * @param in example: name=value&amp;foo=bar#fragment
 */
protected static CharSequence encodeUriQuery(CharSequence in) {
    //Note that I can't simply use URI.java to encode because it will escape pre-existing escaped things.
    StringBuilder outBuf = null;
    Formatter formatter = null;
    for (int i = 0; i < in.length(); i++) {
        char c = in.charAt(i);
        boolean escape = true;
        if (c < 128) {
            if (asciiQueryChars.get((int) c)) {
                escape = false;
            }
        } else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) { //not-ascii
            escape = false;
        }
        if (!escape) {
            if (outBuf != null)
                outBuf.append(c);
        } else {
            //escape
            if (outBuf == null) {
                outBuf = new StringBuilder(in.length() + 5 * 3);
                outBuf.append(in, 0, i);
                formatter = new Formatter(outBuf);
            }
            //leading %, 0 padded, width 2, capital hex
            formatter.format("%%%02X", (int) c); //TODO
        }
    }
    return outBuf != null ? outBuf : in;
}

From source file:com.oncore.calorders.core.utils.FormatHelper.java

/**
 * The <code>isNameValid</code> method checks if the CharSequence contains
 * only unicode letters, spaces, apostrophes, and reverse apostrophes
 *
 * <pre>/*  www  .ja  va  2s  . c o m*/
 * PageUtilities.isNameValid(null) = false
 * PageUtilities.isNameValid("") = false
 * PageUtilities.isNameValid(" ") = false
 * PageUtilities.isNameValid("abc") = true
 * PageUtilities.isNameValid("ab c") = true
 * PageUtilities.isNameValid("ab2c") = false
 * PageUtilities.isNameValid("ab-c") = false
 * PageUtilities.isNameValid("9999") = false
 * PageUtilities.isNameValid("For instance, this is bla") = false
 * PageUtilities.isNameValid("John Doe") = true
 * PageUtilities.isNameValid("John O'Brien") = true
 * PageUtilities.isNameValid("John O`Brien") = true
 * PageUtilities.isNameValid("John") = true
 * PageUtilities.isNameValid("Smith") = true
 * PageUtilities.isNameValid("John O@Brien") = false
 * </pre>
 *
 * @author OnCore Consulting LLC
 *
 * @param cs the CharSequence to check, may be null
 *
 * @return true if only unicode letters, spaces, apostrophes, and reverse
 * apostrophes, false otherwise
 */
@SuppressWarnings("empty-statement")
public static Boolean isNameValid(final CharSequence cs) {
    if (StringUtils.isBlank(String.valueOf(cs))) {
        return Boolean.FALSE;
    }

    final int size = cs.length();

    for (int i = 0; i < size; i++) {
        if ('\'' == cs.charAt(i) || '`' == cs.charAt(i) || cs.charAt(i) == ' '
                || (Character.isLetter(cs.charAt(i)) == true)) {
            ; // do nothing
        } else {
            return Boolean.FALSE;
        }
    }

    return Boolean.TRUE;
}

From source file:io.hops.hopsworks.api.kibana.ProxyServlet.java

/**
 * Encodes characters in the query or fragment part of the URI.
 * <p>//from w  ww.  j a v  a  2  s  .c  o m
 * <p>
 * Unfortunately, an incoming URI sometimes has characters disallowed by the
 * spec. HttpClient
 * insists that the outgoing proxied request has a valid URI because it uses
 * Java's {@link URI}.
 * To be more forgiving, we must escape the problematic characters. See the
 * URI class for the
 * spec.
 *
 * @param in example: name=value&foo=bar#fragment
 */
protected static CharSequence encodeUriQuery(CharSequence in) {
    //Note that I can't simply use URI.java to encode because it will escape 
    //pre-existing escaped things.
    StringBuilder outBuf = null;
    Formatter formatter = null;
    for (int i = 0; i < in.length(); i++) {
        char c = in.charAt(i);
        boolean escape = true;
        if (c < 128) {
            if (asciiQueryChars.get((int) c)) {
                escape = false;
            }
        } else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {//not-ascii
            escape = false;
        }
        if (!escape) {
            if (outBuf != null) {
                outBuf.append(c);
            }
        } else {
            //escape
            if (outBuf == null) {
                outBuf = new StringBuilder(in.length() + 5 * 3);
                outBuf.append(in, 0, i);
                formatter = new Formatter(outBuf);
            }
            //leading %, 0 padded, width 2, capital hex
            formatter.format("%%%02X", (int) c);//TODO
        }
    }
    return outBuf != null ? outBuf : in;
}

From source file:org.nuclos.common2.StringUtils.java

public static String wildcardToRegex(CharSequence s) {
    StringBuilder sb = new StringBuilder();
    int len = s.length();
    for (int i = 0; i < len; i++) {
        char ch = s.charAt(i);
        switch (ch) {
        case '*':
            sb.append(".*");
            break;
        case '?':
            sb.append(".");
            break;
        case '[':
        case ']':
        case '(':
        case ')':
        case '{':
        case '}':
        case '|':
        case '+':
        case '-':
        case '^':
        case '$':
        case '\\':
        case '.':
            sb.append("\\").append(ch);
            break;
        default://from   w w w  . j  av  a2s . co  m
            sb.append(ch);
            break;
        }
    }
    return sb.toString();
}

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 {/*from   w  w  w  . j av a2  s. c o  m*/
            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:org.jbpm.designer.bpmn2.validation.BPMN2SyntaxChecker.java

private static boolean isEmpty(final CharSequence str) {
    if (str == null || str.length() == 0) {
        return true;
    }/*w ww  .  j  ava2s  .com*/
    for (int i = 0, length = str.length(); i < length; i++) {
        if (str.charAt(i) != ' ') {
            return false;
        }
    }
    return true;
}