Java tutorial
/* * File: $RCSfile$ * * Copyright (c) 2005 Wincor Nixdorf International GmbH, * Heinz-Nixdorf-Ring 1, 33106 Paderborn, Germany * All Rights Reserved. * * This software is the confidential and proprietary information * of Wincor Nixdorf ("Confidential Information"). You shall not * disclose such Confidential Information and shall use it only in * accordance with the terms of the license agreement you entered * into with Wincor Nixdorf. */ package cn.fql.utility; import org.apache.commons.lang.StringUtils; import java.util.Map; import java.util.Set; import java.util.HashMap; import java.util.Iterator; import java.util.StringTokenizer; import java.util.List; import java.util.ArrayList; /** * The class <code>cn.fql.utility.StringUtility</code> * * @author User, WN ASP SSD * @version $Revision$ */ public class StringUtility { /** * private constructor */ private StringUtility() { } /** * Trim String, if String is null, return null * * @param str <code>String</code> * @return @see java.lang.String#trim */ public static String trim(String str) { String strReturn; if (str != null) { strReturn = str.trim(); } else { strReturn = str; } return strReturn; } /** * Return is String empty or blank, object is measured with its' string value. * And its' string value with leading and trailing white * space removed, or this string if it has no leading or * trailing white space. * * @param o object which is measured with its' string value * @return whether string value is empty or blank */ public static boolean isEmptyOrBlankString(Object o) { boolean r = true; if (!isEmpty(o)) { if (o instanceof StringBuffer) { r = isEmpty(o.toString().trim()); } else { r = o instanceof String && isEmpty(((String) o).trim()); } } return r; } /** * Return is String empty or blank, object is measured with its' string value. * * @param o object which is measured with its' string value * @return whether string value is empty or blank */ public static boolean isEmptyOrBlankStringWithOutTrim(Object o) { boolean r = true; if (!isEmpty(o)) { if (o instanceof StringBuffer) { r = isEmpty(o.toString()); } else { r = o instanceof String && isEmpty(o); } } return r; } /** * Return is boolean which is indicated whether object is empty or its' string value is "" * * @param o object which is measured with its' string value * @return boolean value indicated whether object is empty or its' string value is "" */ public static boolean isEmpty(Object o) { return o == null || "".equals(o.toString()); } /** * Pad " " to String right side. * * @param strInput string to be right padded * @param intLength right pad the input string to intLength( in bytes ) * @return the string after right padding */ public static String rightPad(String strInput, int intLength) { byte[] byteResult = new byte[intLength]; byte[] byteInput = strInput.getBytes(); System.arraycopy(byteInput, 0, byteResult, 0, byteInput.length); for (int i = byteInput.length; i < intLength; i++) { byteResult[i] = ' '; } return new String(byteResult); } /** * Pad " " to string left side * * @param strInput string to be left padded * @param intLength left pad the input string to intLength( in bytes ) * @return the string after left padding */ public static String leftPad(String strInput, int intLength) { return leftPad(strInput, intLength, ' '); } /** * Find first element, Split by char * * @param src string to be split * @param ch which is used to split <code>src</code> * @return string after split with first char */ public static String splitFirst(String src, char ch) { return src.substring(0, src.indexOf(ch)); } /** * Get Object.toString, if null return "" else return object.toString() * * @param obj object to be replaced with "" * @return obj.toString or "" */ public static String replaceNull(Object obj) { if (obj == null) { return ""; } else { return obj.toString(); } } /** * Use specific String replace null; * * @param src object to be replaced with replaceAs * @param replaceAs string used to replace * @return src or replaceAs */ public static String replaceNull(String src, String replaceAs) { if (src == null) { return replaceAs; } else { return src; } } /** * Find substring start by one string end by another string * * @param src source string to be split * @param start start string * @param end end string * @return string between start and end */ public static String subString(String src, String start, String end) { int iStart = src.indexOf(start); int iEnd = src.indexOf(end); if ((iStart == -1) || (iEnd == -1)) { return null; } iEnd += end.length(); return src.substring(iStart, iEnd + 1); } /** * Find substring start by one string end by index * * @param src source string to be split * @param start start string * @param end end index * @return string between start and end */ public static String subString(String src, String start, int end) { int iStart = src.indexOf(start); if ((iStart == -1) || (end == -1)) { return null; } return src.substring(iStart, end); } /** * Find substring start by one index end by index * * @param src string to be splited * @param startIndex start index * @param endIndex end index * @return string between start and end */ public static String subString(String src, int startIndex, int endIndex) { if ((startIndex == -1) || (endIndex == -1)) { return null; } return src.substring(startIndex, endIndex); } /** * Find substring start by first index and end by length * * @param src source string to be split * @param length end index * @return string between start and end */ public static String subString(String src, int length) { if (src == null) { return ""; } if (src.length() <= length) { return src; } else { return src.substring(0, length); } } /** * Convert map keys to Uppercase or Lowercase * * @param map map to be converted * @param upperIt uppercase of lowercase * @return new map with converted keys */ public static Map upperMapKey(Map map, boolean upperIt) { if (map == null) { return null; } Set keys = map.keySet(); Map map2 = new HashMap(); for (Iterator iterator = keys.iterator(); iterator.hasNext();) { String key = (String) iterator.next(); Object o = map.get(key); if (upperIt) { key = key.toUpperCase(); } else { key = key.toLowerCase(); } map2.put(key, o); } return map2; } /** * Fill String with Zero * * @param source source String * @param length target length * @return String fill with zero */ public static String fillStringWithZero(String source, int length) { if (source.length() < length) { int fillLength = length - source.length(); for (int i = 0; i < fillLength; i++) { source = "0" + source; } } return source; } /** * Convert String to Map, "A=B&C=D" -> [A=B, C=D] * * @param srcStr string to convert * @param sperator sperator for split <code>srcStr</code> * @return <code>Map</code> */ public static Map convertStringToMap(String srcStr, String sperator) { StringTokenizer st1 = new StringTokenizer(srcStr, sperator); Map result = new HashMap(); while (st1.hasMoreTokens()) { String field = st1.nextToken(); StringTokenizer st2 = new StringTokenizer(field, "="); String key; String value = null; if (st2.countTokens() == 2) { key = st2.nextToken(); value = st2.nextToken(); } else { key = st2.nextToken(); } result.put(key, value); } return result; } /** * Pad specific string to string left side * * @param strInput string to be left padded * @param intLength left pad the input string to intLength( in bytes ) * @param paddingWith padding char * @return the string after left padding */ public static String leftPad(String strInput, int intLength, char paddingWith) { if (intLength > strInput.length()) { byte[] byteResult = new byte[intLength]; byte[] byteInput = strInput.getBytes(); System.arraycopy(byteInput, 0, byteResult, intLength - byteInput.length, byteInput.length); for (int i = 0; i < (intLength - byteInput.length); i++) { byteResult[i] = (byte) paddingWith; } return new String(byteResult); } else { return strInput; } } /** * Split String to List * * @param strInput String with splitor * @param strSplitor1 Splitor, such as ',' '|' * @param strSplitor2 Splitor, such as ',' '|' * @return String Item in List */ public static List extractStringBetweenTwoSplitor(String strInput, String strSplitor1, char strSplitor2) { List listOut = new ArrayList(); List listResult = splitString(strInput, strSplitor1); if (listResult != null && listResult.size() > 0) { for (int i = 0; i < listResult.size(); i++) { String foreStr = (String) listResult.get(i); if (foreStr.indexOf(strSplitor2) >= 0) { String splitedStr = splitFirst(foreStr, strSplitor2); if (splitedStr.indexOf(strSplitor2) < 0) { listOut.add(strSplitor1 + splitedStr + strSplitor2); } } } } return listOut; } /** * Split String to List * * @param strInput String with splitor * @param strSplitor Splitor, such as ',' '|' * @return String Item in List */ public static List splitString(String strInput, String strSplitor) { List listResult = new ArrayList(); if (strInput == null) { return null; } int start = 0; int end = strInput.length(); while (start < end) { int delimIdx = strInput.indexOf(strSplitor, start); if (delimIdx < 0) { String tok = strInput.substring(start); listResult.add(tok.trim()); start = end; } else { String tok = strInput.substring(start, delimIdx); listResult.add(tok.trim()); start = delimIdx + strSplitor.length(); } } return listResult; } /** * Split String to List * * @param strInput String with splitor * @param strSplitor Splitor, such as ',' '|' * @return String Item in List */ public static List splitStringWithoutTrim(String strInput, String strSplitor) { List listResult = new ArrayList(); if (strInput == null) { return null; } int start = 0; int end = strInput.length(); while (start < end) { int delimIdx = strInput.indexOf(strSplitor, start); if (delimIdx < 0) { String tok = strInput.substring(start); listResult.add(tok); start = end; } else { String tok = strInput.substring(start, delimIdx); listResult.add(tok); start = delimIdx + strSplitor.length(); } } return listResult; } /** * The index within this string of first occurrence of the specified substring splited by splitor. * * @param strInput String with splitor, such as '|abc|efg|' * @param strSearch String to search, such as 'efg' * @param strSplitor Splitor, such as '|' * @return The index within this string of first occurrence of the specified substring. */ public static int indexOfBySplitor(String strInput, String strSearch, String strSplitor) { int intRet = strInput.indexOf(strSplitor + strSearch + strSplitor); if (intRet >= 0) { intRet += strSplitor.length(); } return intRet; } /** * Check if the search string is in input string seperated by splitor. * * @param strInput string to be searched * @param strSearch string used to be seached as key * @param strSplitor splitor string * @return if has search string with splitor return true, else return false */ public static boolean instrBySplitor(String strInput, String strSearch, String strSplitor) { boolean ret = false; List lst = splitString(strInput, strSplitor); if (lst != null) { for (Iterator it = lst.iterator(); it.hasNext();) { String string = (String) it.next(); if (string != null && string.equals(strSearch)) { ret = true; break; } } } return ret; } /** * Insert string at specified position of <code>src</code> * * @param src string to be inserted * @param strInput insert content * @param position index * @return new string with insert content */ public static String insertStringAtPosition(String src, String strInput, int position) { String result = src; if (src.length() > position) { String firstSection = subString(src, position); String secondSection = subString(src, position, src.length()); result = firstSection + strInput + secondSection; } return result; } /** * Combine string array as string, split by token string * * @param strsInput Object array which includes elements to be combined * @param strToken split token * @return string combined with <code>strsInput</code>, splited by <code>strToken</code> */ public static String combineString(Object[] strsInput, String strToken) { if (strsInput == null) { return null; } StringBuffer sb = new StringBuffer(); int l = strsInput.length; for (int i = 0; i < l; i++) { sb.append(strsInput[i].toString()); if (i < l - 1) { sb.append(strToken); } } return sb.toString(); } /** * Combine int array as string, split by token string * * @param strsInput Object array which includes elements to be combined * @param strToken split token * @return string combined with <code>strsInput</code>, splited by <code>strToken</code> */ public static String combineString(int[] strsInput, String strToken) { if (strsInput == null) { return null; } StringBuffer sb = new StringBuffer(); int l = strsInput.length; for (int i = 0; i < l; i++) { sb.append(strsInput[i]); if (i < l - 1) { sb.append(strToken); } } return sb.toString(); } /** * Combine string array as string, split by token string * * @param lstInput list which includes elements to be combined * @param strToken split token * @return string combined with <code>strsInput</code>, splited by <code>strToken</code> */ public static String combineString(List lstInput, String strToken) { if (lstInput == null) { return null; } StringBuffer sb = new StringBuffer(); for (Iterator iterator = lstInput.iterator(); iterator.hasNext();) { sb.append(iterator.next().toString()); if (iterator.hasNext()) { sb.append(strToken); } } return sb.toString(); } /** * Split string to several segements with specified length, split by token string * * @param strItem string to be splited * @param strToken split token * @param itemLen specified length * @return string splited to several segements with <code>itemLen</code>, splited by <code>strToken</code> */ public static String combineString(String strItem, String strToken, int itemLen) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < itemLen; i++) { if (i > 0) { sb.append(strToken); } sb.append(strItem); } return sb.toString(); } /** * Add ' to every token of input String. Such as if input str is "el1,el2,el3", output str is "'el1','el2','el3'" * * @param inputStr Input String * @return String Add ' to Every Token */ public static String addInvertedComma(String inputStr) { StringBuffer buffer = new StringBuffer(); if (inputStr != null) { StringTokenizer tokens = new StringTokenizer(inputStr, ","); int index = 0; while (tokens.hasMoreTokens()) { if (index > 0) { buffer.append(","); } buffer.append("'"); buffer.append(tokens.nextToken()); buffer.append("'"); index++; } } return buffer.toString(); } /** * Split String to Array * * @param strInput Input String with splitor * @param strSplitor String Splitor * @return String Item in Array */ public static String[] splitStringToArray(String strInput, String strSplitor) { String[] strArray = null; List lstResult = splitString(strInput, strSplitor); if ((lstResult != null) && (lstResult.size() > 0)) { strArray = new String[lstResult.size()]; int size = lstResult.size(); for (int i = 0; i < size; i++) { strArray[i] = (String) lstResult.get(i); } } return strArray; } /** * Convert string to list, every char of string would be convert to string and added to list * * @param source string to be converted * @return <code>List</code> */ public static List string2List(String source) { if (source != null && source.length() > 0) { List result = new ArrayList(); for (int i = 0; i < source.length(); i++) { result.add(String.valueOf(source.charAt(i))); } return result; } else { return new ArrayList(); } } /** * convert a list to a string of the list's meta without seprator * used in checkbox group components's model * * @param list list to be converted * @return converted string */ public static String list2String(List list) { StringBuffer sb = new StringBuffer(""); if (list != null && list.size() > 0) { for (int i = 0; i < list.size(); i++) { sb.append(list.get(i)); } } return sb.toString(); } /** * 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! * * @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(); } /** * 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 * @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(); } /** * insert string at position of martrix * * @param matrix martix to be converte * @param row from 1 * @param col from 1 * @param f insert string */ public static void insertatPosition(char[][] matrix, int row, int col, String f) { insertatPosition(matrix, row, -1, col, -1, f); } /** * insert string at position of martrix * * @param matrix martix to be converte * @param startRow from 1 * @param endRow from 1 * @param startCol from 1 * @param endCol from 1 * @param f insert string */ public static void insertatPosition(char[][] matrix, int startRow, int endRow, int startCol, int endCol, String f) { int maxRow = matrix.length; int maxCol = matrix[0].length; int pointRow = startRow - 1; int pointCol = startCol - 1; int rowLimit = endRow - 1; int colLimit = endCol - 1; if (endRow < 0 || endRow <= startRow || endRow > maxRow) { rowLimit = maxRow - 1; } if (endCol < 0 || endCol <= startCol || endCol > maxCol) { colLimit = maxCol - 1; } if (pointRow >= 0 && pointRow <= rowLimit) { if (pointCol >= 0 && pointCol <= colLimit) { for (int i = 0; i < f.length(); i++) { matrix[pointRow][pointCol] = f.charAt(i); pointCol = pointCol + 1; if (pointCol > colLimit) { //wrap insertatPosition(matrix, startRow + 1, startCol, f.substring(i + 1)); return; } } } } } /** * Combine matrix to string * * @param matrix char array to be combined * @return string corresponded to matrix */ public static String printfromMatrix(char[][] matrix) { StringBuffer resultSt = new StringBuffer(); int maxRow = matrix.length; for (int i = 0; i < maxRow; i++) { for (int j = 0; j < matrix[i].length; j++) { if ('\0' == matrix[i][j]) { resultSt.append(" "); } else { resultSt.append(matrix[i][j]); } } } return resultSt.toString(); } /** * Concatenate string with seperator, skip string with null or "" value * * @param str1 <code>String</code> * @param str2 <code>String</code> * @param seperator <code>String</code> * @return string after concatenated str1,str2 */ public static String concatenateStringWithSeperator(String str1, String str2, String seperator) { String str = ""; if (isEmpty(str1) && isEmpty(str2)) { } else if (isEmpty(str1)) { str = str2; } else if (isEmpty(str2)) { str = str1; } else { str = str1 + seperator + str2; } return str; } /** * Convert string array to string with specified delimiter * * @param strValues string array to be converted * @param delimiter specified delimiter * @return for example {"aa","bb","cc"}, ";" would be convert to "aa;bb;cc" */ public static String connectStrs(String[] strValues, String delimiter) { String result = ""; for (int i = 0; i < strValues.length; i++) { String strValue = strValues[i]; String value = replaceNull(strValue); if (i == strValues.length - 1) { result += value; } else { result += value + delimiter; } } return result; } /** * Convert object to string, if object is null, return "". * * @param object object converted to string * @return if object is null, return "". else object.toString(); */ public static String toString(Object object) { if (object == null) { return null; } else { return object.toString(); } } /** * Split <code>sb</code> to <code>numPreRow</code> * * @param sb string buffer to be splited * @param numPreRow row number * @return <code>ArrayList</code> */ public static List splitContent(StringBuffer sb, int numPreRow) { return splitContent(sb.toString(), numPreRow); } /** * Split string to list which includes elements with numPreRow length * * @param src source string * @param numPreRow row number * @return <code>ArrayList</code> */ public static List splitContent(String src, int numPreRow) { ArrayList strlst = new ArrayList(); if (src == null || "".equals(src)) { return null; } if (numPreRow == 0) { strlst.add(src); return strlst; } for (int i = 0; i < src.length(); i++) { if ((i + 1) * numPreRow <= src.length()) { String temStr = src.substring(i * numPreRow, i * numPreRow + numPreRow); strlst.add(temStr); } else if (i * numPreRow <= src.length() && (i + 1) * numPreRow > src.length()) { strlst.add(src.substring(i * numPreRow, src.length())); } } return strlst; } /** * Recover a illegal string represents a property name of POJO. Convert it to a legal name. * * @param illegalPropertyName illegal property name * @return legal property name */ public static String recoverIllegalPropertyName(String illegalPropertyName) { String _iPropertyName = StringUtility.replaceNull(illegalPropertyName); if (illegalPropertyName.indexOf(" ") != -1 || illegalPropertyName.indexOf("_") != -1 || illegalPropertyName.indexOf("-") != -1) { char[] charArray = _iPropertyName.toCharArray(); char[] legalCharArray = new char[charArray.length]; int emptyCount = 0; for (int i = 0; i < charArray.length; i++) { char c = charArray[i]; if (c == '_' || c == '-' || c == ' ') { if (i < charArray.length - 1) { legalCharArray[i] = ' '; legalCharArray[i + 1] = Character.toUpperCase(charArray[i + 1]); i++; emptyCount++; } } else { legalCharArray[i] = c; } } char[] _result = new char[legalCharArray.length - emptyCount]; for (int i = 0, index = 0; i < legalCharArray.length; i++) { char c = legalCharArray[i]; if (c != ' ') { _result[index] = c; index++; } } _iPropertyName = String.valueOf(_result); } return _iPropertyName; } /** * Separte a full class name into string array. * * @param className Class name with full package name * @return String[0]=className, String[1]=packageName */ public static String[] getClassFullPath(String className) { String[] _segments = StringUtility.splitStringToArray(className, "."); String packageName = ""; for (int i = 0; i < _segments.length - 1; i++) { packageName += _segments[i]; if (i < _segments.length - 2) { packageName += "."; } } if (StringUtils.isEmpty(packageName)) { packageName = "java.lang"; } String _className = _segments[_segments.length - 1]; String[] path = new String[2]; path[0] = _className; path[1] = packageName; return path; } /** * Get like criteria string * * @param value * @return */ public static String getLikeCriteriaString(String value) { String _result = value; if (value.indexOf("%") == -1) { _result += "%"; _result = "%" + _result; } return _result; } } /** * History: * * $Log$ */