Example usage for java.lang Character isDigit

List of usage examples for java.lang Character isDigit

Introduction

In this page you can find the example usage for java.lang Character isDigit.

Prototype

public static boolean isDigit(int codePoint) 

Source Link

Document

Determines if the specified character (Unicode code point) is a digit.

Usage

From source file:com.florian.chess.pgn.SimplePgnParser.java

/**
 * Returns null if wordToken isn't a nag. If word token is only a nag then a
 * String[1] is returned where index 0 = wordToken. If word token starts
 * with a nag then a String[2] is returned where 0=nag and 1 = rest of word.
 * This method is fast and does'nt use REGEX for parsing.
 *//* ww  w  .ja v  a  2s  . c  o m*/
private String[] splitOutNag(String wordToken) {

    if (wordToken.startsWith("$")) {
        int digitEndIndex = 1;
        for (int i = 1; i < wordToken.length(); i++) {
            if (!Character.isDigit(wordToken.charAt(i))) {
                break;
            } else {
                digitEndIndex++;
            }
        }

        if (digitEndIndex <= 1) {
            return null;
        } else if (wordToken.length() == digitEndIndex) {
            return new String[] { wordToken };
        } else {
            return new String[] { wordToken.substring(0, digitEndIndex),
                    wordToken.substring(digitEndIndex, wordToken.length()) };
        }
    }
    return null;
}

From source file:be.dataminded.nifi.plugins.util.JdbcCommon.java

private static String normalizeNameForAvro(String inputName) {
    String normalizedName = inputName.replaceAll("[^A-Za-z0-9_]", "_");
    if (Character.isDigit(normalizedName.charAt(0))) {
        normalizedName = "_" + normalizedName;
    }/*from ww  w  .  j a v  a  2  s .  c  o m*/
    return normalizedName;
}

From source file:ua.com.manometer.jasperreports.AbstractJasperReportsView.java

/**
 * Convert the supplied parameter value into the actual type required by the
 * corresponding {@link JRExporterParameter}.
 * <p>The default implementation simply converts the String values "true" and
 * "false" into corresponding <code>Boolean</code> objects, and tries to convert
 * String values that start with a digit into <code>Integer</code> objects
 * (simply keeping them as String if number conversion fails).
 * @param parameter the parameter key//from   ww w .  j a  v  a  2s .  c  o  m
 * @param value the parameter value
 * @return the converted parameter value
 */
protected Object convertParameterValue(JRExporterParameter parameter, Object value) {
    if (value instanceof String) {
        String str = (String) value;
        if ("true".equals(str)) {
            return Boolean.TRUE;
        } else if ("false".equals(str)) {
            return Boolean.FALSE;
        } else if (str.length() > 0 && Character.isDigit(str.charAt(0))) {
            // Looks like a number... let's try.
            try {
                return new Integer(str);
            } catch (NumberFormatException ex) {
                // OK, then let's keep it as a String value.
                return str;
            }
        }
    }
    return value;
}

From source file:Util.java

/**
 * Replace all the occurences of HTML escape strings with the
 * respective characters./*from w  ww.  j a  v a2  s. c o m*/
 *
 * @param s a <code>String</code> value
 * @return a <code>String</code> value
 */
public static final String unescapeHTML(String s) {
    char[] chars = s.toCharArray();
    char[] escaped = new char[chars.length];

    // Note: escaped[pos] = end of the escaped char array.
    int pos = 0;

    for (int i = 0; i < chars.length;) {
        if (chars[i] != '&') {
            escaped[pos++] = chars[i++];
            continue;
        }

        // Allow e.g. &#123;
        int j = i + 1;
        if (j < chars.length && chars[j] == '#')
            j++;

        // Scan until we find a char that is not letter or digit.
        for (; j < chars.length; j++) {
            if (!Character.isLetterOrDigit(chars[j]))
                break;
        }

        boolean replaced = false;
        if (j < chars.length && chars[j] == ';') {
            if (s.charAt(i + 1) == '#') { // Check for &#D; and &#xD; pattern
                try {
                    long charcode = 0;
                    char ch = s.charAt(i + 2);
                    if (ch == 'x' || ch == 'X') {
                        charcode = Long.parseLong(new String(chars, i + 3, j - i - 3), 16);
                    } else if (Character.isDigit(ch)) {
                        charcode = Long.parseLong(new String(chars, i + 2, j - i - 2));
                    }
                    if (charcode > 0 && charcode < 65536) {
                        escaped[pos++] = (char) charcode;
                        replaced = true;
                    }
                } catch (NumberFormatException ex) {
                    // Failed, not replaced.
                }

            } else {
                String key = new String(chars, i, j - i + 1);
                Character repl = escapeStrings.get(key);
                if (repl != null) {
                    escaped[pos++] = repl.charValue();
                    replaced = true;
                }
            }
            j++; // Skip over ';'
        }

        if (!replaced) {
            // Not a recognized escape sequence, leave as-is
            System.arraycopy(chars, i, escaped, pos, j - i);
            pos += j - i;
        }
        i = j;
    }
    return new String(escaped, 0, pos);
}

From source file:de.unwesen.packrat.api.FeedReader.java

private void handleWebSearchResults(String data, final Handler handler) {
    //    Log.d(LTAG, "Result: " + data);

    try {//from   www.  j  a  v a  2 s. c o m
        // First check response status. If that is != 200, we may have an error
        // message to log, and definitely can bail out early.
        JSONObject result = new JSONObject(data);
        int status = result.getInt("responseStatus");
        if (200 != status) {
            Log.e(LTAG, "Server error: " + result.getString("responseDetails"));
            handler.obtainMessage(ERR_SERVER).sendToTarget();
            return;
        }

        JSONObject d = result.getJSONObject("responseData");
        JSONArray res = d.getJSONArray("results");

        // Count the occurrences of various words across all returned titles.
        // If a word is known to designate media type, we'll ignore it. We'll
        // also ignore words shorter than MIN_WORD_LENGTH.
        HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
        for (int i = 0; i < res.length(); ++i) {
            JSONObject entry = res.getJSONObject(i);

            String title = entry.getString("titleNoFormatting");

            String[] words = title.split(" ");
            for (String word : words) {
                if (MIN_WORD_LENGTH > word.length()) {
                    // Too short
                    continue;
                }

                Integer type = sMediaTypes.get(word);
                if (null != type) {
                    // This word is a media type keyword, so we'll ignore it.
                    continue;
                }

                word = word.toLowerCase();
                Integer count = wordCount.get(word);
                if (null == count) {
                    wordCount.put(word, 1);
                } else {
                    wordCount.put(word, count + 1);
                }
            }
        }

        // Now that we've counted words, first filter out all words that contain
        // non-letters. Those are likely not good candidates for further searching.
        // We ignore them by putting their count to zero.
        // The tricky part here is that trailing non-letters are likely fine, we
        // just can't use them for searches.
        HashMap<String, Integer> filteredWordCount = new HashMap<String, Integer>();
        for (String word : wordCount.keySet()) {
            // Log.d(LTAG, "Word: " + word + " -> " + wordCount.get(word));

            int lastLetter = -1;
            int lastNonLetter = -1;
            for (int i = 0; i < word.length(); ++i) {
                int codePoint = word.codePointAt(i);
                if (Character.isLetter(codePoint) || Character.isDigit(codePoint)) {
                    lastLetter = i;
                    if (lastNonLetter > 0) {
                        // Due to the sequential nature of our iteration, we know that
                        // at(i) is now a letter following a non-letter, so we can
                        // safely ignore this word.
                        break;
                    }
                } else {
                    lastNonLetter = i;
                    if (-1 == lastLetter) {
                        // We have non-letters preceeding letters, that word should
                        // likely be discarded.
                        break;
                    }
                }
            }

            if (-1 == lastNonLetter) {
                // Word is pure letters, keep it.
                filteredWordCount.put(word, wordCount.get(word));
            } else if (-1 == lastLetter) {
                // Word is pure non-letters, discard it.
            } else if (lastNonLetter > lastLetter) {
                // Word has trailing non-letters, cut it.
                Integer count = wordCount.get(word);
                word = word.substring(0, lastLetter + 1);
                filteredWordCount.put(word, count);
            } else {
                // Word has non-letters in the middle.
            }
        }

        // Next filter step is optional: if we had more than one title to go
        // through, then chances are that words with only one count should be
        // ignored. If we had only one title, that's not an optimization we can
        // safely make.
        if (1 < res.length()) {
            wordCount = filteredWordCount;
            filteredWordCount = new HashMap<String, Integer>();
            for (String word : wordCount.keySet()) {
                int count = wordCount.get(word);
                if (count > 1) {
                    filteredWordCount.put(word, count);
                }
            }
        }

        // If we're left with no results, give up right here.
        if (0 == filteredWordCount.size()) {
            handler.obtainMessage(ERR_EMPTY_RESPONSE).sendToTarget();
            return;
        }

        // If we've got results, sort them.
        List<HashMap.Entry> wordList = new LinkedList<HashMap.Entry>(filteredWordCount.entrySet());
        Collections.sort(wordList, new Comparator() {
            public int compare(Object o1, Object o2) {
                return -1 * ((Comparable) ((HashMap.Entry) (o1)).getValue())
                        .compareTo(((HashMap.Entry) (o2)).getValue());
            }
        });

        // With the resulting wordList, we'll generate search terms, preferring
        // more words over fewer words, and words with a higher count over words
        // with a lower count.
        WebSearchMachine machine = new WebSearchMachine(wordList, handler);
        machine.nextTerm();

    } catch (JSONException ex) {
        handler.obtainMessage(ERR_SERIALIZATION).sendToTarget();
    }
}

From source file:com.evolveum.polygon.scim.GenericDataBuilder.java

/**
 * Builds a json object representation out of a provided set of
 * "attributes belonging to an extension". This type of attributes represent
 * a complex json object containing other key value pairs.
 * // www .ja  va2  s .  c o m
 * @param extensionAttribute
 *            A provided set of attributes.
 * @param json
 *            A json representation of the provided data set.
 * 
 * @return A json representation of the provided data set.
 */

public JSONObject buildExtensionAttribute(Set<Attribute> extensionAttribute, JSONObject json) {
    boolean isPartOfName = false;
    String mainAttributeName = "";
    Map<String, Map<String, Object>> processedGoods = new HashMap<String, Map<String, Object>>();

    for (Attribute i : extensionAttribute) {

        String attributeName = i.getName();
        attributeName = attributeName.replace(SEPPARATOR, FORBIDENSEPPARATOR);
        String[] attributeNameParts = attributeName.split(DELIMITER); // e.q.
        // urn:scim:schemas:extension:enterprise:1.0.division
        for (int position = 1; position < attributeNameParts.length; position++) {

            String namePart = attributeNameParts[position];

            for (int charPossition = 0; charPossition < namePart.length(); charPossition++) {
                char c = namePart.charAt(charPossition);
                if (Character.isDigit(c)) {
                    if (charPossition == 0 && charPossition + 1 == namePart.length()) {
                        isPartOfName = true;
                    } else if (charPossition + 1 == namePart.length() && !isPartOfName) {

                        isPartOfName = false;

                    } else {
                        isPartOfName = true;
                    }
                } else {
                    isPartOfName = false;
                }
            }
            if (!isPartOfName) {

                if (mainAttributeName.isEmpty()) {
                    mainAttributeName = attributeNameParts[0];
                }

                if (!processedGoods.containsKey(mainAttributeName)) {

                    Map<String, Object> processedAttribute = new HashMap<String, Object>();
                    processedAttribute.put(namePart, AttributeUtil.getSingleValue(i));
                    processedGoods.put(mainAttributeName, processedAttribute);
                    mainAttributeName = "";
                    break;
                } else {
                    Map<String, Object> processedAttribute = processedGoods.get(mainAttributeName);
                    processedAttribute.put(namePart, AttributeUtil.getSingleValue(i));
                    processedGoods.put(mainAttributeName, processedAttribute);
                    mainAttributeName = "";
                    break;
                }
            } else {
                StringBuilder buildName;
                if (mainAttributeName.isEmpty()) {
                    buildName = new StringBuilder(attributeNameParts[0]).append(DOT).append(namePart);
                    mainAttributeName = buildName.toString();
                } else {
                    buildName = new StringBuilder(mainAttributeName).append(DOT).append(namePart);
                    mainAttributeName = buildName.toString();
                }
            }

        }

    }
    if (!processedGoods.isEmpty()) {
        for (String attributeName : processedGoods.keySet()) {

            JSONObject subAttributes = new JSONObject();

            Map<String, Object> sAttribute = processedGoods.get(attributeName);

            for (String sAttributeName : sAttribute.keySet()) {
                subAttributes.put(sAttributeName, sAttribute.get(sAttributeName));
            }

            json.put(attributeName, subAttributes);

        }
    }

    return json;
}

From source file:cn.aposoft.util.spring.ReflectionUtils.java

/**
 * Determine whether the given method is a CGLIB 'renamed' method, following
 * the pattern "CGLIB$methodName$0".//from   w w  w .j  av a  2 s  .  co m
 * 
 * @param renamedMethod
 *            the method to check
 * @see org.springframework.cglib.proxy.Enhancer#rename
 */
public static boolean isCglibRenamedMethod(Method renamedMethod) {
    String name = renamedMethod.getName();
    if (name.startsWith(CGLIB_RENAMED_METHOD_PREFIX)) {
        int i = name.length() - 1;
        while (i >= 0 && Character.isDigit(name.charAt(i))) {
            i--;
        }
        return ((i > CGLIB_RENAMED_METHOD_PREFIX.length()) && (i < name.length() - 1) && name.charAt(i) == '$');
    }
    return false;
}

From source file:ca.mcgill.cs.swevo.qualyzer.editors.RTFDocumentProvider2.java

private ParserPair getUnicode(InputStream contentStream, Map<String, Integer> state) throws IOException {

    StringBuilder control = new StringBuilder();
    int c = contentStream.read();
    if (c != -1) {
        char ch = (char) c;
        if (ch == UNICODE_COUNT) {
            ParserPair number = getNumber(contentStream);
            control.append(UNICODE_COUNT_FULL);
            control.append(number.fString);
            c = number.fChar;//from w  w w . j ava  2s.c  o m
            // This is a control so a space is a delimiter.
            if (Character.isWhitespace((char) c)) {
                c = contentStream.read();
            }
        } else if (!Character.isDigit(ch)) {
            ParserPair result = handleControl(contentStream, c, String.valueOf(UNICODE), state);
            c = result.fChar;
            control = new StringBuilder(result.fString);
        } else {
            ParserPair number = getNumber(contentStream, Integer.parseInt(String.valueOf(ch)));
            int replacement = number.fChar;
            ParserPair replPair = getUnicodeReplacement(contentStream, replacement, state);
            c = replPair.fChar;

            control.append(UNICODE);
            control.append(number.fString);
            control.append(replPair.fString);
        }
    }

    return new ParserPair(c, control.toString());
}

From source file:com.dgtlrepublic.anitomyj.ParserNumber.java

/**
 * Attempts to find an volume numbers inside a {@code word}.
 *
 * @param word  the word/*from   w w  w. j  a  v  a 2s .c  o  m*/
 * @param token the token
 * @return true if the word was matched to an episode/season number
 */
public boolean matchVolumePatterns(String word, Token token) {
    // All patterns contain at least one non-numeric character
    if (StringHelper.isNumericString(word))
        return false;

    word = StringHelper.trimAny(word, " -");

    boolean numericFront = Character.isDigit(word.charAt(0));
    boolean numericBack = Character.isDigit(word.charAt(word.length() - 1));

    // e.g. "01v2"
    if (numericFront && numericBack)
        if (matchSingleVolumePattern(word, token))
            return true;
    // e.g. "01-02", "03-05v2"
    if (numericFront && numericBack)
        if (matchMultiVolumePattern(word, token))
            return true;

    return false;
}

From source file:com.larvalabs.svgandroid.SVGParser.java

/**
 * This is where the hard-to-parse paths are handled.
 * Uppercase rules are absolute positions, lowercase are relative.
 * Types of path rules://ww w.  java2  s  .com
 * <p/>
 * <ol>
 * <li>M/m - (x y)+ - Move to (without drawing)
 * <li>Z/z - (no params) - Close path (back to starting point)
 * <li>L/l - (x y)+ - Line to
 * <li>H/h - x+ - Horizontal ine to
 * <li>V/v - y+ - Vertical line to
 * <li>C/c - (x1 y1 x2 y2 x y)+ - Cubic bezier to
 * <li>S/s - (x2 y2 x y)+ - Smooth cubic bezier to (shorthand that assumes the x2, y2 from previous C/S is the x1, y1 of this bezier)
 * <li>Q/q - (x1 y1 x y)+ - Quadratic bezier to
 * <li>T/t - (x y)+ - Smooth quadratic bezier to (assumes previous control point is "reflection" of last one w.r.t. to current point)
 * </ol>
 * <p/>
 * Numbers are separate by whitespace, comma or nothing at all (!) if they are self-delimiting, (ie. begin with a - sign)
 *
 * @param s the path string from the XML
 */
private static Path doPath(String s) {
    int n = s.length();
    ParserHelper ph = new ParserHelper(s, 0);
    ph.skipWhitespace();
    Path p = new Path();
    float lastX = 0;
    float lastY = 0;
    float lastX1 = 0;
    float lastY1 = 0;
    RectF r = new RectF();
    char cmd = 'x';
    while (ph.pos < n) {
        char next = s.charAt(ph.pos);
        if (!Character.isDigit(next) && !(next == '.') && !(next == '-')) {
            cmd = next;
            ph.advance();
        } else if (cmd == 'M') { // implied command
            cmd = 'L';
        } else if (cmd == 'm') { // implied command
            cmd = 'l';
        } else { // implied command
            // Log.d(TAG, "Implied command: " + cmd);
        }
        p.computeBounds(r, true);
        // Log.d(TAG, "  " + cmd + " " + r);
        // Util.debug("* Commands remaining: '" + path + "'.");
        boolean wasCurve = false;
        switch (cmd) {
        case 'M':
        case 'm': {
            float x = ph.nextFloat();
            float y = ph.nextFloat();
            if (cmd == 'm') {
                p.rMoveTo(x, y);
                lastX += x;
                lastY += y;
            } else {
                p.moveTo(x, y);
                lastX = x;
                lastY = y;
            }
            break;
        }
        case 'Z':
        case 'z': {
            p.close();
            break;
        }
        case 'L':
        case 'l': {
            float x = ph.nextFloat();
            float y = ph.nextFloat();
            if (cmd == 'l') {
                p.rLineTo(x, y);
                lastX += x;
                lastY += y;
            } else {
                p.lineTo(x, y);
                lastX = x;
                lastY = y;
            }
            break;
        }
        case 'H':
        case 'h': {
            float x = ph.nextFloat();
            if (cmd == 'h') {
                p.rLineTo(x, 0);
                lastX += x;
            } else {
                p.lineTo(x, lastY);
                lastX = x;
            }
            break;
        }
        case 'V':
        case 'v': {
            float y = ph.nextFloat();
            if (cmd == 'v') {
                p.rLineTo(0, y);
                lastY += y;
            } else {
                p.lineTo(lastX, y);
                lastY = y;
            }
            break;
        }
        case 'C':
        case 'c': {
            wasCurve = true;
            float x1 = ph.nextFloat();
            float y1 = ph.nextFloat();
            float x2 = ph.nextFloat();
            float y2 = ph.nextFloat();
            float x = ph.nextFloat();
            float y = ph.nextFloat();
            if (cmd == 'c') {
                x1 += lastX;
                x2 += lastX;
                x += lastX;
                y1 += lastY;
                y2 += lastY;
                y += lastY;
            }
            p.cubicTo(x1, y1, x2, y2, x, y);
            lastX1 = x2;
            lastY1 = y2;
            lastX = x;
            lastY = y;
            break;
        }
        case 'S':
        case 's': {
            wasCurve = true;
            float x2 = ph.nextFloat();
            float y2 = ph.nextFloat();
            float x = ph.nextFloat();
            float y = ph.nextFloat();
            if (cmd == 's') {
                x2 += lastX;
                x += lastX;
                y2 += lastY;
                y += lastY;
            }
            float x1 = 2 * lastX - lastX1;
            float y1 = 2 * lastY - lastY1;
            p.cubicTo(x1, y1, x2, y2, x, y);
            lastX1 = x2;
            lastY1 = y2;
            lastX = x;
            lastY = y;
            break;
        }
        case 'A':
        case 'a': {
            float rx = ph.nextFloat();
            float ry = ph.nextFloat();
            float theta = ph.nextFloat();
            int largeArc = (int) ph.nextFloat();
            int sweepArc = (int) ph.nextFloat();
            float x = ph.nextFloat();
            float y = ph.nextFloat();
            if (cmd == 'a') {
                x += lastX;
                y += lastY;
            }
            drawArc(p, lastX, lastY, x, y, rx, ry, theta, largeArc == 1, sweepArc == 1);
            lastX = x;
            lastY = y;
            break;
        }
        default:
            Log.d(TAG, "Invalid path command: " + cmd);
            ph.advance();
        }
        if (!wasCurve) {
            lastX1 = lastX;
            lastY1 = lastY;
        }
        ph.skipWhitespace();
    }
    return p;
}