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

/**
 * <p>//w  w w . j a v  a2s  .  c  om
 * 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
 */
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 chacater
                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.depas.utils.FileUtils.java

/**
 * Gets a shortened version of the a file String.
 * <pre>/*from w  w  w .j  a  v  a  2 s.co m*/
 * If the fileIn is < the maxSize, you will get fileIn back
 * Otherwise we will try to get just the file name by taking all characters
 * to the right of either a '\' or a '/'
 * If the fileName alone is > maxSize then we will take the last maxSize characters
 * Otherwise we will try split the String into parts as follows...
 * If the fileIn contains a drive letter C:\, D:\, etc
 *   we will return C:\...\file.ext or if the file name exceeds maxSize
 *   something like this C:\...aLongFileNameThatExceedsTheMax.ext
 * If the fileIn does not contain a drive letter
 * <pre>
 * @param fileIn the file in
 * @param maxSize the max size
 * @return the shortened file
 */
public static String getShortenedFile(String fileIn, int maxSize) {
    if (fileIn.length() <= maxSize) {
        return fileIn;
    }
    // Let's limit the minimum shrink size, any smaller than this isn't worth doing
    if (maxSize < 10) {
        throw new IllegalArgumentException(
                maxSize + " is too small, maxSize must be greater than or equal to 10.");
    }

    // Try to get just the file name
    String fileName = null;
    for (int i = fileIn.length() - 1; i > -1; i--) {
        char c = fileIn.charAt(i);
        if (c == '\\' || c == '/') {
            fileName = fileIn.substring(i);
            break;
        }
    }
    // Not sure what this string is, but we will use it as is
    if (fileName == null) {
        fileName = fileIn;
    }

    String elipses = "...";
    StringBuffer sb = new StringBuffer();

    // First of all file names with Drive letters are treated differently,
    // They will always start with the drive letter and then ...
    // C:\\...\file.txt
    if (fileIn.charAt(1) == ':') {
        // Add the drive
        sb.append(fileIn.substring(0, 3)); // C:\
        sb.append(elipses); // C:\...
        int total = sb.length() + fileName.length();
        if (total > maxSize) {
            sb.append(fileName.substring(total - maxSize));
        } else {
            sb.append(fileName);
        }
    }
    // Otherwise it is something else, a network drive perhaps
    else {
        // Big filename, just prepend '...' to the what ever we can of the file name
        if (fileName.length() + elipses.length() > maxSize) {
            sb.append(elipses);
            sb.append(fileName.substring(fileName.length() - (maxSize - sb.length())));
        }
        // Otherwise the file name can fit so we lets prepend the path
        else {
            sb.append(fileIn.substring(0, (maxSize - fileName.length() - elipses.length())));
            sb.append(elipses);
            sb.append(fileName);
        }
    }
    return sb.toString();

}

From source file:de.cismet.cids.custom.objectrenderer.utils.alkis.AlkisUtils.java

/**
 * DOCUMENT ME!//from   w  ww.  java 2s .c  o m
 *
 * @param   buchungsblattCode  DOCUMENT ME!
 *
 * @return  DOCUMENT ME!
 */
public static String fixBuchungslattCode(final String buchungsblattCode) {
    if (buchungsblattCode != null) {
        final StringBuffer buchungsblattCodeSB = new StringBuffer(buchungsblattCode);
        // Fix SICAD-API-strangeness...
        while (buchungsblattCodeSB.length() < 14) {
            buchungsblattCodeSB.append(" ");
        }
        return buchungsblattCodeSB.toString();
    } else {
        return "";
    }
}

From source file:cn.fql.utility.StringUtility.java

/**
 * convert a list to a string of the list's meta with a seprator
 * if the atom is a string then surround with "'".
 *
 * @param list      list to be converted
 * @param separator separator string/*from   w w w  .  j  a  v  a2s  . co  m*/
 * @return <code>String</code>
 */
public static String lst2Str(List list, String separator) {
    StringBuffer sb = new StringBuffer("");
    if (list != null && list.size() > 0) {
        for (int i = 0; i < list.size(); i++) {
            Object objItem = list.get(i);
            if (sb.length() != 0) {
                sb.append(separator);
            }
            if (objItem instanceof String) {
                String strItem = (String) objItem;
                sb.append(strItem);
            } else {
                sb.append(objItem);
            }
        }
    }
    return sb.toString();
}

From source file:edu.mayo.informatics.lexgrid.convert.directConversions.UmlsCommon.LoadRRFToDB.java

private static String[] createAndLoadTables(URI rrfLocation, boolean skipNonLexGridFiles,
        boolean recalcRootOnly, String dbServer, String dbDriver, String username, String password,
        LgMessageDirectorIF md, boolean validateMode) throws Exception {
    md.info("Connecting to RRF Files");
    BufferedReader reader = getReader(rrfLocation.resolve("MRFILES.RRF"));

    md.info("Connecting to db Files");
    Connection sqlConnection = DBUtility.connectToDatabase(dbServer, dbDriver, username, password);

    GenericSQLModifier gsm = new GenericSQLModifier(sqlConnection);

    Hashtable columnTypeMap = readMRCols(rrfLocation);
    Hashtable tableColumnMap = new Hashtable();

    List tables = new ArrayList();

    if (skipNonLexGridFiles) {
        // the only tables that I need to load
        tables.add("MRCONSO");
        tables.add("MRDOC");
        tables.add("MRREL");
        tables.add("MRSAB");
        tables.add("MRRANK");

        if (!recalcRootOnly) {
            tables.add("MRDEF");
            tables.add("MRSTY");
            tables.add("MRSAT");
            tables.add("MRHIER");
        }//from   w ww. j a  v a2 s . c  o m
    }

    md.info("Creating SQL database tables");

    PreparedStatement create = null;
    PreparedStatement drop = null;
    String line = reader.readLine();

    int mrhierHCDCol = -1;
    while (line != null) {
        String[] vals = stringToArray(line, '|');

        // for MRFILES, all I care about is the following
        String file = vals[0];
        String tableName = file.substring(0, file.indexOf('.'));

        // if file is MRHIER, remember HCD column number (base 0)
        if ("MRHIER".equalsIgnoreCase(tableName) && vals.length > 1) {
            mrhierHCDCol = Arrays.asList(vals[2].split(",")).indexOf("HCD");
        }

        if (skipNonLexGridFiles || recalcRootOnly) {
            if (!tables.contains(tableName)) {
                line = reader.readLine();
                continue;
            }
        } else {
            if (file.indexOf('/') != -1) {
                // skip files in subfolders.
                line = reader.readLine();
                continue;
            }
            if (!tables.contains(tableName))
                tables.add(tableName);
        }

        String[] columns = stringToArray(vals[2], ',');

        tableColumnMap.put(file, columns);

        StringBuffer tableCreateSQL = new StringBuffer();
        tableCreateSQL.append("CREATE TABLE {IF NOT EXISTS} ^" + tableName + "^ (");

        for (int i = 0; i < columns.length; i++) {

            tableCreateSQL.append(" ^" + columns[i] + "^ "
                    + mapUMLSType((String) columnTypeMap.get(columns[i] + "|" + file)) + " default NULL,");
        }

        // chop the last comma
        tableCreateSQL.deleteCharAt(tableCreateSQL.length() - 1);
        tableCreateSQL.append(") {TYPE}");

        // make sure the table doesn't exist
        try {
            drop = sqlConnection.prepareStatement(gsm.modifySQL("DROP TABLE " + tableName + " {CASCADE}"));
            drop.executeUpdate();
            drop.close();
        } catch (SQLException e) {
            // most likely means that the table didn't exist.
        }

        create = sqlConnection.prepareStatement(gsm.modifySQL(tableCreateSQL.toString()));
        create.executeUpdate();

        create.close();

        line = reader.readLine();
    }
    reader.close();

    md.info("Creating indexes");

    PreparedStatement createIndex = null;

    createIndex = sqlConnection
            .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi1^ ON ^MRCONSO^ (^CUI^, ^SAB^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection
            .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi2^ ON ^MRCONSO^ (^CUI^, ^AUI^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection
            .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi3^ ON ^MRCONSO^ (^AUI^, ^CODE^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi4^ ON ^MRREL^ (^RELA^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi5^ ON ^MRREL^ (^REL^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi6^ ON ^MRREL^ (^RUI^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection
            .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi7^ ON ^MRREL^ (^SAB^, ^RELA^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi8^ ON ^MRSAB^ (^RSAB^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi9^ ON ^MRRANK^ (^SAB^)"));
    createIndex.executeUpdate();
    createIndex.close();

    createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi10^ ON ^MRRANK^ (^TTY^)"));
    createIndex.executeUpdate();
    createIndex.close();

    if (!recalcRootOnly) {
        createIndex = sqlConnection
                .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi11^ ON ^MRDEF^ (^CUI^, ^SAB^)"));
        createIndex.executeUpdate();
        createIndex.close();

        createIndex = sqlConnection
                .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi12^ ON ^MRSAT^ (^METAUI^)"));
        createIndex.executeUpdate();
        createIndex.close();

        createIndex = sqlConnection
                .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi13^ ON ^MRSAT^ (^CUI^, ^SAB^)"));
        createIndex.executeUpdate();
        createIndex.close();

        createIndex = sqlConnection
                .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi14^ ON ^MRSAT^ (^CODE^, ^SAB^)"));
        createIndex.executeUpdate();
        createIndex.close();

        createIndex = sqlConnection.prepareStatement(gsm.modifySQL("CREATE INDEX ^mi15^ ON ^MRSTY^ (^CUI^)"));
        createIndex.executeUpdate();
        createIndex.close();

        createIndex = sqlConnection.prepareStatement(
                gsm.modifySQL("CREATE INDEX ^mi16^ ON ^MRHIER^ (^CUI^, ^AUI^, ^HCD^, ^SAB^, ^CXN^)"));
        createIndex.executeUpdate();
        createIndex.close();

        createIndex = sqlConnection
                .prepareStatement(gsm.modifySQL("CREATE INDEX ^mi17^ ON ^MRHIER^ (^CUI^, ^SAB^, ^CXN^)"));
        createIndex.executeUpdate();
        createIndex.close();
    }

    PreparedStatement insert = null;

    Iterator allTables = tables.iterator();
    Set rootCUIs = new HashSet();
    while (allTables.hasNext()) {
        System.gc();
        String table = (String) allTables.next();
        md.info("Loading " + table);

        boolean loadingMrHier = table.equalsIgnoreCase("MRHIER");

        StringBuffer insertSQL = new StringBuffer();

        insertSQL.append("INSERT INTO " + table + " (");

        String[] vals = (String[]) tableColumnMap.get(table + ".RRF");
        for (int i = 0; i < vals.length; i++) {
            if (gsm.getDatabaseType().equals("ACCESS") && vals[i].equals("VALUE")) {
                // reserved word in MSAccess
                insertSQL.append("\"" + vals[i] + "\", ");
            } else {
                insertSQL.append(vals[i] + ", ");
            }
        }

        // chop the last comma and space
        insertSQL.deleteCharAt(insertSQL.length() - 2);
        insertSQL.append(") VALUES (");

        for (int i = 0; i < vals.length; i++) {
            insertSQL.append("?, ");
        }

        // chop the last comma and space
        insertSQL.deleteCharAt(insertSQL.length() - 2);
        insertSQL.append(")");
        insert = sqlConnection.prepareStatement(gsm.modifySQL(insertSQL.toString()));

        URI tableURI = rrfLocation.resolve(table + ".RRF");

        if (verifyTableExists(tableURI)) {
            try {
                reader = getReader(tableURI);

                int count = 1;
                line = reader.readLine();
                boolean restrictToRootCUIs = recalcRootOnly && table.equalsIgnoreCase("MRCONSO");
                boolean restrictToRootRels = recalcRootOnly && table.equalsIgnoreCase("MRREL");
                while (line != null && line.length() > 0) {
                    // Note: If we are only using the data to recalculate
                    // root nodes,
                    // we only need CUIs defining root hierarchical terms
                    // and any related
                    // relationships.
                    if (restrictToRootCUIs && !line.contains("|SRC|RHT|")) {
                        line = reader.readLine();
                        continue;
                    }
                    String[] data = stringToArray(line, '|');

                    // If processing MRHIER, we only care about entries
                    // relevant to
                    // the specified MRHIER processing option. Many entries
                    // in this file
                    // we do not require since they can be derived from
                    // MRREL.
                    // MRHIER typically is much larger since it pre-computes
                    // the entire
                    // hierarchy, so we want to conserve time and space by
                    // loading only
                    // those entries that require special handling.
                    if (loadingMrHier && mrhierHCDCol > 0 && data.length > mrhierHCDCol
                            && StringUtils.isBlank(data[mrhierHCDCol])) {
                        line = reader.readLine();
                        continue;
                    }

                    if (restrictToRootCUIs && data.length >= 1)
                        rootCUIs.add(data[0]);
                    if (restrictToRootRels && (data.length < 5
                            || (!rootCUIs.contains(data[0]) && !rootCUIs.contains(data[4])))) {
                        line = reader.readLine();
                        continue;
                    }

                    for (int i = 0; i < vals.length; i++) {
                        insert.setString(i + 1, data[i]);
                    }
                    insert.executeUpdate();

                    count++;
                    line = reader.readLine();

                    if (validateMode && count > 100) {
                        line = null;
                    }

                    if (count % 10000 == 0) {
                        md.busy();
                    }

                    if (count % 100000 == 0) {
                        md.info("Loaded " + count + " into " + table);
                    }
                }
                reader.close();
            } catch (Exception e) {
                md.fatalAndThrowException("problem loading the table " + table, e);
            }

        } else {
            md.warn("Could not load table " + table + ". This" + "most likely means the corresponding RRF file"
                    + "was not found in the source.");
        }

        insert.close();
        System.gc();
    }

    sqlConnection.close();
    return (String[]) tables.toArray(new String[tables.size()]);
}

From source file:ca.simplegames.micro.utils.StringUtils.java

/**
 * Trim <i>all</i> whitespace from the given String:
 * leading, trailing, and inbetween characters.
 *
 * @param str the String to check//from www. ja  v a  2 s .  com
 * @return the trimmed String
 * @see java.lang.Character#isWhitespace
 */
public static String trimAllWhitespace(String str) {
    if (!hasLength(str)) {
        return str;
    }
    StringBuffer buf = new StringBuffer(str);
    int index = 0;
    while (buf.length() > index) {
        if (Character.isWhitespace(buf.charAt(index))) {
            buf.deleteCharAt(index);
        } else {
            index++;
        }
    }
    return buf.toString();
}

From source file:cn.fql.utility.StringUtility.java

/**
 * convert a list to a string of the list's meta with a seperator
 * if the atom is a string then surround with "'".
 * used in sql!/*from   w ww.  j a v a 2s . co  m*/
 *
 * @param list      <code>List</code>
 * @param separator specified separator
 * @return converted string with <code>seperator</code> seperator
 */
public static String list2String(List list, String separator) {
    StringBuffer sb = new StringBuffer("");
    if (list != null && list.size() > 0) {
        for (int i = 0; i < list.size(); i++) {
            Object objItem = list.get(i);
            if (sb.length() != 0) {
                sb.append(separator);
            }
            if (objItem instanceof String) {
                String strItem = (String) objItem;
                sb.append("'");
                sb.append(strItem);
                sb.append("'");
            } else {
                sb.append(objItem);
            }
        }
    }
    return sb.toString();
}

From source file:com.ikanow.infinit.e.data_model.store.config.source.SourcePojo.java

public static Collection<String> getDistributedKeys(String key, Integer highestDistributionFactorStored) {
    int numShards = 1;
    if (null != highestDistributionFactorStored) {
        numShards = highestDistributionFactorStored;
    }//from   w  ww .  j ava 2s .co m
    ArrayList<String> distributedKeys = new ArrayList<String>(numShards);
    StringBuffer keySb = new StringBuffer(key).append("#");
    int originalLength = keySb.length();
    for (int i = 0; i < numShards; i++) {
        if (0 == i) {
            distributedKeys.add(key);
        } else {
            keySb.append(i);
            distributedKeys.add(keySb.toString());
            keySb.setLength(originalLength);
        }
    }
    return distributedKeys;
}

From source file:com.adito.util.Utils.java

public static String readLine(InputStream in) throws IOException, EOFException {

    StringBuffer buf = new StringBuffer();

    int ch;//from w w w. java2 s.  co  m

    while ((ch = in.read()) > -1) {

        if (ch == '\n')
            break;
        buf.append((char) ch);
    }

    if (ch != '\n' && buf.length() == 0)
        return null;

    return buf.toString();
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.authenticate.BaseLoginServlet.java

/**
 * If we don't have a referrer, send them to the home page.
 *//*from  w  ww  . j  a  v  a  2s .  c o m*/
protected String figureHomePageUrl(HttpServletRequest req) {
    StringBuffer url = req.getRequestURL();
    String uri = req.getRequestURI();
    int authLength = url.length() - uri.length();
    String auth = url.substring(0, authLength);
    return auth + req.getContextPath();
}