Example usage for java.lang StringBuffer length

List of usage examples for java.lang StringBuffer length

Introduction

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

Prototype

@Override
    public synchronized int length() 

Source Link

Usage

From source file:Main.java

public static String normalize(final String s) {
    if (s == null) {
        return "";
    }/* w ww .ja  v  a 2s .c o m*/

    final StringBuffer str = new StringBuffer();
    final int len = s.length();

    for (int i = 0; i < len; i++) {
        final char ch = s.charAt(i);

        switch (ch) {
        case '<': {
            str.append("&lt;");
            break;
        }
        case '>': {
            str.append("&gt;");
            break;
        }
        case '&': {
            str.append("&amp;");
            break;
        }
        case '"': {
            str.append("&quot;");
            break;
        }
        case '\n': {
            if (i > 0) {
                str.charAt(str.length() - 1);
                str.append("\n");
            } else {
                str.append("\n");
            }
            break;
        }
        default: {
            str.append(ch);
        }
        }
    }

    return (str.toString());
}

From source file:com.fiveamsolutions.nci.commons.util.HibernateHelper.java

/**
 * Break up a list of items into separate in clauses, to avoid limits imposed by databases or by Hibernate bug
 * http://opensource.atlassian.com/projects/hibernate/browse/HHH-2166.
 * @param items list of items to include in the in clause
 * @param columnName name of column to match against the list
 * @param blocks empty Map of HQL param name to param list of values to be set in the HQL query - it will be
 *               populated by the method
 * @return full HQL "in" clause, of the form: " columnName in (:block1) or ... or columnName in (:blockN)"
 *///from  w w w .  ja  v a2  s  . c  o m
public static String buildInClause(List<? extends Serializable> items, String columnName,
        Map<String, List<? extends Serializable>> blocks) {
    StringBuffer inClause = new StringBuffer();
    for (int i = 0; i < items.size(); i += MAX_IN_CLAUSE_LENGTH) {
        List<? extends Serializable> block = items.subList(i, Math.min(items.size(), i + MAX_IN_CLAUSE_LENGTH));
        String paramName = "block" + i / MAX_IN_CLAUSE_LENGTH;
        if (inClause.length() > 0) {
            inClause.append(" or");
        }
        inClause.append(" " + columnName + " in (:" + paramName + ")");
        blocks.put(paramName, block);
    }
    return inClause.toString();
}

From source file:eionet.cr.web.action.HarvestSourceActionBean.java

/**
 *
 * @param minutes// ww w  . ja  v  a2 s.  com
 * @return
 */
private static String getMinutesDisplay(int minutes) {

    int days = minutes / 1440;
    minutes = minutes - (days * 1440);
    int hours = minutes / 60;
    minutes = minutes - (hours * 60);

    StringBuffer buf = new StringBuffer();
    if (days > 0) {
        buf.append(days).append(days == 1 ? " day" : " days");
    }
    if (hours > 0) {
        buf.append(buf.length() > 0 ? ", " : "").append(hours).append(hours == 1 ? " hour" : " hours");
    }
    if (minutes > 0) {
        buf.append(buf.length() > 0 ? ", " : "").append(minutes).append(minutes == 1 ? " minute" : " minutes");
    }

    return buf.toString();
}

From source file:JavascriptUtil.java

/**
 * <p>Unescapes any JavaScript literals found in the <code>String</code>.</p>
 * <p>For example, it will turn a sequence of <code>'\'</code> and <code>'n'</code>
 * into a newline character, unless the <code>'\'</code> is preceded by another
 * <code>'\'</code>.</p>
 * @param str the <code>String</code> to unescape, may be null
 * @return A new unescaped <code>String</code>, <code>null</code> if null string input
 *//*  www  .  j  a  va2s .c  om*/
public static String unescapeJavaScript(String str) {
    if (str == null) {
        return null;
    }

    StringBuffer writer = new StringBuffer(str.length());
    int sz = str.length();
    StringBuffer unicode = new StringBuffer(4);
    boolean hadSlash = false;
    boolean inUnicode = false;

    for (int i = 0; i < sz; i++) {
        char ch = str.charAt(i);
        if (inUnicode) {
            // if in unicode, then we're reading unicode
            // values in somehow
            unicode.append(ch);
            if (unicode.length() == 4) {
                // unicode now contains the four hex digits
                // which represents our unicode character
                try {
                    int value = Integer.parseInt(unicode.toString(), 16);
                    writer.append((char) value);
                    unicode.setLength(0);
                    inUnicode = false;
                    hadSlash = false;
                } catch (NumberFormatException nfe) {
                    throw new IllegalArgumentException(
                            "Unable to parse unicode value: " + unicode + " cause: " + nfe);
                }
            }
            continue;
        }

        if (hadSlash) {
            // handle an escaped value
            hadSlash = false;
            switch (ch) {
            case '\\':
                writer.append('\\');
                break;
            case '\'':
                writer.append('\'');
                break;
            case '\"':
                writer.append('"');
                break;
            case 'r':
                writer.append('\r');
                break;
            case 'f':
                writer.append('\f');
                break;
            case 't':
                writer.append('\t');
                break;
            case 'n':
                writer.append('\n');
                break;
            case 'b':
                writer.append('\b');
                break;
            case 'u':
                // uh-oh, we're in unicode country....
                inUnicode = true;
                break;
            default:
                writer.append(ch);
                break;
            }
            continue;
        } else if (ch == '\\') {
            hadSlash = true;
            continue;
        }
        writer.append(ch);
    }

    if (hadSlash) {
        // then we're in the weird case of a \ at the end of the
        // string, let's output it anyway.
        writer.append('\\');
    }

    return writer.toString();
}

From source file:com.amazonaws.services.kinesis.aggregators.StreamAggregatorUtils.java

/**
 * Returns a statement which can be used to create an External Table in Hive
 * which wraps the Aggregator Table indicated, using the required name in
 * Hive./*from  w w  w.  j  ava 2  s  .c  om*/
 * 
 * @param dynamoClient Dynamo DB Client to use for connection to Dynamo DB.
 * @param hiveTableName The table name to generate for the Hive Table.
 * @param dynamoTable The name of the aggregator table in Dynamo DB.
 * @return A CREATE EXTERNAL TABLE statement to be used in Hive
 * @throws Exception
 */
public static String getDynamoHiveWrapper(AmazonDynamoDB dynamoClient, String hiveTableName, String dynamoTable)
        throws Exception {
    LOG.info("Generating Hive Integration Statement");

    StringBuffer sb = new StringBuffer();
    sb.append(String.format("CREATE EXTERNAL TABLE %s(", hiveTableName));

    // add the hive table spec
    List<String> tableDefinition = DynamoUtils.getDictionaryEntry(dynamoClient, dynamoTable);
    for (String s : tableDefinition) {
        sb.append(String.format("%s string,", s));
    }
    sb.replace(sb.length() - 1, sb.length(), "");

    sb.append(String.format(
            ") STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler' TBLPROPERTIES (\"dynamodb.table.name\" = \"%s\", \"dynamodb.column.mapping\" = \"",
            dynamoTable));
    for (String s : tableDefinition) {
        sb.append(String.format("%s:%s,", s, s));
    }
    sb.replace(sb.length() - 1, sb.length(), "");
    sb.append("))");

    return sb.toString();
}

From source file:com.vmware.aurora.global.Configuration.java

/**
 * Get all of values in a property as a string type.
 * //from   w w  w . j  ava2s .c  o  m
 * @param key
 *           The key of property.
 * @param defautValue
 *           The default value.
 * @return The property value.
 */
public static String getStrings(String key, String defautValue) {
    String[] values = config.getStringArray(key);
    if (values != null && values.length > 0) {
        StringBuffer buffer = new StringBuffer();
        for (String value : values) {
            buffer.append(value.trim()).append(",");
        }
        buffer.delete(buffer.length() - 1, buffer.length());
        return buffer.toString();
    } else {
        return defautValue;
    }
}

From source file:FileUtils.java

/**
 * Rename the file to temporaty name with given prefix
 * /*w  w w .j a  va 2  s. c om*/
 * @param flFileToRename - file to rename
 * @param strPrefix - prefix to use
 * @throws IOException - error message
 */
public static void renameToTemporaryName(File flFileToRename, String strPrefix) throws IOException {
    assert strPrefix != null : "Prefix cannot be null.";

    String strParent;
    StringBuffer sbBuffer = new StringBuffer();
    File flTemp;
    int iIndex = 0;

    strParent = flFileToRename.getParent();

    // Generate new name for the file in a deterministic way
    do {
        iIndex++;
        sbBuffer.delete(0, sbBuffer.length());
        if (strParent != null) {
            sbBuffer.append(strParent);
            sbBuffer.append(File.separatorChar);
        }

        sbBuffer.append(strPrefix);
        sbBuffer.append("_");
        sbBuffer.append(iIndex);
        sbBuffer.append("_");
        sbBuffer.append(flFileToRename.getName());

        flTemp = new File(sbBuffer.toString());
    } while (flTemp.exists());

    // Now we should have unique name
    if (!flFileToRename.renameTo(flTemp)) {
        throw new IOException(
                "Cannot rename " + flFileToRename.getAbsolutePath() + " to " + flTemp.getAbsolutePath());
    }
}

From source file:com.mingsoft.util.proxy.Proxy.java

/**
 * cookie// w w w  .ja v  a2s. co m
 * 
 * @param cookies
 *            ?cookie <br>
 * @return cookie
 */
public static String assemblyCookie(List cookies) {
    StringBuffer sbu = new StringBuffer();
    //log.info("cookie?");
    for (int i = 0; i < cookies.size(); i++) {
        Cookie cookie = (Cookie) cookies.get(i);
        sbu.append(cookie.getName()).append("=").append(cookie.getValue()).append(";");
        //log.info(cookie.getName() + ":" + cookie.getValue());
    }
    //log.info("?cookie?");
    if (sbu.length() > 0)
        sbu.deleteCharAt(sbu.length() - 1);
    return sbu.toString();
}

From source file:StringUtils.java

/**
 *  Makes sure that the POSTed data is conforms to certain rules.  These
 *  rules are:/*from  w ww.j  av a2 s . c o  m*/
 *  <UL>
 *  <LI>The data always ends with a newline (some browsers, such
 *      as NS4.x series, does not send a newline at the end, which makes
 *      the diffs a bit strange sometimes.
 *  <LI>The CR/LF/CRLF mess is normalized to plain CRLF.
 *  </UL>
 *
 *  The reason why we're using CRLF is that most browser already
 *  return CRLF since that is the closest thing to a HTTP standard.
 *  
 *  @param postData The data to normalize
 *  @return Normalized data
 */
public static String normalizePostData(String postData) {
    StringBuffer sb = new StringBuffer();

    for (int i = 0; i < postData.length(); i++) {
        switch (postData.charAt(i)) {
        case 0x0a: // LF, UNIX
            sb.append("\r\n");
            break;

        case 0x0d: // CR, either Mac or MSDOS
            sb.append("\r\n");
            // If it's MSDOS, skip the LF so that we don't add it again.
            if (i < postData.length() - 1 && postData.charAt(i + 1) == 0x0a) {
                i++;
            }
            break;

        default:
            sb.append(postData.charAt(i));
            break;
        }
    }

    if (sb.length() < 2 || !sb.substring(sb.length() - 2).equals("\r\n")) {
        sb.append("\r\n");
    }

    return sb.toString();
}

From source file:jdiff.API.java

/**
 * Convert all HTML tags to text by stuffing text into the HTML tag
 * to stop it being an HTML or XML tag. E.g. &quot;<code>foo</code>&quot;
 * becomes &quot;lEsS_tHaNcode>foolEsS_tHaN/code>&quot;. Replace all &lt; 
 * characters//ww  w . j a  va 2  s.  c  o m
 * with the string "lEsS_tHaN". Also replace &amp; character with the  
 * string "aNd_cHaR" to avoid text entities. Also replace &quot; 
 * character with the  
 * string "qUoTe_cHaR".
 */
public static String hideHTMLTags(String htmlText) {
    StringBuffer sb = new StringBuffer(htmlText);
    int i = 0;
    while (i < sb.length()) {
        if (sb.charAt(i) == '<') {
            sb.setCharAt(i, 'l');
            sb.insert(i + 1, "EsS_tHaN");
        } else if (sb.charAt(i) == '&') {
            sb.setCharAt(i, 'a');
            sb.insert(i + 1, "Nd_cHaR");
        } else if (sb.charAt(i) == '"') {
            sb.setCharAt(i, 'q');
            sb.insert(i + 1, "uote_cHaR");
        }
        i++;
    }
    return sb.toString();
}