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:CssCompressor.java

public void compress(Writer out, int linebreakpos) throws IOException {

    Pattern p;/*from  w ww  .j a va2 s  .c o m*/
    Matcher m;
    String css;
    StringBuffer sb;
    int startIndex, endIndex;

    // Remove all comment blocks...
    startIndex = 0;
    boolean iemac = false;
    boolean preserve = false;
    sb = new StringBuffer(srcsb.toString());
    while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
        preserve = sb.length() > startIndex + 2 && sb.charAt(startIndex + 2) == '!';
        endIndex = sb.indexOf("*/", startIndex + 2);
        if (endIndex < 0) {
            if (!preserve) {
                sb.delete(startIndex, sb.length());
            }
        } else if (endIndex >= startIndex + 2) {
            if (sb.charAt(endIndex - 1) == '\\') {
                // Looks like a comment to hide rules from IE Mac.
                // Leave this comment, and the following one, alone...
                startIndex = endIndex + 2;
                iemac = true;
            } else if (iemac) {
                startIndex = endIndex + 2;
                iemac = false;
            } else if (!preserve) {
                sb.delete(startIndex, endIndex + 2);
            } else {
                startIndex = endIndex + 2;
            }
        }
    }

    css = sb.toString();

    // Normalize all whitespace strings to single spaces. Easier to work
    // with that way.
    css = css.replaceAll("\\s+", " ");

    // Make a pseudo class for the Box Model Hack
    css = css.replaceAll("\"\\\\\"}\\\\\"\"", "___PSEUDOCLASSBMH___");

    // ---------where zk modify it
    sb = new StringBuffer();
    p = Pattern.compile("\\$\\{([^\\}]+)\\}");
    Matcher m1 = p.matcher(css);
    while (m1.find()) {
        String s1 = m1.group();
        s1 = s1.replaceAll("\\$\\{", "__EL__");
        s1 = s1.replaceAll(":", "__ELSP__");
        s1 = s1.replaceAll("\\}", "__ELEND__");

        m1.appendReplacement(sb, s1);
    }
    m1.appendTail(sb);
    css = sb.toString();

    // ---------where zk modify it----end

    // Remove the spaces before the things that should not have spaces
    // before them.
    // But, be careful not to turn "p :link {...}" into "p:link{...}"
    // Swap out any pseudo-class colons with the token, and then swap back.
    sb = new StringBuffer();
    p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
    m = p.matcher(css);
    while (m.find()) {
        String s = m.group();
        s = s.replaceAll(":", "___PSEUDOCLASSCOLON___");
        m.appendReplacement(sb, s);
    }
    m.appendTail(sb);
    css = sb.toString();
    css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
    css = css.replaceAll("___PSEUDOCLASSCOLON___", ":");

    // Remove the spaces after the things that should not have spaces after
    // them.
    css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");

    // Add the semicolon where it's missing.
    css = css.replaceAll("([^;\\}])}", "$1;}");

    // Replace 0(px,em,%) with 0.
    css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");

    // Replace 0 0 0 0; with 0.
    css = css.replaceAll(":0 0 0 0;", ":0;");
    css = css.replaceAll(":0 0 0;", ":0;");
    css = css.replaceAll(":0 0;", ":0;");
    // Replace background-position:0; with background-position:0 0;
    css = css.replaceAll("background-position:0;", "background-position:0 0;");

    // Replace 0.6 to .6, but only when preceded by : or a white-space
    css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");

    // Shorten colors from rgb(51,102,153) to #336699
    // This makes it more likely that it'll get further compressed in the
    // next step.
    p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
    m = p.matcher(css);
    sb = new StringBuffer();
    while (m.find()) {
        String[] rgbcolors = m.group(1).split(",");
        StringBuffer hexcolor = new StringBuffer("#");
        for (int i = 0; i < rgbcolors.length; i++) {
            int val = Integer.parseInt(rgbcolors[i]);
            if (val < 16) {
                hexcolor.append("0");
            }
            hexcolor.append(Integer.toHexString(val));
        }
        m.appendReplacement(sb, hexcolor.toString());
    }
    m.appendTail(sb);
    css = sb.toString();

    // Shorten colors from #AABBCC to #ABC. Note that we want to make sure
    // the color is not preceded by either ", " or =. Indeed, the property
    // filter: chroma(color="#FFFFFF");
    // would become
    // filter: chroma(color="#FFF");
    // which makes the filter break in IE.
    p = Pattern.compile(
            "([^\"'=\\s])(\\s*)#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
    m = p.matcher(css);
    sb = new StringBuffer();
    while (m.find()) {
        // Test for AABBCC pattern
        if (m.group(3).equalsIgnoreCase(m.group(4)) && m.group(5).equalsIgnoreCase(m.group(6))
                && m.group(7).equalsIgnoreCase(m.group(8))) {
            m.appendReplacement(sb, m.group(1) + m.group(2) + "#" + m.group(3) + m.group(5) + m.group(7));
        } else {
            m.appendReplacement(sb, m.group());
        }
    }
    m.appendTail(sb);
    css = sb.toString();

    // Remove empty rules.
    css = css.replaceAll("[^\\}]+\\{;\\}", "");

    if (linebreakpos >= 0) {
        // Some source control tools don't like it when files containing
        // lines longer
        // than, say 8000 characters, are checked in. The linebreak option
        // is used in
        // that case to split long lines after a specific column.
        int i = 0;
        int linestartpos = 0;
        sb = new StringBuffer(css);
        while (i < sb.length()) {
            char c = sb.charAt(i++);
            if (c == '}' && i - linestartpos > linebreakpos) {
                sb.insert(i, '\n');
                linestartpos = i;
            }
        }

        css = sb.toString();
    }

    // Replace the pseudo class for the Box Model Hack
    css = css.replaceAll("___PSEUDOCLASSBMH___", "\"\\\\\"}\\\\\"\"");

    // Replace multiple semi-colons in a row by a single one
    // See SF bug #1980989
    css = css.replaceAll(";;+", ";");

    // ---------where zk modify it
    css = css.replaceAll("__EL__", "\\$\\{");
    css = css.replaceAll("__ELSP__", ":");
    css = css.replaceAll("__ELEND__", "\\}");

    // ---------where zk modify it----end

    // Trim the final string (for any leading or trailing white spaces)
    css = css.trim();

    // Write the output...
    out.write(css);
}

From source file:de.escidoc.sb.common.lucene.analyzer.EscidocJapaneseAnalyzer.java

/**
 * Constructs a token stream with JapaneseAnalyzer or WhitespaceTokenizer
 * depending if text is japanese or not.
 * //from   ww w  . j  a  v a 2 s  .co  m
 * @param fieldName
 *            name of the Lucene Indexfield.
 * @param reader
 *            reader with field-value
 * 
 * @return TokenStream tokenStream
 * 
 * @sb
 */
@Override
public TokenStream tokenStream(final String fieldName, final Reader reader) {
    if (log.isDebugEnabled()) {
        log.debug("tokenizing with EscidocJapaneseAnalyzer");
    }
    //checkJapanese ///////////////////////////////////////////////////////
    boolean isJapanese = false;
    TokenStream whitespaceTokens = new WhitespaceTokenizer(Constants.LUCENE_VERSION, reader);
    Reader reader1 = null;
    try {
        StringBuffer tokenBuffer = new StringBuffer("");
        CharTermAttribute termAtt = whitespaceTokens.addAttribute(CharTermAttribute.class);
        whitespaceTokens.reset();
        while (whitespaceTokens.incrementToken()) {
            if (tokenBuffer.length() > 0) {
                tokenBuffer.append(" ");
            }
            tokenBuffer.append(termAtt.toString());
        }
        for (int i = 0; i < tokenBuffer.length(); i++) {
            int hexInt = Integer.parseInt(charToHex(tokenBuffer.charAt(i)), 16);
            if (hexInt > 12287 && hexInt < 13328) {
                isJapanese = true;
                break;
            }
        }
        reader1 = new StringReader(tokenBuffer.toString());
    } catch (Exception e) {
        log.error(e);
    }
    ///////////////////////////////////////////////////////////////////////

    //No Japanese, so return whitespace-tokens
    if (!isJapanese) {
        TokenStream result = new XmlWhitespaceTokenizer(reader1);
        result = new JunkFilter(result);
        result = new LowerCaseFilter(Constants.LUCENE_VERSION, result);
        return result;
    }

    //Get Japanese Tokens
    JapaneseAnalyzer analyzer = new JapaneseAnalyzer(Constants.LUCENE_VERSION);
    TokenStream japaneseTokens = analyzer.tokenStream("", reader1);
    if (analyzer != null) {
        try {
            analyzer.close();
        } catch (Exception e) {
        }
    }
    return japaneseTokens;
}

From source file:com.digitalpebble.storm.crawler.protocol.http.HttpResponse.java

private void processHeaderLine(StringBuffer line) throws HttpException {

    int colonIndex = line.indexOf(":"); // key is up to colon
    if (colonIndex == -1) {
        int i;//from www . j ava  2  s .  co m
        for (i = 0; i < line.length(); i++)
            if (!Character.isWhitespace(line.charAt(i)))
                break;
        if (i == line.length())
            return;
        throw new HttpException("No colon in header:" + line);
    }
    String key = line.substring(0, colonIndex);

    int valueStart = colonIndex + 1; // skip whitespace
    while (valueStart < line.length()) {
        int c = line.charAt(valueStart);
        if (c != ' ' && c != '\t')
            break;
        valueStart++;
    }
    String value = line.substring(valueStart);
    headers.addValue(key.toLowerCase(Locale.ROOT), value);
}

From source file:com.netcrest.pado.tools.pado.command.put.java

/**
 * Returns the index of the enclosed parenthesis, i.e., ')'.
 * /*from  w ww .j  a  va2 s  .c  om*/
 * @param buffer
 * @param startIndex
 * @return
 */
private int getEnclosingParenthesis(StringBuffer buffer, int startIndex) {
    int enclosedIndex = -1;
    int parenCount = 0;
    boolean inQuote = false;
    // to_date('04/09/2009', 'MM/dd/yyyy')
    for (int i = startIndex; i < buffer.length(); i++) {
        char c = buffer.charAt(i);
        if (c == '(') {
            if (inQuote == false) {
                parenCount++;
            }
        } else if (c == ')') {
            if (inQuote == false) {
                parenCount--;
            }
            if (parenCount == 0) {
                enclosedIndex = i;
                break;
            }
        } else if (c == '\'') {
            inQuote = !inQuote;
        }
    }
    return enclosedIndex;
}

From source file:net.sbbi.upnp.messages.ActionMessage.java

private String getResponseBody(InputStream in) throws IOException {
    byte[] buffer = new byte[256];
    int readen = 0;
    StringBuffer content = new StringBuffer(256);
    while ((readen = in.read(buffer)) != -1) {
        content.append(new String(buffer, 0, readen));
    }/*from  w ww  .j  a  v a 2s.c om*/
    // some devices add \0 chars at XML message end
    // which causes XML parsing errors...
    int len = content.length();
    while (content.charAt(len - 1) == '\0') {
        len--;
        content.setLength(len);
    }
    return content.toString().trim();
}

From source file:com.avricot.prediction.utils.Steemer.java

/**
 * Turns u and i preceded AND followed by a vowel to UpperCase<br>
 * Turns y preceded OR followed by a vowel to UpperCase<br>
 * Turns u preceded by q to UpperCase<br>
  *//from   w w  w  .  j  a  va 2 s  .co  m
  * @param buffer java.util.StringBuffer - the buffer to treat
  * @return java.util.StringBuffer - the treated buffer
  */
 private StringBuffer treatVowels(StringBuffer buffer) {
     for (int c = 0; c < buffer.length(); c++) {
         char ch = buffer.charAt(c);

         if (c == 0) // first char
         {
             if (buffer.length() > 1) {
                 if (ch == 'y' && isVowel(buffer.charAt(c + 1)))
                     buffer.setCharAt(c, 'Y');
             }
         } else if (c == buffer.length() - 1) // last char
         {
             if (ch == 'u' && buffer.charAt(c - 1) == 'q')
                 buffer.setCharAt(c, 'U');
             if (ch == 'y' && isVowel(buffer.charAt(c - 1)))
                 buffer.setCharAt(c, 'Y');
         } else // other cases
         {
             if (ch == 'u') {
                 if (buffer.charAt(c - 1) == 'q')
                     buffer.setCharAt(c, 'U');
                 else if (isVowel(buffer.charAt(c - 1)) && isVowel(buffer.charAt(c + 1)))
                     buffer.setCharAt(c, 'U');
             }
             if (ch == 'i') {
                 if (isVowel(buffer.charAt(c - 1)) && isVowel(buffer.charAt(c + 1)))
                     buffer.setCharAt(c, 'I');
             }
             if (ch == 'y') {
                 if (isVowel(buffer.charAt(c - 1)) || isVowel(buffer.charAt(c + 1)))
                     buffer.setCharAt(c, 'Y');
             }
         }
     }

     return buffer;
 }

From source file:com.avricot.prediction.utils.Steemer.java

/**
  * Retrieve the "RV zone" from a buffer an return the corresponding string<br>
  * "If the word begins with two vowels, RV is the region after the third letter,
  * otherwise the region after the first vowel not at the beginning of the word,
  * or the end of the word if these positions cannot be found."<br>
  * @param buffer java.lang.StringBuffer - the in buffer
  * @return java.lang.String - the resulting string
  *//*from   w w  w .j av  a  2  s  . c om*/
 private String retrieveRV(StringBuffer buffer) {
     int len = buffer.length();
     if (buffer.length() > 3) {
         if (isVowel(buffer.charAt(0)) && isVowel(buffer.charAt(1))) {
             return buffer.substring(3, len);
         } else {
             int pos = 0;
             for (int c = 1; c < len; c++) {
                 if (isVowel(buffer.charAt(c))) {
                     pos = c;
                     break;
                 }
             }
             if (pos + 1 < len)
                 return buffer.substring(pos + 1, len);
             else
                 return null;
         }
     } else
         return null;
 }

From source file:org.eclipse.lyo.oslc.am.resource.ResourceService.java

private String filterCharacters(String str) {
    if (str == null || str.length() == 0)
        return "";
    StringBuffer inBuf = new StringBuffer(str);
    StringBuffer outBuf = new StringBuffer();
    int len = inBuf.length();
    for (int i = 0; i < len; i++) {
        char ch = inBuf.charAt(i);
        if (Character.isWhitespace(ch)) {
            outBuf.append(' ');
        } else if (Character.isLetterOrDigit(ch) || ch == '\'') {
            outBuf.append(ch);/* w w w .jav  a 2 s .c om*/
        }
    }
    return outBuf.toString();
}

From source file:com.wabacus.system.dataset.select.report.value.RelationalDBReportDataSetValueProvider.java

protected String getRowGroupStatiGroupByClause(AbsListReportRowGroupSubDisplayRowBean rowGroupSubDisplayRowBean,
        Map<String, String> mRowGroupColumnValues) {
    if (rowGroupSubDisplayRowBean == null)
        return null;
    ReportBean rbean = this.getReportBean();
    String[] colsArr = rowGroupSubDisplayRowBean.getParentAndMyOwnRowGroupColumnsArray(rbean);
    StringBuffer groupbyBuf = new StringBuffer();
    for (int i = 0; i < colsArr.length; i++) {
        groupbyBuf.append(colsArr[i]).append(",");
    }/*from www .j  a v  a 2s. c  o m*/
    if (groupbyBuf.charAt(groupbyBuf.length() - 1) == ',') {
        groupbyBuf.deleteCharAt(groupbyBuf.length() - 1);
    }
    String realGroupByClause = " group by " + groupbyBuf.toString() + " having "
            + getStatiRowGroupConditionExpression(rowGroupSubDisplayRowBean);
    String colvalTmp;
    for (int i = 0; i < colsArr.length; i++) {
        colvalTmp = mRowGroupColumnValues.get(colsArr[i]);
        if (colvalTmp == null)
            colvalTmp = "";
        realGroupByClause = Tools.replaceAll(realGroupByClause, "#" + colsArr[i] + "#", colvalTmp);
    }
    return realGroupByClause;
}

From source file:net.sourceforge.eclipsetrader.opentick.Feed.java

public void snapshot() {
    SimpleDateFormat usDateTimeParser = new SimpleDateFormat("MM/dd/yyyy h:mma");
    SimpleDateFormat usDateParser = new SimpleDateFormat("MM/dd/yyyy");
    SimpleDateFormat usTimeParser = new SimpleDateFormat("h:mma");
    NumberFormat numberFormat = NumberFormat.getInstance(Locale.US);

    // Builds the url for quotes download
    String host = "quote.yahoo.com";
    StringBuffer url = new StringBuffer("http://" + host + "/download/javasoft.beans?symbols=");
    for (Iterator iter = subscribedSecurities.iterator(); iter.hasNext();) {
        Security security = (Security) iter.next();
        url = url.append(security.getCode() + "+");
    }//from  ww  w.j a v  a2s. c om
    if (url.charAt(url.length() - 1) == '+')
        url.deleteCharAt(url.length() - 1);
    url.append("&format=sl1d1t1c1ohgvbap");

    // Read the last prices
    String line = "";
    try {
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        BundleContext context = OpenTickPlugin.getDefault().getBundle().getBundleContext();
        ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
        if (reference != null) {
            IProxyService proxy = (IProxyService) context.getService(reference);
            IProxyData data = proxy.getProxyDataForHost(host, IProxyData.HTTP_PROXY_TYPE);
            if (data != null) {
                if (data.getHost() != null)
                    client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                if (data.isRequiresAuthentication())
                    client.getState().setProxyCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
            }
        }

        HttpMethod method = new GetMethod(url.toString());
        method.setFollowRedirects(true);
        client.executeMethod(method);

        BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        while ((line = in.readLine()) != null) {
            String[] item = line.split(",");
            if (line.indexOf(";") != -1)
                item = line.split(";");

            Double open = null, high = null, low = null, close = null;
            Quote quote = new Quote();

            // 2 = Date
            // 3 = Time
            try {
                GregorianCalendar c = new GregorianCalendar(TimeZone.getTimeZone("EST"), Locale.US);
                usDateTimeParser.setTimeZone(c.getTimeZone());
                usDateParser.setTimeZone(c.getTimeZone());
                usTimeParser.setTimeZone(c.getTimeZone());

                String date = stripQuotes(item[2]);
                if (date.indexOf("N/A") != -1)
                    date = usDateParser.format(Calendar.getInstance().getTime());
                String time = stripQuotes(item[3]);
                if (time.indexOf("N/A") != -1)
                    time = usTimeParser.format(Calendar.getInstance().getTime());
                c.setTime(usDateTimeParser.parse(date + " " + time));
                c.setTimeZone(TimeZone.getDefault());
                quote.setDate(c.getTime());
            } catch (Exception e) {
                System.out.println(e.getMessage() + ": " + line);
            }
            // 1 = Last price or N/A
            if (item[1].equalsIgnoreCase("N/A") == false)
                quote.setLast(numberFormat.parse(item[1]).doubleValue());
            // 4 = Change
            // 5 = Open
            if (item[5].equalsIgnoreCase("N/A") == false)
                open = new Double(numberFormat.parse(item[5]).doubleValue());
            // 6 = Maximum
            if (item[6].equalsIgnoreCase("N/A") == false)
                high = new Double(numberFormat.parse(item[6]).doubleValue());
            // 7 = Minimum
            if (item[7].equalsIgnoreCase("N/A") == false)
                low = new Double(numberFormat.parse(item[7]).doubleValue());
            // 8 = Volume
            if (item[8].equalsIgnoreCase("N/A") == false)
                quote.setVolume(numberFormat.parse(item[8]).intValue());
            // 9 = Bid Price
            if (item[9].equalsIgnoreCase("N/A") == false)
                quote.setBid(numberFormat.parse(item[9]).doubleValue());
            // 10 = Ask Price
            if (item[10].equalsIgnoreCase("N/A") == false)
                quote.setAsk(numberFormat.parse(item[10]).doubleValue());
            // 11 = Close Price
            if (item[11].equalsIgnoreCase("N/A") == false)
                close = new Double(numberFormat.parse(item[11]).doubleValue());

            // 0 = Code
            String symbol = stripQuotes(item[0]);
            for (Iterator iter = subscribedSecurities.iterator(); iter.hasNext();) {
                Security security = (Security) iter.next();
                if (symbol.equalsIgnoreCase(security.getCode()))
                    security.setQuote(quote, open, high, low, close);
            }
        }
        in.close();
    } catch (Exception e) {
        System.out.println(e.getMessage() + ": " + line);
        e.printStackTrace();
    }
}