Example usage for java.lang Character isLetter

List of usage examples for java.lang Character isLetter

Introduction

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

Prototype

public static boolean isLetter(int codePoint) 

Source Link

Document

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

Usage

From source file:edu.umd.cfar.lamp.viper.util.StringHelp.java

/**
 * Checks to see if a String is a legal identifier.
 * Uses java/c++ standards, execept it cannot start with
 * an underscore.//from   www.  ja v a  2 s  .  c om
 *
 * @param str The String to check.
 * @return <code>true</code> if the String uses valid characters.
 */
public static boolean isLegalIdentifier(String str) {
    if (str == null)
        return (false);

    char c = str.charAt(0);
    if (!Character.isLetter(c)) {
        return (false);
    }
    int size = str.length();
    for (int i = 1; i < size; i++) {
        c = str.charAt(i);
        if (!(Character.isLetterOrDigit(c) || c == '_' || c == '-'))
            return (false);
    }
    return (true);
}

From source file:com.globalsight.everest.webapp.pagehandler.edit.inctxrv.EditorPageHandler.java

private String removeSpecialChars(String segment) {
    if (segment == null) {
        return "";
    }/*w w w  .ja va2 s  .  c o  m*/

    StringBuffer sb = new StringBuffer();

    for (int i = 0; i < segment.length(); i++) {
        char ccc = segment.charAt(i);

        if (ccc == 9632) {
            continue;
        }

        if (i > 0) {
            char lastChar = sb.length() > 0 ? sb.charAt(sb.length() - 1) : 'N';
            // ignore tab
            if (ccc == '\t' && lastChar == ' ') {
                continue;
            }

            // ignore Hyphen char
            if (i < segment.length() - 1) {
                char nextChar = segment.charAt(i + 1);
                if (ccc == 173 && lastChar == ' ' && Character.isLetter(nextChar)) {
                    continue;
                }
            }
        }

        sb.append(ccc);
    }

    String result = sb.toString().trim();
    result = StringUtil.replace(result, "\t", " ");
    result = StringUtil.replaceWithRE(result, "[ \t]{2,}", " ");

    return result;
}

From source file:org.apache.hyracks.data.std.primitive.UTF8StringPointable.java

/**
 * Generates a "title" format string from an input source string, i.e., the first letter of each word
 * is in the upper case while the other letter is in the lower case.
 *
 * @param src//from ww  w  . j  a va  2 s .  c om
 *            , the input source string.
 * @param builder
 *            , a builder for the resulting string.
 * @param out
 *            , the storage for a result string.
 * @throws IOException
 */
public static void initCap(UTF8StringPointable src, UTF8StringBuilder builder, GrowableArray out)
        throws IOException {
    final int srcUtfLen = src.getUTF8Length();
    final int srcStart = src.getMetaDataLength();

    builder.reset(out, srcUtfLen);
    boolean toUpperCase = true;
    int byteIndex = 0;
    while (byteIndex < srcUtfLen) {
        char originalChar = src.charAt(srcStart + byteIndex);
        boolean isLetter = Character.isLetter(originalChar);

        // Make the first character into upper case while the later ones into lower case.
        char resultChar = toUpperCase && isLetter ? Character.toUpperCase(originalChar)
                : (isLetter ? Character.toLowerCase(originalChar) : originalChar);
        builder.appendChar(resultChar);
        byteIndex += src.charSize(srcStart + byteIndex);

        // Whether the next letter needs to switch to the upper case.
        toUpperCase = !isLetter;
    }
    builder.finish();
}

From source file:com.openerp.addons.messages.Message.java

public static String capitalizeString(String string) {
    char[] chars = string.toLowerCase().toCharArray();
    boolean found = false;
    for (int i = 0; i < chars.length; i++) {
        if (!found && Character.isLetter(chars[i])) {
            chars[i] = Character.toUpperCase(chars[i]);
            found = true;/*from www .  j  a v a  2  s  . co  m*/
        } else if (Character.isWhitespace(chars[i]) || chars[i] == '.' || chars[i] == '\'') { // You can add other chars here
            found = false;
        }
    }
    return String.valueOf(chars);
}

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

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

    try {//from   w w  w. j  av a  2 s .c  om
        // 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:org.novoj.utils.datePattern.DatePatternConverter.java

/**
 * Returns delimiter between date and time part of the DateFormat pattern. This part is needed to by handed forward
 * to the jQueryUI DatePicker to combine data with TimePicker addon.
 *
 * @param patternDecomposition// ww  w . j a  v  a 2s  . c o  m
 * @return
 * @throws PatternNotConvertableException
 */
@SuppressWarnings({ "ImplicitNumericConversion", "OverlyComplexMethod" })
public String getDateAndTimeDelimiter(List<String> patternDecomposition) throws PatternNotConvertableException {
    boolean anyPatternRecognized = false;
    Map<String, String> patternSource = null;

    StringBuffer result = new StringBuffer();
    for (String patternPart : patternDecomposition) {
        char leadLetter = patternPart.charAt(0);
        if (leadLetter == '\'') {
            if (anyPatternRecognized) {
                result.append(patternPart);
            }
        } else if (Character.isLetter(leadLetter)) {
            if (java2jQueryUIdatePatterns.containsKey(patternPart)
                    || java2jQueryUItimePatterns.containsKey(patternPart)) {

                if (patternSource != null && patternSource.containsKey(patternPart)) {
                    result = new StringBuffer();
                } else {
                    if (anyPatternRecognized) {
                        break;
                    } else {
                        anyPatternRecognized = true;
                        patternSource = java2jQueryUIdatePatterns.containsKey(patternPart)
                                ? java2jQueryUIdatePatterns
                                : java2jQueryUItimePatterns;
                    }
                }

            }
        } else {
            if (anyPatternRecognized) {
                if (result.length() > 0 || !specialCharacters.contains(new Character(patternPart.charAt(0)))) {
                    result.append(patternPart);
                }
            }
        }
    }

    return REGEX_APOSTROPHE.matcher(result.toString()).replaceAll("");
}

From source file:com.android.tools.lint.checks.StringFormatDetector.java

private void checkTextNode(XmlContext context, Element element, String text) {
    String name = element.getAttribute(ATTR_NAME);
    boolean found = false;
    boolean foundPlural = false;

    // Look at the String and see if it's a format string (contains
    // positional %'s)
    for (int j = 0, m = text.length(); j < m; j++) {
        char c = text.charAt(j);
        if (c == '\\') {
            j++;/*from   ww  w .  j  a  va2  s . co  m*/
        }
        if (c == '%') {
            // Also make sure this String isn't an unformatted String
            String formatted = element.getAttribute("formatted"); //$NON-NLS-1$
            if (!formatted.isEmpty() && !Boolean.parseBoolean(formatted)) {
                if (!mNotFormatStrings.containsKey(name)) {
                    Handle handle = context.createLocationHandle(element);
                    handle.setClientData(element);
                    mNotFormatStrings.put(name, handle);
                }
                return;
            }

            // See if it's not a format string, e.g. "Battery charge is 100%!".
            // If so we want to record this name in a special list such that we can
            // make sure you don't attempt to reference this string from a String.format
            // call.
            Matcher matcher = FORMAT.matcher(text);
            if (!matcher.find(j)) {
                if (!mNotFormatStrings.containsKey(name)) {
                    Handle handle = context.createLocationHandle(element);
                    handle.setClientData(element);
                    mNotFormatStrings.put(name, handle);
                }
                return;
            }

            String conversion = matcher.group(6);
            int conversionClass = getConversionClass(conversion.charAt(0));
            if (conversionClass == CONVERSION_CLASS_UNKNOWN || matcher.group(5) != null) {
                if (mIgnoreStrings == null) {
                    mIgnoreStrings = new HashSet<String>();
                }
                mIgnoreStrings.add(name);

                // Don't process any other strings here; some of them could
                // accidentally look like a string, e.g. "%H" is a hash code conversion
                // in String.format (and hour in Time formatting).
                return;
            }

            if (conversionClass == CONVERSION_CLASS_INTEGER && !foundPlural) {
                // See if there appears to be further text content here.
                // Look for whitespace followed by a letter, with no punctuation in between
                for (int k = matcher.end(); k < m; k++) {
                    char nc = text.charAt(k);
                    if (!Character.isWhitespace(nc)) {
                        if (Character.isLetter(nc)) {
                            foundPlural = checkPotentialPlural(context, element, text, k);
                        }
                        break;
                    }
                }
            }

            found = true;
            j++; // Ensure that when we process a "%%" we don't separately check the second %
        }
    }

    if (!context.getProject().getReportIssues()) {
        // If this is a library project not being analyzed, ignore it
        return;
    }

    if (name != null) {
        Handle handle = context.createLocationHandle(element);
        handle.setClientData(element);
        if (found) {
            // Record it for analysis when seen in Java code
            if (mFormatStrings == null) {
                mFormatStrings = new HashMap<String, List<Pair<Handle, String>>>();
            }

            List<Pair<Handle, String>> list = mFormatStrings.get(name);
            if (list == null) {
                list = new ArrayList<Pair<Handle, String>>();
                mFormatStrings.put(name, list);
            }
            list.add(Pair.of(handle, text));
        } else {
            if (!isReference(text)) {
                mNotFormatStrings.put(name, handle);
            }
        }
    }
}

From source file:org.apache.camel.component.jms.JmsBinding.java

/**
 * Is the given header a standard JMS header
 * @param headerName the header name/*from   w w w . j a  v  a2s.co  m*/
 * @return <tt>true</tt> if its a standard JMS header
 */
protected boolean isStandardJMSHeader(String headerName) {
    if (!headerName.startsWith("JMS")) {
        return false;
    }
    if (headerName.startsWith("JMSX")) {
        return false;
    }
    // IBM WebSphereMQ uses JMS_IBM as special headers
    if (headerName.startsWith("JMS_")) {
        return false;
    }

    // the 4th char must be a letter to be a standard JMS header
    if (headerName.length() > 3) {
        Character fourth = headerName.charAt(3);
        if (Character.isLetter(fourth)) {
            return true;
        }
    }

    return false;
}

From source file:org.sharegov.cirm.utils.GenUtils.java

/**
 * Ensures that a string starts with a capitalized letter.
 * @param s accepts a string, null, empty
 * @return//from w  w  w. jav  a2  s. c om
 */
public static String capitalize(String s) {
    if (s == null || s.isEmpty())
        return s;
    char first = s.charAt(0);
    if (Character.isLetter(first) && Character.isLowerCase(first))
        return Character.toUpperCase(first) + s.substring(1);
    else
        return s;
}

From source file:com.huofu.RestaurantOS.ui.splash.activate.java

/**
 * ?//w  w w  .j av a2 s .c o m
 */
public void widgetConfigure() {

    buttonActivate.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            if (authDialog == null) {
                authDialog = new Dialog(activate.this, R.style.PauseDialog);
            }
            if (ttv.getParent() != null) {
                ttv = new TitanicTextView(ctxt);
            }

            String key = etActivteCode.getText().toString();
            if (key.length() >= 16) {
                CommonUtils.LogWuwei(tag, "key is " + key);
                CommonUtils.sendMsg("?", activate.SHOW_LOADING_TEXT, mUiHandler);
                activate(ctxt, key);
            } else {
                CommonUtils.sendMsg("????", activate.SHOW_ERROR_MESSAGE, mUiHandler);
            }

        }
    });

    InputFilter filter = new InputFilter() {

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                int dend) {
            // TODO Auto-generated method stub
            for (int i = start; i < end; i++) {
                //???'-'
                if (!Character.isLetter(source.charAt(i)) && source.charAt(i) != '-') {
                    return "";
                }
            }
            return null;
        }
    };

    InputFilter filterLength = new InputFilter.LengthFilter(19);

    etActivteCode.setCursorVisible(false);
    etActivteCode.setFilters(new InputFilter[] { filter, filterLength });
    etActivteCode.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

            etActivteCode.setCursorVisible(true);
            etActivteCode.removeTextChangedListener(this);// ?
            etActivteCode.setText(s.toString().toUpperCase());// ?
            etActivteCode.setSelection(s.toString().length());// ??
            etActivteCode.addTextChangedListener(this);// ?
            String licensePlateNumber = etActivteCode.getText().toString().trim();

            if (s.length() == 19) {
                InputMethodUtils.HideKeyboard(etActivteCode);
            }

        }
    });
    etActivteCode.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // TODO Auto-generated method stub
            if (keyCode == KeyEvent.KEYCODE_DEL) {
                CommonUtils.LogWuwei(tag, "delete");
                etActivteCode.setCursorVisible(false);
            }
            return false;
        }
    });

    rl_activate_qrscan_ready.setVisibility(View.INVISIBLE);

    OnClickListener oclGetQrCode = new OnClickListener() {
        @Override
        public void onClick(View v) {
            flagInQrcodeDialog = true;
            CommonUtils.sendMsg("??", SHOW_LOADING_TEXT, mUiHandler);

            if (LocalDataDeal.readFromLocalPublicKey(ctxt) == null
                    || LocalDataDeal.readFromLocalPublicKey(ctxt).equals("")) {
                ApisManager.GetPublicKey(new ApiCallback() {
                    @Override
                    public void success(Object object) {
                        sendUIMessage(HIDE_LOADING, "");
                        try {
                            org.json.JSONObject obj = new org.json.JSONObject((String) object);
                            String public_key = obj.getString("public_key");
                            LocalDataDeal.writeToLocalPublicKey(public_key, ctxt);//key?base64?
                        } catch (Exception e) {
                        }
                        CommonUtils.sendMsg("", GET_QRCODE, mUiHandler);
                    }

                    @Override
                    public void error(BaseApi.ApiResponse response) {
                        sendUIMessage(HIDE_LOADING, "");
                        sendUIMessage(SHOW_ERROR_MESSAGE, response.error_message);
                    }
                });
            } else {
                CommonUtils.sendMsg("", GET_QRCODE, mUiHandler);
            }

            rl_activate_input.setVisibility(View.INVISIBLE);
            rl_activate_qrscan_ready.setVisibility(View.VISIBLE);
            imageViewQrcode.setVisibility(View.INVISIBLE);
            rl_activate_qrscan_ready
                    .startAnimation(new AnimationUtils().loadAnimation(ctxt, R.anim.small_2_big));

            textviewScanStauts.setTextColor(Color.parseColor("#898989"));
            textviewScanStauts.setText(R.string.activateByQrCodeTips);

            rl_activate_qrscan_ready
                    .startAnimation(new AnimationUtils().loadAnimation(ctxt, R.anim.slide_left_in));
            rl_activate_input.startAnimation(new AnimationUtils().loadAnimation(ctxt, R.anim.slide_right_out));
        }
    };

    buttonSwitchQrScan.setOnClickListener(oclGetQrCode);
    findViewById(R.id.rl_switch_activate_qrcode_way).setOnClickListener(oclGetQrCode);

    buttonSwitchInputCode.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            flagInQrcodeDialog = false;
            flagWaitingCmd = false;
            rl_activate_qrscan_ready.setVisibility(View.INVISIBLE);
            rl_activate_input.setVisibility(View.VISIBLE);
            rl_activate_input.startAnimation(new AnimationUtils().loadAnimation(ctxt, R.anim.small_2_big));

            stopQrScanTimer();

            rl_activate_input.startAnimation(new AnimationUtils().loadAnimation(ctxt, R.anim.slide_right_in));
            rl_activate_qrscan_ready
                    .startAnimation(new AnimationUtils().loadAnimation(ctxt, R.anim.slide_left_out));

        }
    });

    findViewById(R.id.rl_switch_activate_keyboard_way).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            flagInQrcodeDialog = false;
            flagWaitingCmd = false;
            rl_activate_qrscan_ready.setVisibility(View.INVISIBLE);
            rl_activate_input.setVisibility(View.VISIBLE);
            rl_activate_input.startAnimation(new AnimationUtils().loadAnimation(ctxt, R.anim.small_2_big));

            stopQrScanTimer();
        }
    });

    PackageManager manager;
    PackageInfo info = null;
    manager = this.getPackageManager();
    String versionName = null;
    try {
        info = manager.getPackageInfo(this.getPackageName(), 0);
        versionName = info.versionName;
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }

    ((TextView) findViewById(R.id.tv_app_version))
            .setText(getResources().getString(R.string.app_name) + " V" + versionName);

    LocalDataDeal.writeToLocalVersion(versionName, ctxt);
    LocalDataDeal.writeToLocalVersionCode(info.versionCode, ctxt);

    ftpServiceStart();
}