Example usage for java.lang Character toChars

List of usage examples for java.lang Character toChars

Introduction

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

Prototype

public static char[] toChars(int codePoint) 

Source Link

Document

Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array.

Usage

From source file:org.eclipse.rdf4j.rio.turtle.TurtleParser.java

/**
 * Verifies that the supplied character code point <tt>codePoint</tt> is one
 * of the expected characters specified in <tt>expected</tt>. This method
 * will throw a <tt>ParseException</tt> if this is not the case.
 *///  www . java  2  s . c  o  m
protected void verifyCharacterOrFail(int codePoint, String expected) throws RDFParseException {
    if (codePoint == -1) {
        throwEOFException();
    }

    final String supplied = new String(Character.toChars(codePoint));

    if (expected.indexOf(supplied) == -1) {
        StringBuilder msg = new StringBuilder(32);
        msg.append("Expected ");
        for (int i = 0; i < expected.length(); i++) {
            if (i > 0) {
                msg.append(" or ");
            }
            msg.append('\'');
            msg.append(expected.charAt(i));
            msg.append('\'');
        }
        msg.append(", found '");
        msg.append(supplied);
        msg.append("'");

        reportFatalError(msg.toString());
    }
}

From source file:org.openrdf.rio.turtle.TurtleParser.java

/**
 * Consumes characters from reader until the first EOL has been read. This
 * line of text is then passed to the {@link #rdfHandler} as a comment.
 *///  w  w  w.  j a v a  2s. c o m
protected void processComment() throws IOException, RDFHandlerException {
    StringBuilder comment = new StringBuilder(64);
    int c = readCodePoint();
    while (c != -1 && c != 0xD && c != 0xA) {
        comment.append(Character.toChars(c));
        c = readCodePoint();
    }

    // c is equal to -1, \r or \n.
    // In case c is equal to \r, we should also read a following \n.
    if (c == 0xD) {
        c = readCodePoint();

        if (c != 0xA) {
            unread(c);
        }
    }
    if (rdfHandler != null) {
        rdfHandler.handleComment(comment.toString());
    }
    reportLocation();
}

From source file:org.eclipse.rdf4j.rio.turtle.TurtleParser.java

/**
 * Pushes back a single code point by copying it to the front of the buffer.
 * After this method returns, a call to {@link #readCodePoint()} will return
 * the same code point c again./*from w w  w.  ja  va  2 s  .  co m*/
 *
 * @param codePoint
 *            a single Unicode code point.
 * @throws IOException
 */
protected void unread(int codePoint) throws IOException {
    if (codePoint != -1) {
        if (Character.isSupplementaryCodePoint(codePoint)) {
            final char[] surrogatePair = Character.toChars(codePoint);
            reader.unread(surrogatePair);
        } else {
            reader.unread(codePoint);
        }
    }
}

From source file:com.gelakinetic.mtgfam.helpers.CardDbAdapter.java

public Cursor PrefixSearch(String cardname, String[] returnTypes) throws FamiliarDbException {
    Cursor mCursor = null;//w ww . j  a v a  2s. co m
    String convertName = null;

    if (cardname != null) {
        cardname = cardname.replace(Character.toChars(0xE6)[0], Character.toChars(0xC6)[0]).trim();
        convertName = cardname.toLowerCase().replace("ae", String.valueOf(Character.toChars(0xC6)[0]));
    }

    String statement = " WHERE 1=1";

    statement += " AND (" + DATABASE_TABLE_CARDS + "." + KEY_NAME + " LIKE "
            + DatabaseUtils.sqlEscapeString(cardname + "%") + " OR " + DATABASE_TABLE_CARDS + "." + KEY_NAME
            + " LIKE " + DatabaseUtils.sqlEscapeString(convertName + "%") + ")";

    try {
        String sel = null;
        for (String s : returnTypes) {
            if (sel == null) {
                sel = DATABASE_TABLE_CARDS + "." + s + " AS " + s;
            } else {
                sel += ", " + DATABASE_TABLE_CARDS + "." + s + " AS " + s;
            }
        }
        sel += ", " + DATABASE_TABLE_SETS + "." + KEY_DATE;

        String sql = "SELECT * FROM (SELECT " + sel + " FROM " + DATABASE_TABLE_CARDS + " JOIN "
                + DATABASE_TABLE_SETS + " ON " + DATABASE_TABLE_CARDS + "." + KEY_SET + " = "
                + DATABASE_TABLE_SETS + "." + KEY_CODE + statement;

        sql += " ORDER BY " + DATABASE_TABLE_SETS + "." + KEY_DATE + ") GROUP BY " + KEY_NAME + " ORDER BY "
                + KEY_NAME + " COLLATE UNICODE";
        mCursor = mDb.rawQuery(sql, null);
    } catch (SQLiteException e) {
        throw new FamiliarDbException(e);
    } catch (IllegalStateException e) {
        throw new FamiliarDbException(e);
    }
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

From source file:org.eclipse.rdf4j.rio.turtle.TurtleParser.java

/**
 * Pushes back the supplied string by copying it to the front of the buffer.
 * After this method returns, successive calls to {@link #readCodePoint()}
 * will return the code points in the supplied string again, starting at the
 * first in the String..//from  w ww .j  a v a  2 s .c o  m
 *
 * @param string
 *            the string to un-read.
 * @throws IOException
 */
protected void unread(String string) throws IOException {
    for (int i = string.codePointCount(0, string.length()); i >= 1; i--) {
        final int codePoint = string.codePointBefore(i);
        if (Character.isSupplementaryCodePoint(codePoint)) {
            final char[] surrogatePair = Character.toChars(codePoint);
            reader.unread(surrogatePair);
        } else {
            reader.unread(codePoint);
        }
    }
}

From source file:org.igov.service.business.action.task.core.ActionTaskService.java

public String getSeparator(String sID_BP, String nASCI_Spliter) {
    if (nASCI_Spliter == null) {
        return String.valueOf(Character.toChars(DEFAULT_REPORT_FIELD_SPLITTER));
    }//www . ja va2s.  co m
    if (!StringUtils.isNumeric(nASCI_Spliter)) {
        LOG.error("ASCI code is not a number {}", nASCI_Spliter);
        throw new ActivitiObjectNotFoundException(
                "Statistics for the business task with name '" + sID_BP + "' not found. Wrong splitter.",
                Task.class);
    }
    return String.valueOf(Character.toChars(Integer.valueOf(nASCI_Spliter)));
}

From source file:com.screenslicer.common.HtmlCoder.java

private static String codePointToSymbol(int codePoint) {
    char[] chars = new char[0];
    if ((codePoint >= 0xD800 && codePoint <= 0xDFFF) || codePoint > 0x10FFFF) {
        return "\uFFFD";
    }/*  w  w w .j  av  a  2 s.c  o  m*/
    if (decodeMapNumeric.containsKey(codePoint)) {
        return decodeMapNumeric.get(codePoint);
    }
    if (codePoint > 0xFFFF) {
        codePoint -= 0x10000;
        chars = ArrayUtils.addAll(chars, Character.toChars(codePoint >>> 10 & 0x3FF | 0xD800));
        codePoint = 0xDC00 | codePoint & 0x3FF;
    }
    chars = ArrayUtils.addAll(chars, Character.toChars(codePoint));
    return new String(chars);
}

From source file:com.gelakinetic.mtgfam.helpers.CardDbAdapter.java

public int checkLegality(String mCardName, String format) throws FamiliarDbException {
    mCardName = mCardName.replace("'", "''").replace(Character.toChars(0xE6)[0], Character.toChars(0xC6)[0]);
    format = format.replace("'", "''"); // Just to be safe; remember Bobby
    // Tables/*from  w w  w .  j  a  v  a  2 s .  c o  m*/
    try {
        // The new way (single query per type, should be much faster) - Alex
        String sql = "SELECT COALESCE(CASE (SELECT " + KEY_SET + " FROM " + DATABASE_TABLE_CARDS + " WHERE "
                + KEY_NAME + " = '" + mCardName
                + "') WHEN 'UG' THEN 1 WHEN 'UNH' THEN 1 WHEN 'ARS' THEN 1 WHEN 'PCP' THEN 1 "
                + "WHEN 'PP2' THEN 1 ELSE NULL END, " + "CASE (SELECT 1 FROM " + DATABASE_TABLE_CARDS
                + " c INNER JOIN " + DATABASE_TABLE_LEGAL_SETS + " ls ON ls." + KEY_SET + " = c." + KEY_SET
                + " WHERE ls." + KEY_FORMAT + " = '" + format + "' AND c." + KEY_NAME + " = '" + mCardName
                + "') WHEN 1 THEN NULL ELSE CASE WHEN '" + format + "' = 'Legacy' " + "THEN NULL WHEN '"
                + format + "' = 'Vintage' THEN NULL ELSE 1 END END, (SELECT " + KEY_LEGALITY + " from "
                + DATABASE_TABLE_BANNED_CARDS + " WHERE " + KEY_NAME + " = '" + mCardName + "' AND "
                + KEY_FORMAT + " = '" + format + "'), 0) AS " + KEY_LEGALITY;

        Cursor c = null;
        c = mDb.rawQuery(sql, null);

        c.moveToFirst();
        int legality = c.getInt(c.getColumnIndex(KEY_LEGALITY));
        c.close();
        return legality;
    } catch (SQLiteException e) {
        throw new FamiliarDbException(e);
    } catch (IllegalStateException e) {
        throw new FamiliarDbException(e);
    }
}

From source file:com.strathclyde.highlightingkeyboard.SoftKeyboardService.java

/**
 * Manages actual input into the editor. Here we:
 * implement our injection algorithm as required
 * store data relating to the key press/*from   www  .j av  a 2 s  .c  om*/
 * initiate any spell checking as required
 */
public void onKey(int primaryCode, int[] keyCodes) {

    // touches all done, add the chars to the event and then the event to the session       
    currentEvent.keyCode = primaryCode;

    if (errorInjection && primaryCode >= 32) {
        //give a n% chance of the key being modified
        Random r = new Random();
        int res = r.nextInt(100);
        if (res <= errorInjectionThreshold) //%n chance of key being modified
        {
            //Log.i("OnKey", "Will modify");
            try {
                //for each combination in the model, find the eucleidian distance and the replacement freq
                JSONObject targetObj = suspectReplacementDistribution
                        .getJSONObject(Integer.toString(primaryCode));
                Iterator<?> keys = targetObj.keys();
                ArrayList<Character> list = new ArrayList();
                while (keys.hasNext()) {
                    String key = (String) keys.next();
                    int freq = targetObj.getInt(key);
                    //if the frequency is 0, add the suspect as a replacement candidate
                    double dist = keyModel.distance2(primaryCode, Integer.parseInt(key));

                    if (dist > 0) {
                        if (dist > 2.0) //fix it so that only nearby keys have a chance of being elected
                            dist = 100;
                        //add to the list of candidates as many times as required if specific freq>0;
                        int sfreq = (int) Math.round(freq / dist);
                        //Log.i("Test", "Freq/Dist to "+key+": "+freq+"/"+dist+" final prob: "+sfreq);

                        if (sfreq == 0) //add the suspect as a replacement candidate
                        {
                            list.add(Character.toChars(primaryCode)[0]);
                        } else //add the other replacement candidates as required
                        {
                            for (int x = 0; x < targetObj.getInt(key); x++) {
                                list.add(Character.toChars(Integer.parseInt(key))[0]);

                            }
                        }
                    }
                }
                //Log.i("OnKey", "Replace list size: "+list.size());

                Random x = new Random();
                int sel = x.nextInt(list.size());

                //if the replacement eventually happens
                if ((int) list.get(sel) != primaryCode) {

                    if (errorInjectionSound) {
                        final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
                        tg.startTone(ToneGenerator.TONE_CDMA_SOFT_ERROR_LITE);
                    }
                    //primaryCode = (int)list.get(sel);

                    //Log.w("OnKey", "Replace "+Character.toChars(primaryCode)[0]+" with "+list.get(sel));
                    errorMap.put(mComposing.length(), (char) (int) list.get(sel)); //put in our current position and the replacement
                    //nInjections++;      
                } else
                    Log.i("OnKey", "Replacement will not happen, same key selected");

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            //Log.i("OnKey", "Will not modify, r="+res);
        }
    }
    //switch adaptxt language if necessary
    if (coreEngine != null) {
        switch (mInputView.currentKeyboard) {
        case KeyboardViews.QWERTY_EL:
            coreEngine.activateLanguageKeymap(131092, null);
            coreEngine.setDictionaryPriority(131092, 0);
            break;
        case KeyboardViews.QWERTY_EN:
            coreEngine.activateLanguageKeymap(131081, null);
            coreEngine.setDictionaryPriority(131092, 1);
            break;
        }
    }

    //get the full inputted text
    extr = ic.getExtractedText(new ExtractedTextRequest(), 0);

    if (currentEvent != null && captureData == true) {

        //Log.i("OnKey", "OK to capture data!");
        currentEvent.user = userid;

        if (primaryCode > 0)
            currentEvent.keyChar = (char) primaryCode;

        //handle the booleans
        if (currentSession.events.get(currentSession.events.size() - 1).keyChar == ' ') //space
        {
            currentEvent.followsSpace = true;
        }

        if (currentEvent.keyCode == Keyboard.KEYCODE_DELETE) {
            System.out.println("Backspace Pressed!");

            //if a delete is pressed after another delete
            //and its cursor position is not -1 from the previous delete
            //we must commit the previous deletion as a suspect character.
            if (currentSession.events.get(currentSession.events.size() - 1).keyCode == Keyboard.KEYCODE_DELETE
                    && extr.selectionStart != lastDeletedPos - 1) {
                currentSession.suspects.add(lastDeleted);
                //System.out.println("Suspect = "+lastDeleted);
            }

            //get all the text before the backspace press and the current cursor position
            if (extr.selectionStart > 0) {
                lastDeleted = extr.text.charAt(extr.selectionStart - 1);
                lastDeletedPos = extr.selectionStart;
                //System.out.println("Deleted = "+lastDeleted+"\nCursor Position = "+extr.selectionStart);
            }
        }

        //if the current key is NOT a backspace but the previous one was
        if (currentEvent.keyCode != Keyboard.KEYCODE_DELETE && currentSession.events
                .get(currentSession.events.size() - 1).keyCode == Keyboard.KEYCODE_DELETE) {
            currentSession.suspects.add(lastDeleted);
            //System.out.println("Suspect = "+lastDeleted);

        }

    }

    //do the handling     
    if (isWordSeparator(primaryCode)) {
        // Handle separator
        //System.out.println("Detected a word separator \""+primaryCode+"\"");
        if (primaryCode != 32) {
            shouldInsertSpace = false;
            if (extr.text.length() > 0) {
                //Log.i("On Key ", "last letter after separator was ["+extr.text.charAt(extr.selectionStart-1)+"]");
                //check if the previous char was a space, if so delete it.
                if (extr.text.charAt(extr.selectionStart - 1) == ' ' && !isSpecialSeparator(primaryCode)) //detecting if the current char is not part of a smiley face
                {
                    onKey(-5, null);
                }
            }
        }

        //clear the touch history
        clearDots();

        //ensure spell checker is using correct language          
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

        Editor ed = prefs.edit();
        if (captureData) {
            if (mInputView.currentLang == 1) //english
            {
                ed.putString("available_dicts", "en");
                ed.commit();
                if (mScs != null)
                    mScs.close();
                String lang = prefs.getString("available_dicts", "jam");
                Log.i("OnKey", "Spellcheck lang set to " + lang);
                Locale english = new Locale("en", "GB");
                mScs = tsm.newSpellCheckerSession(null, english, this, false);
                if (mScs == null)
                    Log.e("OnKey", "Failed to obtain spell-checker session");
            } else {
                ed.putString("available_dicts", "el");
                ed.commit();
                if (mScs != null)
                    mScs.close();
                String lang = prefs.getString("available_dicts", "jam");
                Log.i("OnKey", "Spellcheck lang set to " + lang);
                Locale greek = new Locale("el", "GR");
                mScs = tsm.newSpellCheckerSession(null, greek, this, false);
                if (mScs == null)
                    Log.e("OnKey", "Failed to obtain spell-checker session");
            }
        }

        //handle space for Adaptxt
        if (Character.isSpaceChar(primaryCode)) {
            if (coreEngine != null) {
                //Log.i("Handle Character", "Space pressed");
                coreEngine.resetCoreString();
                //Log.i("Space Pressed", "Word is "+mComposing+" ");
                coreEngine.insertText(mComposing.toString() + " ");
                updateCandidates();
            }
        }

        if (!firstWordSet && mComposing.length() > 1) {
            if (captureData)
                currentSession.firstWord = mComposing.toString();
            else
                currentSession.firstWord = "$$$$";

            firstWordSet = true;
            //System.out.println("First Word\""+mComposing.toString()+"\"");
        }

        //effect any injections as required
        if (mComposing.length() > 0) {
            //commitTyped(getCurrentInputConnection());
            //check the errormap for any replacements 
            if (errorMap.size() > 0) {

                //restrict the errormap to the 25% of word length cap

                int replacementstodelete = errorMap.size() - (int) Math.round(mComposing.length() * 0.25); //total replacements - those to keep
                if (replacementstodelete < 0)
                    replacementstodelete = 0;
                //allow at least one
                if (errorMap.size() == replacementstodelete)
                    replacementstodelete = errorMap.size() - 1;

                if (replacementstodelete > 0) {
                    List<Integer> keys = new ArrayList<Integer>(errorMap.keySet());

                    for (int z = 0; z < replacementstodelete; z++) {
                        Random random = new Random();
                        int listposition = random.nextInt(keys.size());
                        int randomKey = keys.get(listposition);
                        //remove this from the error map and the list
                        errorMap.remove(randomKey);
                        keys.remove(listposition);

                    }
                }

                //effect the injections
                String oldmComposing = mComposing.toString();
                Iterator it = errorMap.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry pair = (Map.Entry) it.next();
                    mComposing.replace((Integer) pair.getKey(), (Integer) pair.getKey() + 1,
                            "" + (Character) pair.getValue());
                    //it.remove(); // avoids a ConcurrentModificationException
                }
                nInjections += errorMap.size();
                currentSession.nInjections = nInjections;
                //Log.i("Injections", "Will replace "+oldmComposing+" with "+mComposing+", nInjections="+nInjections);
                errorMap.clear();
            }

            wordSeparatorKeyCode = primaryCode;
            if (captureData)
                commitTyped(ic, isWordSeparator(primaryCode));
            else {
                if (primaryCode != Keyboard.KEYCODE_DONE && primaryCode != 10) //done and go/enter
                    handleCharacter(primaryCode, keyCodes);
                else
                    sendKey(primaryCode);
                commitTyped(ic);
            }
        } else {
            sendKey(primaryCode);
        }

        updateShiftKeyState(getCurrentInputEditorInfo());

    } else if (primaryCode == Keyboard.KEYCODE_DELETE) {
        if (errorMap.get(mComposing.length() - 1) != null) {
            //Log.i("Injection", "Delete from map pos="+(mComposing.length()-1)+", char="+errorMap.get(mComposing.length()-1));
            errorMap.remove(mComposing.length() - 1);
        }

        handleBackspace();
    } else if (primaryCode == Keyboard.KEYCODE_SHIFT) {
        handleShift();
    } else if (primaryCode == Keyboard.KEYCODE_CANCEL) { //keyboard hiding button
        //override this for settings activity
        //handleClose();
        Intent intent = new Intent(this, LoggingIMESettings.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        return;
    } else if (primaryCode == LatinKeyboardView.KEYCODE_OPTIONS) {
        // Show a menu or somethin'
    } else if (primaryCode == Keyboard.KEYCODE_MODE_CHANGE && mInputView != null) {
        //Keyboard current = mInputView.getKeyboard();

        if (mInputView.currentKeyboard == KeyboardViews.SYMBOLS
                || mInputView.currentKeyboard == KeyboardViews.SYMBOLS_SHIFTED) {
            //mInputView.currentKeyboard = KeyboardViews.QWERTY_EN;
            mInputView.currentKeyboard = lastKeyboardView;
        } else { //about to change to symbols
            lastKeyboardView = mInputView.currentKeyboard; //keep track of where we came from
            mInputView.currentKeyboard = KeyboardViews.SYMBOLS;
        }
        mInputView.switchKeyboard();
        if (mInputView.currentKeyboard == KeyboardViews.SYMBOLS) {
            mInputView.getKeyboard().setShifted(false);
        }
    } else {
        handleCharacter(primaryCode, keyCodes);
    }
}

From source file:com.gelakinetic.mtgfam.helpers.CardDbAdapter.java

/**
 * Returns a Cursor over all words that match the given query
 * //  w  w w . j  ava  2 s . c  om
 * @param query
 *            The string to search for
 * @param columns
 *            The columns to include, if null then all are included
 * @return Cursor over all words that match, or null if none found.
 * @throws FamiliarDbException
 */
public Cursor getWordMatches(String query, String[] columns) throws FamiliarDbException {

    query = query.replace("'", "''").replace(Character.toChars(0xE6)[0], Character.toChars(0xC6)[0]).trim();
    String convert = query.toLowerCase().replace("ae", String.valueOf(Character.toChars(0xC6)[0]));

    if (query.length() < 2) {
        return null;
    }

    String sql = "SELECT * FROM (" + "SELECT " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " AS " + KEY_NAME
            + ", " + DATABASE_TABLE_CARDS + "." + KEY_ID + " AS " + KEY_ID + ", " + DATABASE_TABLE_CARDS + "."
            + KEY_ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID + " FROM " + DATABASE_TABLE_CARDS
            + " JOIN " + DATABASE_TABLE_SETS + " ON " + DATABASE_TABLE_SETS + "." + KEY_CODE + " = "
            + DATABASE_TABLE_CARDS + "." + KEY_SET + " WHERE " + DATABASE_TABLE_CARDS + "." + KEY_NAME
            + " LIKE '" + query + "%'" + " OR " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " LIKE '" + convert
            + "%'" + " ORDER BY " + DATABASE_TABLE_CARDS + "." + KEY_NAME + " COLLATE UNICODE, "
            + DATABASE_TABLE_SETS + "." + KEY_DATE + " ASC " + ") GROUP BY " + KEY_NAME;
    return mDb.rawQuery(sql, null);
}