Example usage for java.lang StringBuilder appendCodePoint

List of usage examples for java.lang StringBuilder appendCodePoint

Introduction

In this page you can find the example usage for java.lang StringBuilder appendCodePoint.

Prototype

@Override
public StringBuilder appendCodePoint(int codePoint) 

Source Link

Usage

From source file:nz.ac.otago.psyanlab.common.designer.program.operand.RenameOperandDialogueFragment.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Bundle args = getArguments();/*from   w  w w.  j  av a2  s .  c  om*/
    if (args != null) {
        mOperandId = args.getLong(ARG_OPERAND_ID, -1);
    }

    if (mOperandId == -1) {
        throw new RuntimeException("Invalid operand id.");
    }

    mOperand = mCallbacks.getOperand(mOperandId);

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View view = inflater.inflate(R.layout.dialogue_rename_variable, null);
    mName = (EditText) view.findViewById(R.id.name);
    mName.setText(mOperand.getName());

    // Thanks to serwus <http://stackoverflow.com/users/1598308/serwus>,
    // who posted at <http://stackoverflow.com/a/20325852>. Modified to
    // support unicode codepoints and validating first character of input.
    InputFilter filter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                int dend) {
            boolean keepOriginal = true;
            StringBuilder sb = new StringBuilder(end - start);

            int offset = 0;
            String s = source.toString();

            while (offset < s.length()) {
                final int codePoint = s.codePointAt(offset);
                if ((offset == 0 && isAllowedAsFirst(codePoint)) || (offset > 0 && isAllowed(codePoint))) {
                    sb.appendCodePoint(codePoint);
                } else {
                    keepOriginal = false;
                }
                offset += Character.charCount(codePoint);
            }

            if (keepOriginal)
                return null;
            else {
                if (source instanceof Spanned) {
                    SpannableString sp = new SpannableString(sb);
                    TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
                    return sp;
                } else {
                    return sb;
                }
            }
        }

        private boolean isAllowed(int codePoint) {
            return Character.isLetterOrDigit(codePoint);
        }

        private boolean isAllowedAsFirst(int codePoint) {
            return Character.isLetter(codePoint);
        }
    };

    mName.setFilters(new InputFilter[] { filter });

    // Build dialogue.
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(getString(R.string.title_rename_variable, mOperand.getName())).setView(view)
            .setPositiveButton(R.string.action_rename, mPositiveListener)
            .setNegativeButton(R.string.action_cancel, mNegativeListener);

    // Create the AlertDialog object and return it
    Dialog dialog = builder.create();
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    return dialog;
}

From source file:org.kitodo.production.plugin.opac.pica.Query.java

/**
 * Query constructor. Constructs a query from a String. For the query
 * semantics, see/*w  w w.  j a  va2 s. c o m*/
 * {@link org.goobi.production.plugin.CataloguePlugin.QueryBuilder}.
 *
 * @param queryString
 *            Query string to parse
 * @throws IllegalArgumentException
 *             if the query is syntactically incomplete (i.e. unterminated
 *             String literal), contains fieldless tokens or bracket
 *             expressions
 */
Query(String queryString) {
    int state = 0;
    String operator = null;
    StringBuilder field = new StringBuilder();
    StringBuilder term = new StringBuilder(32);
    for (int index = 0; index < queryString.length(); index++) {
        int codePoint = queryString.codePointAt(index);
        switch (state) {
        case 0:
            switch (codePoint) {
            case ' ':
                continue;
            case '"':
                throw new IllegalArgumentException(FIELDLESS);
            case '(':
                throw new IllegalArgumentException(BRACKET);
            case '-':
                operator = NOT;
                break;
            default:
                field.appendCodePoint(codePoint);
            }
            state = 1;
            break;
        case 1:
            switch (codePoint) {
            case ' ':
                throw new IllegalArgumentException(FIELDLESS);
            case ':':
                state = 2;
                break;
            default:
                field.appendCodePoint(codePoint);
            }
            break;
        case 2:
            switch (codePoint) {
            case ' ':
                continue;
            case '"':
                state = 4;
                break;
            case '(':
                throw new IllegalArgumentException(BRACKET);
            default:
                term.appendCodePoint(codePoint);
                state = 3;
            }
            break;
        case 3:
            if (codePoint == ' ') {
                if (term.length() == 0) {
                    throw new IllegalArgumentException(INCOMPLETE);
                }
                addQuery(operator, term.toString(), field.toString());
                operator = AND;
                field = new StringBuilder();
                term = new StringBuilder(32);
                state = 5;
            } else {
                term.appendCodePoint(codePoint);
            }
            break;
        case 4:
            if (codePoint == '"') {
                addQuery(operator, term.toString(), field.toString());
                operator = AND;
                field = new StringBuilder();
                term = new StringBuilder(32);
                state = 5;
            } else {
                term.appendCodePoint(codePoint);
            }
            break;
        case 5:
            switch (codePoint) {
            case ' ':
                continue;
            case '-':
                operator = NOT;
                break;
            case '|':
                operator = OR;
                break;
            default:
                field.appendCodePoint(codePoint);
            }
            state = 1;
            break;
        default:
            throw new UnreachableCodeException();
        }
    }
    if (state == 3) {
        addQuery(operator, term.toString(), field.toString());
    }
    if (state != 3 && state != 5) {
        throw new IllegalArgumentException(INCOMPLETE);
    }
}

From source file:org.sakaiproject.gradebookng.tool.model.GbGradebookData.java

private String serializeSmallGrades(final List<Score> gradeList) {
    final StringBuilder sb = new StringBuilder();

    for (final Score score : gradeList) {
        if (score == null || score.isNull()) {
            // No grade set. Use a sentinel value.
            sb.appendCodePoint(this.NULL_SENTINEL);
            continue;
        }//ww w.j  a  va2 s  .  c o m

        final double grade = score.getScore();

        if (grade < 0) {
            throw new IllegalStateException("serializeSmallGrades doesn't support negative scores");
        }

        final boolean hasFraction = ((int) grade != grade);

        if (grade < 127 && !hasFraction) {
            // single byte, no fraction
            //
            // input number like 0nnnnnnn serialized as 0nnnnnnn
            sb.appendCodePoint((int) grade & 0xFF);
        } else if (grade < 16384 && !hasFraction) {
            // two byte, no fraction
            //
            // input number like 00nnnnnn nnnnnnnn serialized as 10nnnnnn nnnnnnnn
            //
            // where leading '10' means 'two bytes, no fraction part'
            sb.appendCodePoint(((int) grade >> 8) | 0b10000000);
            sb.appendCodePoint(((int) grade & 0xFF));
        } else if (grade < 16384) {
            // three byte encoding, fraction
            //
            // input number like 00nnnnnn nnnnnnnn.25 serialized as 11nnnnnn nnnnnnnn 00011001
            //
            // where leading '11' means 'two bytes plus a fraction part',
            // and the fraction part is stored as an integer between 0-99,
            // where 50 represents 0.5, 25 represents .25, etc.

            sb.appendCodePoint(((int) grade >> 8) | 0b11000000);
            sb.appendCodePoint((int) grade & 0xFF);
            sb.appendCodePoint((int) Math.round((grade * 100) - ((int) grade * 100)));
        } else {
            throw new RuntimeException("Grade too large: " + grade);
        }
    }

    try {
        return Base64.getEncoder().encodeToString(sb.toString().getBytes("ISO-8859-1"));
    } catch (final UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:r.parser.RLexer.java

private String codePointToString(int c) {
    // TODO: this can't be the most efficient way to do this
    StringBuilder sb = new StringBuilder(1);
    sb.appendCodePoint(c);
    return sb.toString();
}

From source file:org.apache.orc.impl.mask.RedactMaskFactory.java

/**
 * Mask the given stringified numeric value excluding the unmask range.
 * Non-digit characters are passed through on the assumption they are
 * markers (eg. one of ",.ef")./* w  ww  . jav a2 s.c  o  m*/
 * @param value the original value.
 */
String maskNumericString(final String value) {
    StringBuilder result = new StringBuilder();
    final int length = value.codePointCount(0, value.length());
    for (int c = 0; c < length; ++c) {
        int cp = value.codePointAt(c);
        if (isIndexInUnmaskRange(c, length) || Character.getType(cp) != Character.DECIMAL_DIGIT_NUMBER) {
            result.appendCodePoint(cp);
        } else {
            result.appendCodePoint(DIGIT_CP_REPLACEMENT);
        }
    }
    return result.toString();
}

From source file:fr.ens.biologie.genomique.eoulsan.it.ITFactory.java

/**
 * Evaluate expression in a string.//  w w  w  .  j  ava2  s .c o  m
 * @param s string in witch expression must be replaced
 * @param allowExec allow execution of code
 * @return a string with expression evaluated
 * @throws EoulsanException if an error occurs while parsing the string or
 *           executing an expression
 */
static String evaluateExpressions(final String s, final boolean allowExec) throws EoulsanException {

    if (s == null) {
        return null;
    }

    final StringBuilder result = new StringBuilder();

    final int len = s.length();

    for (int i = 0; i < len; i++) {

        final int c0 = s.codePointAt(i);

        // Variable substitution
        if (c0 == '$' && i + 1 < len) {

            final int c1 = s.codePointAt(i + 1);
            if (c1 == '{') {

                final String expr = subStr(s, i + 2, '}');

                final String trimmedExpr = expr.trim();
                if (CONSTANTS.containsKey(trimmedExpr)) {
                    result.append(CONSTANTS.get(trimmedExpr));
                }

                i += expr.length() + 2;
                continue;
            }
        }

        // Command substitution
        if (c0 == '`' && allowExec) {
            final String expr = subStr(s, i + 1, '`');
            try {
                final String r = ProcessUtils.execToString(evaluateExpressions(expr, false));

                // remove last '\n' in the result
                if (!r.isEmpty() && r.charAt(r.length() - 1) == '\n') {
                    result.append(r.substring(0, r.length() - 1));
                } else {
                    result.append(r);
                }

            } catch (final IOException e) {
                throw new EoulsanException("Error while evaluating expression \"" + expr + "\"", e);
            }
            i += expr.length() + 1;
            continue;
        }

        result.appendCodePoint(c0);
    }

    return result.toString();
}

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

private int consumeNumericValue(int c) {
    StringBuilder buffer = new StringBuilder();
    buffer.appendCodePoint(c);

    int seendot = c == '.' ? 1 : 0;
    boolean seenexp = false;
    int last = c;
    int nd = 0;/*from w w  w.ja v a2s  .  c om*/
    int asNumeric = 0;

    /* We don't care about other than ASCII digits */
    while (isDigit(c = xxgetc()) || c == '.' || c == 'e' || c == 'E' || c == 'x' || c == 'X' || c == 'L') {
        if (c == 'L') /* must be at the end.  Won't allow 1Le3 (at present). */
            break;

        if (c == 'x' || c == 'X') {
            if (last != '0') {
                break;
            }
            buffer.appendCodePoint(c);
            while (isDigit(c = xxgetc()) || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F') || c == '.') {
                buffer.appendCodePoint(c);
                nd++;
            }
            if (nd == 0) {
                return ERROR;
            }
            if (c == 'p' || c == 'P') {
                buffer.appendCodePoint(c);
                c = xxgetc();
                if (!isDigit(c) && c != '+' && c != '-') {
                    return ERROR;
                }
                if (c == '+' || c == '-') {
                    buffer.appendCodePoint(c);
                    c = xxgetc();
                }
                for (nd = 0; isDigit(c); c = xxgetc(), nd++) {
                    buffer.appendCodePoint(c);
                }
                if (nd == 0) {
                    return ERROR;
                }
            }
            break;
        }
        if (c == 'E' || c == 'e') {
            if (seenexp) {
                break;
            }
            seenexp = true;
            seendot = seendot == 1 ? seendot : 2;
            buffer.appendCodePoint(c);
            c = xxgetc();
            if (!isDigit(c) && c != '+' && c != '-') {
                return ERROR;
            }
            if (c == '+' || c == '-') {
                buffer.appendCodePoint(c);
                c = xxgetc();
                if (!isDigit(c)) {
                    return ERROR;
                }
            }
        }
        if (c == '.') {
            if (seendot != 0) {
                break;
            }
            seendot = 1;
        }
        buffer.appendCodePoint(c);
        last = c;
    }

    /* Make certain that things are okay. */
    if (c == 'L') {
        double a = ParseUtil.parseDouble(buffer.toString());
        int b = (int) a;
        /* We are asked to create an integer via the L, so we check that the
          double and int values are the same. If not, this is a problem and we
          will not lose information and so use the numeric value.
        */
        if (a != (double) b) {
            if (parseOptions.isGenerateCode()) {
                if (seendot == 1 && !seenexp) {
                    logger.warning(String.format("integer literal %sL contains decimal; using numeric value",
                            buffer.toString()));
                } else {
                    logger.warning(String.format("non-integer value %s qualified with L; using numeric value",
                            buffer));
                }
            }
            asNumeric = 1;
            seenexp = true;
        }
    }

    if (c == 'i') {
        yylval = parseOptions.isGenerateCode() ? mkComplex(buffer.toString()) : Null.INSTANCE;
    } else if (c == 'L' && asNumeric == 0) {
        if (parseOptions.isGenerateCode() && seendot == 1 && !seenexp) {
            logger.warning(
                    String.format("integer literal %sL contains unnecessary decimal point", buffer.toString()));
        }
        yylval = parseOptions.isGenerateCode() ? new IntArrayVector(ParseUtil.parseInt(buffer.toString()))
                : Null.INSTANCE;
    } else {
        if (c != 'L') {
            xxungetc(c);
        }
        yylval = parseOptions.isGenerateCode() ? new DoubleArrayVector(ParseUtil.parseDouble(buffer.toString()))
                : Null.INSTANCE;
    }

    return NUM_CONST;
}

From source file:r.parser.RLexer.java

private int consumeNumericValue(int c) {
    StringBuilder buffer = new StringBuilder();
    buffer.appendCodePoint(c);

    int seendot = c == '.' ? 1 : 0;
    boolean seenexp = false;
    int last = c;
    int nd = 0;/*  ww w . j a  va  2  s.c  om*/
    int asNumeric = 0;

    /* We don't care about other than ASCII digits */
    while (isDigit(c = xxgetc()) || c == '.' || c == 'e' || c == 'E' || c == 'x' || c == 'X' || c == 'L') {
        if (c == 'L') /* must be at the end.  Won't allow 1Le3 (at present). */
            break;

        if (c == 'x' || c == 'X') {
            if (last != '0') {
                break;
            }
            buffer.appendCodePoint(c);
            while (isDigit(c = xxgetc()) || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F') || c == '.') {
                buffer.appendCodePoint(c);
                nd++;
            }
            if (nd == 0) {
                return ERROR;
            }
            if (c == 'p' || c == 'P') {
                buffer.appendCodePoint(c);
                c = xxgetc();
                if (!isDigit(c) && c != '+' && c != '-') {
                    return ERROR;
                }
                if (c == '+' || c == '-') {
                    buffer.appendCodePoint(c);
                    c = xxgetc();
                }
                for (nd = 0; isDigit(c); c = xxgetc(), nd++) {
                    buffer.appendCodePoint(c);
                }
                if (nd == 0) {
                    return ERROR;
                }
            }
            break;
        }
        if (c == 'E' || c == 'e') {
            if (seenexp) {
                break;
            }
            seenexp = true;
            seendot = seendot == 1 ? seendot : 2;
            buffer.appendCodePoint(c);
            c = xxgetc();
            if (!isDigit(c) && c != '+' && c != '-') {
                return ERROR;
            }
            if (c == '+' || c == '-') {
                buffer.appendCodePoint(c);
                c = xxgetc();
                if (!isDigit(c)) {
                    return ERROR;
                }
            }
        }
        if (c == '.') {
            if (seendot != 0) {
                break;
            }
            seendot = 1;
        }
        buffer.appendCodePoint(c);
        last = c;
    }

    /* Make certain that things are okay. */
    if (c == 'L') {
        double a = ParseUtil.parseDouble(buffer.toString());
        int b = (int) a;
        /* We are asked to create an integer via the L, so we check that the
          double and int values are the same. If not, this is a problem and we
          will not lose information and so use the numeric value.
        */
        if (a != (double) b) {
            if (parseOptions.isGenerateCode()) {
                if (seendot == 1 && !seenexp) {
                    logger.warning(String.format("integer literal %sL contains decimal; using numeric value",
                            buffer.toString()));
                } else {
                    logger.warning(String.format("non-integer value %s qualified with L; using numeric value",
                            buffer));
                }
            }
            asNumeric = 1;
            seenexp = true;
        }
    }

    if (c == 'i') {
        yylval = parseOptions.isGenerateCode() ? mkComplex(buffer.toString()) : R_NilValue;
    } else if (c == 'L' && asNumeric == 0) {
        if (parseOptions.isGenerateCode() && seendot == 1 && !seenexp) {
            logger.warning(
                    String.format("integer literal %sL contains unnecessary decimal point", buffer.toString()));
        }
        yylval = parseOptions.isGenerateCode() ? IntVector.parseInt(buffer.toString()) : R_NilValue;
    } else {
        if (c != 'L') {
            xxungetc(c);
        }
        yylval = parseOptions.isGenerateCode() ? DoubleVector.parseDouble(buffer.toString()) : R_NilValue;
    }

    return NUM_CONST;
}

From source file:Main.java

public static String $$insertWordBreaks(String value, int maxCharsBetweenWordBreaks) {

    StringBuilder result = new StringBuilder();

    // These variables keep track of important state while looping through the string below.
    boolean isInTag = false; // whether we're inside an HTML tag
    boolean isMaybeInEntity = false; // whether we might be inside an HTML entity
    int numCharsWithoutBreak = 0; // number of characters since the last word break

    for (int codePoint, i = 0; i < value.length(); i += Character.charCount(codePoint)) {
        codePoint = value.codePointAt(i);

        // If hit maxCharsBetweenWordBreaks, and next char is not a space, then add <wbr>.
        if (numCharsWithoutBreak >= maxCharsBetweenWordBreaks && codePoint != ' ') {
            result.append("<wbr>");
            numCharsWithoutBreak = 0;/*from w  w  w  . j a v a 2  s. co m*/
        }

        if (isInTag) {
            // If inside an HTML tag and we see '>', it's the end of the tag.
            if (codePoint == '>') {
                isInTag = false;
            }

        } else if (isMaybeInEntity) {
            switch (codePoint) {
            // If maybe inside an entity and we see ';', it's the end of the entity. The entity
            // that just ended counts as one char, so increment numCharsWithoutBreak.
            case ';':
                isMaybeInEntity = false;
                ++numCharsWithoutBreak;
                break;
            // If maybe inside an entity and we see '<', we weren't actually in an entity. But
            // now we're inside an HTML tag.
            case '<':
                isMaybeInEntity = false;
                isInTag = true;
                break;
            // If maybe inside an entity and we see ' ', we weren't actually in an entity. Just
            // correct the state and reset the numCharsWithoutBreak since we just saw a space.
            case ' ':
                isMaybeInEntity = false;
                numCharsWithoutBreak = 0;
                break;
            }

        } else { // !isInTag && !isInEntity
            switch (codePoint) {
            // When not within a tag or an entity and we see '<', we're now inside an HTML tag.
            case '<':
                isInTag = true;
                break;
            // When not within a tag or an entity and we see '&', we might be inside an entity.
            case '&':
                isMaybeInEntity = true;
                break;
            // When we see a space, reset the numCharsWithoutBreak count.
            case ' ':
                numCharsWithoutBreak = 0;
                break;
            // When we see a non-space, increment the numCharsWithoutBreak.
            default:
                ++numCharsWithoutBreak;
                break;
            }
        }

        // In addition to adding <wbr>s, we still have to add the original characters.
        result.appendCodePoint(codePoint);
    }

    return result.toString();
}

From source file:org.apache.vxquery.xmlquery.translator.XMLQueryTranslator.java

private static String unquote(String image) throws SystemException {
    StringBuilder buffer = new StringBuilder();
    char quoteChar = image.charAt(0);
    image = image.substring(1, image.length() - 1);
    Matcher m = UNQUOTER.matcher(image);
    int i = 0;//from   w  w  w .  ja  v  a2 s .com
    while (m.find()) {
        int start = m.start();
        int end = m.end();
        if (i < start) {
            buffer.append(image, i, start);
        }
        if (m.start(1) >= 0) {
            buffer.append('<');
        } else if (m.start(2) >= 0) {
            buffer.append('>');
        } else if (m.start(3) >= 0) {
            buffer.append('\'');
        } else if (m.start(4) >= 0) {
            buffer.append('&');
        } else if (m.start(5) >= 0) {
            buffer.append('"');
        } else if (m.start(6) >= 0) {
            buffer.append(quoteChar == '"' ? '"' : "\"\"");
        } else if (m.start(7) >= 0) {
            buffer.append(quoteChar == '\'' ? '\'' : "''");
        } else if (m.start(8) >= 0) {
            try {
                buffer.appendCodePoint(Integer.parseInt(image.substring(start + 2, end - 1)));
            } catch (NumberFormatException e) {
                throw new SystemException(ErrorCode.XQST0090);
            }
        } else if (m.start(9) >= 0) {
            try {
                buffer.appendCodePoint(Integer.parseInt(image.substring(start + 3, end - 1), 16));
            } catch (NumberFormatException e) {
                throw new SystemException(ErrorCode.XQST0090);
            }
        }
        i = m.end();
    }
    if (i < image.length()) {
        buffer.append(image, i, image.length());
    }
    return buffer.toString();
}