Example usage for java.lang StringBuffer charAt

List of usage examples for java.lang StringBuffer charAt

Introduction

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

Prototype

@Override
public synchronized char charAt(int index) 

Source Link

Usage

From source file:org.apache.fop.hyphenation.HyphenationTree.java

/**
 * Get values./*  w w w.  j  a  va 2s . com*/
 * @param k an integer
 * @return a byte array
 */
protected byte[] getValues(int k) {
    StringBuffer buf = new StringBuffer();
    byte v = vspace.get(k++);
    while (v != 0) {
        char c = (char) ((v >>> 4) - 1);
        buf.append(c);
        c = (char) (v & 0x0f);
        if (c == 0) {
            break;
        }
        c = (char) (c - 1);
        buf.append(c);
        v = vspace.get(k++);
    }
    byte[] res = new byte[buf.length()];
    for (int i = 0; i < res.length; i++) {
        res[i] = (byte) buf.charAt(i);
    }
    return res;
}

From source file:org.jivesoftware.community.util.StringUtils.java

public static long decodeAlphaNumeric(String encoded) {
    if (encoded.equals("0"))
        return 0L;
    StringBuffer buff = (new StringBuffer(encoded)).reverse();
    long result = 0L;
    for (int i = 0; i < buff.length(); i++) {
        char current = buff.charAt(i);
        long currentVal = indexes[current];
        result += currentVal * (long) Math.pow(base.length, i);
    }//from   w  w  w.  j  ava 2  s.c o  m

    if (result < 0L)
        throw new IllegalArgumentException((new StringBuilder()).append("Input string ").append(encoded)
                .append(" did not decode to a positive long value.").toString());
    else
        return result;
}

From source file:SignificantFigures.java

/**
 * Formats this number./*  w w w .j  ava 2 s  .c  o  m*/
 * If the number is less than 10^-3 or greater than or equal to 10^7,
 * or the number might have an ambiguous number of significant figures,
 * scientific notation will be used.
 * <p>
 * A string such as "NaN" or "Infinity" may be returned by this method.
 *
 * @return representation of this number.
 *
 * @since ostermillerutils 1.00.00
 */
@Override
public String toString() {
    if (digits == null)
        return original;
    StringBuffer digits = new StringBuffer(this.digits.toString());
    int length = digits.length();
    if (mantissa <= -4 || mantissa >= 7 || (mantissa >= length && digits.charAt(digits.length() - 1) == '0')
            || (isZero && mantissa != 0)) {
        // use scientific notation.
        if (length > 1) {
            digits.insert(1, '.');
        }
        if (mantissa != 0) {
            digits.append("E" + mantissa);
        }
    } else if (mantissa <= -1) {
        digits.insert(0, "0.");
        for (int i = mantissa; i < -1; i++) {
            digits.insert(2, '0');
        }
    } else if (mantissa + 1 == length) {
        if (length > 1 && digits.charAt(digits.length() - 1) == '0') {
            digits.append('.');
        }
    } else if (mantissa < length) {
        digits.insert(mantissa + 1, '.');
    } else {
        for (int i = length; i <= mantissa; i++) {
            digits.append('0');
        }
    }
    if (!sign) {
        digits.insert(0, '-');
    }
    return digits.toString();
}

From source file:org.apache.axis2.jaxws.util.BaseWSDLLocator.java

protected String normalizePath(String parentLocation, String relativeLocation) {
    if (log.isDebugEnabled()) {
        log.debug(/*from   www  .j a va  2  s.  c  o  m*/
                "normalizePath, parentLocation= " + parentLocation + " relativeLocation= " + relativeLocation);
    }
    // Get the path from the module root to the directory containing the importing WSDL file.
    // Note this path will end in a "/" and will not contain any ".." path components.
    String pathFromRoot = convertURI(parentLocation);

    // Construct the path to the location relative to the module root based on the parent location, 
    // removing any ".." or "." path components.
    StringBuffer pathToRelativeLocation = new StringBuffer(pathFromRoot);
    StringTokenizer tokenizedRelativeLocation = new StringTokenizer(relativeLocation, WSDL_PATH_SEPERATOR);
    if (log.isDebugEnabled()) {
        log.debug("pathFromRoot = " + pathFromRoot);
        log.debug("relativeLocation = " + relativeLocation);
    }
    while (tokenizedRelativeLocation.hasMoreTokens()) {
        String nextToken = tokenizedRelativeLocation.nextToken();
        if (nextToken.equals("..")) {
            // Relative parent directory, so chop off the last path component in the path to back
            // up to the parent directory.  First delete the trailing "/" from the path if there 
            // is one, then delete characters from the end of the path until we find the next "/".
            int charToDelete = pathToRelativeLocation.length() - 1;
            if (pathToRelativeLocation.charAt(charToDelete) == WSDL_PATH_SEPERATOR_CHAR
                    || pathToRelativeLocation.charAt(charToDelete) == '\\') {
                pathToRelativeLocation.deleteCharAt(charToDelete--);
            }
            while (pathToRelativeLocation.charAt(charToDelete) != WSDL_PATH_SEPERATOR_CHAR
                    && pathToRelativeLocation.charAt(charToDelete) != '\\') {
                pathToRelativeLocation.deleteCharAt(charToDelete--);
            }
        } else if (nextToken.equals(".")) {
            // Relative current directory, do not add or delete any path components
        } else {
            // Make sure the current path ends in a "/"  or "\\" then append this path component
            // This handles locations within the module and URIs
            if ((pathToRelativeLocation.indexOf(String.valueOf(WSDL_PATH_SEPERATOR_CHAR)) != -1)
                    && (pathToRelativeLocation
                            .charAt(pathToRelativeLocation.length() - 1) != WSDL_PATH_SEPERATOR_CHAR)) {
                pathToRelativeLocation.append(WSDL_PATH_SEPERATOR_CHAR);
            }
            // This handles file based locations
            else if ((pathToRelativeLocation.indexOf("\\") != -1)
                    && (pathToRelativeLocation.charAt(pathToRelativeLocation.length() - 1) != '\\')) {
                pathToRelativeLocation.append('\\');
            }
            pathToRelativeLocation.append(nextToken);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Built path = " + pathToRelativeLocation.toString());
    }
    return pathToRelativeLocation.toString();
}

From source file:com.example.phonetic.Nysiis.java

/**
 * Retrieves the NYSIIS code for a given String object.
 *
 * @param str String to encode using the NYSIIS algorithm
 * @return A NYSIIS code for the String supplied
 *///from   w ww .  j a  va2s  .com
public String nysiis(String str) {
    if (str == null) {
        return null;
    }

    // Use the same clean rules as Soundex
    str = clean(str);

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

    // Translate first characters of name:
    // MAC -> MCC, KN -> NN, K -> C, PH | PF -> FF, SCH -> SSS
    str = PAT_MAC.matcher(str).replaceFirst("MCC");
    str = PAT_KN.matcher(str).replaceFirst("NN");
    str = PAT_K.matcher(str).replaceFirst("C");
    str = PAT_PH_PF.matcher(str).replaceFirst("FF");
    str = PAT_SCH.matcher(str).replaceFirst("SSS");

    // Translate last characters of name:
    // EE -> Y, IE -> Y, DT | RT | RD | NT | ND -> D
    str = PAT_EE_IE.matcher(str).replaceFirst("Y");
    str = PAT_DT_ETC.matcher(str).replaceFirst("D");

    // First character of key = first character of name.
    StringBuffer key = new StringBuffer(str.length());
    key.append(str.charAt(0));

    // Transcode remaining characters, incrementing by one character each time
    final char[] chars = str.toCharArray();
    final int len = chars.length;

    for (int i = 1; i < len; i++) {
        final char next = i < len - 1 ? chars[i + 1] : SPACE;
        final char aNext = i < len - 2 ? chars[i + 2] : SPACE;
        final char[] transcoded = transcodeRemaining(chars[i - 1], chars[i], next, aNext);
        System.arraycopy(transcoded, 0, chars, i, transcoded.length);

        // only append the current char to the key if it is different from the last one
        if (chars[i] != chars[i - 1]) {
            key.append(chars[i]);
        }
    }

    if (key.length() > 1) {
        char lastChar = key.charAt(key.length() - 1);

        // If last character is S, remove it.
        if (lastChar == 'S') {
            key.deleteCharAt(key.length() - 1);
            lastChar = key.charAt(key.length() - 1);
        }

        if (key.length() > 2) {
            final char last2Char = key.charAt(key.length() - 2);
            // If last characters are AY, replace with Y.
            if (last2Char == 'A' && lastChar == 'Y') {
                key.deleteCharAt(key.length() - 2);
            }
        }

        // If last character is A, remove it.
        if (lastChar == 'A') {
            key.deleteCharAt(key.length() - 1);
        }
    }

    final String string = key.toString();
    return this.isStrict() ? string.substring(0, Math.min(TRUE_LENGTH, string.length())) : string;
}

From source file:org.apache.jasper.JspCompilationContext.java

private static final String canonicalURI(String s) {
    if (s == null)
        return null;
    StringBuffer result = new StringBuffer();
    final int len = s.length();
    int pos = 0;//from w w w.  ja va  2s.  c  o m
    while (pos < len) {
        char c = s.charAt(pos);
        if (isPathSeparator(c)) {
            /*
             * multiple path separators.
             * 'foo///bar' -> 'foo/bar'
             */
            while (pos + 1 < len && isPathSeparator(s.charAt(pos + 1))) {
                ++pos;
            }

            if (pos + 1 < len && s.charAt(pos + 1) == '.') {
                /*
                 * a single dot at the end of the path - we are done.
                 */
                if (pos + 2 >= len)
                    break;

                switch (s.charAt(pos + 2)) {
                /*
                * self directory in path
                * foo/./bar -> foo/bar
                */
                case '/':
                case '\\':
                    pos += 2;
                    continue;

                /*
                * two dots in a path: go back one hierarchy.
                * foo/bar/../baz -> foo/baz
                */
                case '.':
                    // only if we have exactly _two_ dots.
                    if (pos + 3 < len && isPathSeparator(s.charAt(pos + 3))) {
                        pos += 3;
                        int separatorPos = result.length() - 1;
                        while (separatorPos >= 0 && !isPathSeparator(result.charAt(separatorPos))) {
                            --separatorPos;
                        }
                        if (separatorPos >= 0)
                            result.setLength(separatorPos);
                        continue;
                    }
                }
            }
        }
        result.append(c);
        ++pos;
    }
    return result.toString();
}

From source file:org.apache.james.mime4j.MimeStreamParser.java

/**
 * Parses a header./*from w  w w . j a v  a 2s. c o  m*/
 * 
 * @param is the stream to parse.
 * @return a <code>BodyDescriptor</code> describing the body following 
 *         the header.
 */
private BodyDescriptor parseHeader(InputStream is) throws IOException {
    BodyDescriptor bd = new BodyDescriptor(
            bodyDescriptors.isEmpty() ? null : (BodyDescriptor) bodyDescriptors.getFirst());

    handler.startHeader();

    int lineNumber = rootStream.getLineNumber();

    StringBuffer sb = new StringBuffer();
    int curr = 0;
    int prev = 0;
    while ((curr = is.read()) != -1) {
        if (curr == '\n' && (prev == '\n' || prev == 0)) {
            /*
             * [\r]\n[\r]\n or an immediate \r\n have been seen.
             */
            sb.deleteCharAt(sb.length() - 1);
            break;
        }
        sb.append((char) curr);
        prev = curr == '\r' ? prev : curr;
    }

    if (curr == -1 && log.isWarnEnabled()) {
        log.warn("Line " + rootStream.getLineNumber() + ": Unexpected end of headers detected. "
                + "Boundary detected in header or EOF reached.");
    }

    int start = 0;
    int pos = 0;
    int startLineNumber = lineNumber;
    while (pos < sb.length()) {
        while (pos < sb.length() && sb.charAt(pos) != '\r') {
            pos++;
        }
        if (pos < sb.length() - 1 && sb.charAt(pos + 1) != '\n') {
            pos++;
            continue;
        }

        if (pos >= sb.length() - 2 || fieldChars.get(sb.charAt(pos + 2))) {

            /*
             * field should be the complete field data excluding the 
             * trailing \r\n.
             */
            String field = sb.substring(start, pos);
            start = pos + 2;

            /*
             * Check for a valid field.
             */
            int index = field.indexOf(':');
            boolean valid = false;
            if (index != -1 && fieldChars.get(field.charAt(0))) {
                valid = true;
                String fieldName = field.substring(0, index).trim();
                for (int i = 0; i < fieldName.length(); i++) {
                    if (!fieldChars.get(fieldName.charAt(i))) {
                        valid = false;
                        break;
                    }
                }

                if (valid) {
                    handler.field(field);
                    bd.addField(fieldName, field.substring(index + 1));
                }
            }

            if (!valid && log.isWarnEnabled()) {
                log.warn("Line " + startLineNumber + ": Ignoring invalid field: '" + field.trim() + "'");
            }

            startLineNumber = lineNumber;
        }

        pos += 2;
        lineNumber++;
    }

    handler.endHeader();

    return bd;
}

From source file:it.eng.spagobi.jpivotaddins.crossnavigation.SpagoBICrossNavigationConfig.java

private String getCrossNavigationUrl(Target target, Cell cell, MondrianModel model) {
    logger.debug("IN");
    StringBuffer buffer = new StringBuffer("parent.execCrossNavigation(window.name, '"
            + StringEscapeUtils.escapeJavaScript(target.documentLabel) + "', '");
    String query = model.getCurrentMdx();
    Connection monConnection = model.getConnection();
    Query monQuery = monConnection.parseQuery(query);
    Cube cube = monQuery.getCube();// w  w  w.  j av  a 2 s.c om

    List<TargetParameter> parameters = target.parameters;
    if (!parameters.isEmpty()) {
        for (int i = 0; i < parameters.size(); i++) {
            TargetParameter aParameter = parameters.get(i);
            String parameterName = aParameter.name;
            String parameterValue = getParameterValue(aParameter, cube, cell);
            if (parameterValue != null) {
                buffer.append(StringEscapeUtils.escapeJavaScript(parameterName + "=" + parameterValue + "&"));
            }
        }
    }

    if (buffer.charAt(buffer.length() - 1) == '&') {
        buffer.deleteCharAt(buffer.length() - 1);
    }
    if (target.customizedView != null) {
        buffer.append("', '" + StringEscapeUtils.escapeJavaScript(target.customizedView) + "'");
    } else {
        buffer.append("', ''");
    }

    if (target.titleCross != null && target.targetCross != null && target.targetCross.equalsIgnoreCase("tab")) {
        buffer.append(",'" + target.titleCross + "','tab'");
    } else if (target.titleCross != null) {
        buffer.append(",'" + target.titleCross + "'");
    }

    buffer.append(");");
    String toReturn = buffer.toString();
    logger.debug("OUT: returning [" + toReturn + "]");
    return toReturn;
}

From source file:org.jivesoftware.community.util.StringUtils.java

public static String wordWrap(String input, int width, Locale locale) {
    if (input == null)
        return "";
    if (width < 5)
        return input;
    if (width >= input.length())
        return input;
    if (locale == null)
        locale = JiveGlobals.getLocale();
    StringBuffer buf = new StringBuffer(input);
    boolean endOfLine = false;
    int lineStart = 0;
    for (int i = 0; i < buf.length(); i++) {
        if (buf.charAt(i) == '\n') {
            lineStart = i + 1;//from www .j av  a 2 s  .c o m
            endOfLine = true;
        }
        if (i <= (lineStart + width) - 1)
            continue;
        if (!endOfLine) {
            int limit = i - lineStart - 1;
            BreakIterator breaks = BreakIterator.getLineInstance(locale);
            breaks.setText(buf.substring(lineStart, i));
            int end = breaks.last();
            if (end == limit + 1 && !Character.isWhitespace(buf.charAt(lineStart + end)))
                end = breaks.preceding(end - 1);
            if (end != -1 && end == limit + 1) {
                buf.replace(lineStart + end, lineStart + end + 1, "\n");
                lineStart += end;
                continue;
            }
            if (end != -1 && end != 0) {
                buf.insert(lineStart + end, '\n');
                lineStart = lineStart + end + 1;
            } else {
                buf.insert(i, '\n');
                lineStart = i + 1;
            }
        } else {
            buf.insert(i, '\n');
            lineStart = i + 1;
            endOfLine = false;
        }
    }

    return buf.toString();
}

From source file:org.apache.struts2.jasper.JspCompilationContext.java

protected static final String canonicalURI(String s) {
    if (s == null)
        return null;
    StringBuffer result = new StringBuffer();
    final int len = s.length();
    int pos = 0;/*from  w  w  w  .java  2  s .  c o m*/
    while (pos < len) {
        char c = s.charAt(pos);
        if (isPathSeparator(c)) {
            /*
             * multiple path separators.
             * 'foo///bar' -> 'foo/bar'
             */
            while (pos + 1 < len && isPathSeparator(s.charAt(pos + 1))) {
                ++pos;
            }

            if (pos + 1 < len && s.charAt(pos + 1) == '.') {
                /*
                 * a single dot at the end of the path - we are done.
                 */
                if (pos + 2 >= len)
                    break;

                switch (s.charAt(pos + 2)) {
                /*
                * self directory in path
                * foo/./bar -> foo/bar
                */
                case '/':
                case '\\':
                    pos += 2;
                    continue;

                /*
                * two dots in a path: go back one hierarchy.
                * foo/bar/../baz -> foo/baz
                */
                case '.':
                    // only if we have exactly _two_ dots.
                    if (pos + 3 < len && isPathSeparator(s.charAt(pos + 3))) {
                        pos += 3;
                        int separatorPos = result.length() - 1;
                        while (separatorPos >= 0 && !isPathSeparator(result.charAt(separatorPos))) {
                            --separatorPos;
                        }
                        if (separatorPos >= 0)
                            result.setLength(separatorPos);
                        continue;
                    }
                }
            }
        }
        result.append(c);
        ++pos;
    }
    return result.toString();
}