/*
* Copyright 2014, Brook. All rights reserved.
*/
package brook.common.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import org.hibernate.dialect.Dialect;
import org.hibernate.internal.util.collections.ArrayHelper;
public class StringUtil {
private static String[] straChineseUnit = { "分", "角", "圆", "拾", "佰", "仟",
"万", "拾", "佰", "仟", "亿", "拾", "佰", "仟" };
private static String[] straChineseNumber = { "零", "壹", "贰", "叁", "肆", "伍",
"陆", "柒", "捌", "玖" };
private static final int ALIAS_TRUNCATE_LENGTH = 10;
public static final String WHITESPACE = " \n\r\f\t";
private StringUtil() { /* static methods only - hide constructor */
}
public static String randomString(int length) {
StringBuilder sb = new StringBuilder(length);
Random rand = new Random();
for (int i = 0; i < length; ++i) {
int r = rand.nextInt(63);
if (r >= 37)
sb.append((char) (97 + r - 37));
else if (r == 36)
sb.append('_');
else if (r >= 10)
sb.append((char) (65 + r - 10));
else
sb.append((char) (48 + r));
}
return sb.toString();
}
public static boolean isNullOrSpace(String str) {
return ((str == null) || ("".equals(str)) || ("".equals(str.trim())));
}
public static final boolean isNotEmpty(String s) {
return (!(isEmpty(s)));
}
public static final boolean isEmpty(String s) {
if ((s == null) || (s.length() == 0))
return true;
for (int i = s.length() - 1; i >= 0; --i)
if (!(Character.isSpaceChar(s.charAt(i))))
return false;
return true;
}
/*public static boolean isNotEmpty(String string) {
return string != null && string.length() > 0;
}
public static boolean isEmpty(String string) {
return string == null || string.length() == 0;
}*/
public static byte[] hexStrToBytes(String hex) {
if (hex.length() % 2 != 0)
hex = '0' + hex;
byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < hex.length(); i += 2)
bytes[(i / 2)] = Integer.valueOf(hex.substring(i, i + 2), 16)
.byteValue();
return bytes;
}
public static String bytesToHexStr(byte[] bytes) {
StringBuffer buf = new StringBuffer();
String stmp = null;
for (int i = 0; i < bytes.length; ++i) {
stmp = Integer.toHexString(bytes[i] & 0xFF);
if (stmp.length() == 1)
buf.append('0');
buf.append(stmp);
}
return buf.toString().toUpperCase();
}
public static String concat(String[] strings) {
int capacity = 0;
for (int i = 0; i < strings.length; ++i)
capacity += strings[i].length();
StringBuilder sb = new StringBuilder(capacity);
for (int i = 0; i < strings.length; ++i)
sb.append(strings[i]);
return sb.toString();
}
public static String trimToSize(String src, int bytes) {
return trimToSize(src, bytes, null);
}
public static String trimToSize(String src, int bytes, String suffix) {
byte[] arr = src.getBytes();
if (arr.length <= bytes)
return src;
boolean hasSuffix = (suffix != null) && (suffix.length() > 0);
if (hasSuffix)
bytes -= suffix.getBytes().length;
int i = bytes - 1;
while ((i >= 0) && (arr[i] < 0))
--i;
if ((bytes - 1 - i & 0x1) == 1)
--bytes;
String str = new String(arr, 0, bytes);
return ((hasSuffix) ? str + suffix : str);
}
public static String fillAtLeft(String str, int totalLength, char ch) {
int count = totalLength - str.length();
if (count < 0)
throw new IllegalArgumentException(
"string length is great than total length");
StringBuilder buf = new StringBuilder(totalLength);
for (int i = 0; i < count; ++i)
buf.append(ch);
return str;
}
public static String fillToLength(int value, int length) {
String str = String.valueOf(value);
if (str.length() > length)
throw new RuntimeException("number overflow");
return fillAtLeft(str, length, '0');
}
public static String toCnCurrency(String number) {
return numberToChinse(new BigDecimal(number));
}
public static String toCnCurrency(double number) {
return numberToChinse(new BigDecimal(number));
}
public static String toCnCurrency(long number) {
return numberToChinse(new BigDecimal(number));
}
@Deprecated
/**
* 废弃,因为第228行有错误
*/
public static String numberToChinse(BigDecimal bigdMoneyNumber) {
String strChineseCurrency = "";
boolean bZero = true;
int ChineseUnitIndex = 0;
try {
if (bigdMoneyNumber.intValue() == 0) {
return "零圆整";
}
double doubMoneyNumber = Math
.round(bigdMoneyNumber.doubleValue() * 100.0D);
boolean bNegative = doubMoneyNumber < 0D;
doubMoneyNumber = Math.abs(doubMoneyNumber);
while (doubMoneyNumber > 0D) {
if ((ChineseUnitIndex == 2)
&& (strChineseCurrency.length() == 0)) {
strChineseCurrency = strChineseCurrency + "整";
}
if (doubMoneyNumber % 10.0D > 0D) {
strChineseCurrency = straChineseNumber[((int) doubMoneyNumber % 10)]
+ straChineseUnit[ChineseUnitIndex]
+ strChineseCurrency;
bZero = false;
} else {
if (ChineseUnitIndex == 2) {
if (doubMoneyNumber > 0D) {
strChineseCurrency = straChineseUnit[ChineseUnitIndex]
+ strChineseCurrency;
bZero = true;
}
} else if ((((ChineseUnitIndex == 6) || (ChineseUnitIndex == 10)))
&& (doubMoneyNumber % 1000.0D > 0D)) {
strChineseCurrency = straChineseUnit[ChineseUnitIndex]
+ strChineseCurrency;
}
if (!(bZero))
strChineseCurrency = straChineseNumber[0]
+ strChineseCurrency;
bZero = true;
}
doubMoneyNumber = Math.floor(doubMoneyNumber / 10.0D);
++ChineseUnitIndex;
}
if (!(bNegative))
// break label312;
strChineseCurrency = "负" + strChineseCurrency;
} catch (Exception e) {
e.printStackTrace();
return "";
}
label312: return strChineseCurrency;
}
public static String stringToHtml(String str) {
char ch;
if (str == null)
return "";
int len = str.length();
StringBuilder htm = new StringBuilder(len + len / 10);
for (int i = 0; i < len; ++i) {
ch = str.charAt(i);
switch (ch) {
case '<':
htm.append("<");
break;
case '>':
htm.append(">");
break;
case '&':
htm.append("&");
break;
case '"':
htm.append(""");
break;
case ' ':
htm.append(" ");
break;
case '\t':
htm.append(" ");
break;
case '\n':
htm.append("<br>");
break;
case '\r':
break;
default:
htm.append(ch);
}
}
return htm.toString();
}
public static String stringToXml(String str) {
char ch;
if (str == null)
return "";
int len = str.length();
StringBuilder xml = new StringBuilder(len + len / 10);
for (int i = 0; i < len; ++i) {
ch = str.charAt(i);
switch (ch) {
case '<':
xml.append("<");
break;
case '>':
xml.append(">");
break;
case '&':
xml.append("&");
break;
case '"':
xml.append(""");
break;
default:
xml.append(ch);
}
}
return xml.toString();
}
public static String htmlToString(String html) {
html = html.replaceAll(" ", " ");
html = html.replaceAll(""", "\"");
html = html.replaceAll("&", "&");
html = html.replaceAll("<", "<");
html = html.replaceAll(">", ">");
html = html.replaceAll("&", "&");
html = html.replaceAll("®", "(R)");
html = html.replaceAll("©", "(C)");
html = html.replaceAll(" ", "\t");
html = html.replaceAll(" ", "\t");
return html.replaceAll("™", "TM");
}
public static String toSQLString(String str) {
int len = str.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; ++i) {
char ch = str.charAt(i);
if (ch == '\'')
sb.append("\\'");
else if (ch == '"')
sb.append("\\\"");
else if (ch == ';')
sb.append("\\;");
else
sb.append(ch);
}
return sb.toString();
}
public static String toJsonString(String str) {
char ch;
int len = str.length();
StringBuilder sb = new StringBuilder(len + 16);
for (int i = 0; i < len; ++i) {
ch = str.charAt(i);
switch (ch) {
case '\'':
sb.append("\\'");
break;
case '"':
sb.append("\\\"");
break;
case '\n':
sb.append("\\n");
break;
case '\\':
sb.append("\\\\");
break;
default:
sb.append(ch);
}
}
return sb.toString();
}
/*
* public static boolean containsDigits(String string) { for ( int i=0;
* i<string.length(); i++ ) { if ( Character.isDigit( string.charAt(i) ) )
* return true; } return false; }
*/
public static int lastIndexOfLetter(String string) {
for (int i = 0; i < string.length(); i++) {
char character = string.charAt(i);
if (!Character.isLetter(character) /* && !('_'==character) */)
return i - 1;
}
return string.length() - 1;
}
public static String join(String seperator, String[] strings) {
int length = strings.length;
if (length == 0)
return "";
StringBuilder buf = new StringBuilder(length * strings[0].length())
.append(strings[0]);
for (int i = 1; i < length; i++) {
buf.append(seperator).append(strings[i]);
}
return buf.toString();
}
public static String join(String seperator, Iterator objects) {
StringBuilder buf = new StringBuilder();
if (objects.hasNext())
buf.append(objects.next());
while (objects.hasNext()) {
buf.append(seperator).append(objects.next());
}
return buf.toString();
}
public static String[] add(String[] x, String sep, String[] y) {
String[] result = new String[x.length];
for (int i = 0; i < x.length; i++) {
result[i] = x[i] + sep + y[i];
}
return result;
}
public static String repeat(String string, int times) {
StringBuilder buf = new StringBuilder(string.length() * times);
for (int i = 0; i < times; i++)
buf.append(string);
return buf.toString();
}
public static String repeat(char character, int times) {
char[] buffer = new char[times];
Arrays.fill(buffer, character);
return new String(buffer);
}
public static String replace(String template, String placeholder,
String replacement) {
return replace(template, placeholder, replacement, false);
}
public static String[] replace(String templates[], String placeholder,
String replacement) {
String[] result = new String[templates.length];
for (int i = 0; i < templates.length; i++) {
result[i] = replace(templates[i], placeholder, replacement);
}
return result;
}
public static String replace(String template, String placeholder,
String replacement, boolean wholeWords) {
return replace(template, placeholder, replacement, wholeWords, false);
}
public static String replace(String template, String placeholder,
String replacement, boolean wholeWords,
boolean encloseInParensIfNecessary) {
if (template == null) {
return template;
}
int loc = template.indexOf(placeholder);
if (loc < 0) {
return template;
} else {
String beforePlaceholder = template.substring(0, loc);
String afterPlaceholder = template.substring(loc
+ placeholder.length());
return replace(beforePlaceholder, afterPlaceholder, placeholder,
replacement, wholeWords, encloseInParensIfNecessary);
}
}
public static String replace(String beforePlaceholder,
String afterPlaceholder, String placeholder, String replacement,
boolean wholeWords, boolean encloseInParensIfNecessary) {
final boolean actuallyReplace = !wholeWords
|| afterPlaceholder.length() == 0
|| !Character.isJavaIdentifierPart(afterPlaceholder.charAt(0));
boolean encloseInParens = actuallyReplace && encloseInParensIfNecessary
&& !(getLastNonWhitespaceCharacter(beforePlaceholder) == '(')
&& !(getFirstNonWhitespaceCharacter(afterPlaceholder) == ')');
StringBuilder buf = new StringBuilder(beforePlaceholder);
if (encloseInParens) {
buf.append('(');
}
buf.append(actuallyReplace ? replacement : placeholder);
if (encloseInParens) {
buf.append(')');
}
buf.append(replace(afterPlaceholder, placeholder, replacement,
wholeWords, encloseInParensIfNecessary));
return buf.toString();
}
public static char getLastNonWhitespaceCharacter(String str) {
if (str != null && str.length() > 0) {
for (int i = str.length() - 1; i >= 0; i--) {
char ch = str.charAt(i);
if (!Character.isWhitespace(ch)) {
return ch;
}
}
}
return '\0';
}
public static char getFirstNonWhitespaceCharacter(String str) {
if (str != null && str.length() > 0) {
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (!Character.isWhitespace(ch)) {
return ch;
}
}
}
return '\0';
}
public static String replaceOnce(String template, String placeholder,
String replacement) {
if (template == null) {
return template; // returnign null!
}
int loc = template.indexOf(placeholder);
if (loc < 0) {
return template;
} else {
return new StringBuilder(template.substring(0, loc))
.append(replacement)
.append(template.substring(loc + placeholder.length()))
.toString();
}
}
public static String[] split(String seperators, String list) {
return split(seperators, list, false);
}
public static String[] split(String seperators, String list, boolean include) {
StringTokenizer tokens = new StringTokenizer(list, seperators, include);
String[] result = new String[tokens.countTokens()];
int i = 0;
while (tokens.hasMoreTokens()) {
result[i++] = tokens.nextToken();
}
return result;
}
public static String unqualify(String qualifiedName) {
int loc = qualifiedName.lastIndexOf(".");
return (loc < 0) ? qualifiedName : qualifiedName.substring(loc + 1);
}
public static String qualifier(String qualifiedName) {
int loc = qualifiedName.lastIndexOf(".");
return (loc < 0) ? "" : qualifiedName.substring(0, loc);
}
/**
* Collapses a name. Mainly intended for use with classnames, where an
* example might serve best to explain. Imagine you have a class named
* <samp>'org.hibernate.internal.util.StringHelper'</samp>; calling collapse
* on that classname will result in <samp>'o.h.u.StringHelper'<samp>.
*
* @param name
* The name to collapse.
* @return The collapsed name.
*/
public static String collapse(String name) {
if (name == null) {
return null;
}
int breakPoint = name.lastIndexOf('.');
if (breakPoint < 0) {
return name;
}
return collapseQualifier(name.substring(0, breakPoint), true)
+ name.substring(breakPoint); // includes last '.'
}
/**
* Given a qualifier, collapse it.
*
* @param qualifier
* The qualifier to collapse.
* @param includeDots
* Should we include the dots in the collapsed form?
*
* @return The collapsed form.
*/
public static String collapseQualifier(String qualifier, boolean includeDots) {
StringTokenizer tokenizer = new StringTokenizer(qualifier, ".");
String collapsed = Character.toString(tokenizer.nextToken().charAt(0));
while (tokenizer.hasMoreTokens()) {
if (includeDots) {
collapsed += '.';
}
collapsed += tokenizer.nextToken().charAt(0);
}
return collapsed;
}
/**
* Partially unqualifies a qualified name. For example, with a base of
* 'org.hibernate' the name 'org.hibernate.internal.util.StringHelper' would
* become 'util.StringHelper'.
*
* @param name
* The (potentially) qualified name.
* @param qualifierBase
* The qualifier base.
*
* @return The name itself, or the partially unqualified form if it begins
* with the qualifier base.
*/
public static String partiallyUnqualify(String name, String qualifierBase) {
if (name == null || !name.startsWith(qualifierBase)) {
return name;
}
return name.substring(qualifierBase.length() + 1); // +1 to start after
// the following '.'
}
/**
* Cross between {@link #collapse} and {@link #partiallyUnqualify}.
* Functions much like {@link #collapse} except that only the qualifierBase
* is collapsed. For example, with a base of 'org.hibernate' the name
* 'org.hibernate.internal.util.StringHelper' would become
* 'o.h.util.StringHelper'.
*
* @param name
* The (potentially) qualified name.
* @param qualifierBase
* The qualifier base.
*
* @return The name itself if it does not begin with the qualifierBase, or
* the properly collapsed form otherwise.
*/
public static String collapseQualifierBase(String name, String qualifierBase) {
if (name == null || !name.startsWith(qualifierBase)) {
return collapse(name);
}
return collapseQualifier(qualifierBase, true)
+ name.substring(qualifierBase.length());
}
public static String[] suffix(String[] columns, String suffix) {
if (suffix == null)
return columns;
String[] qualified = new String[columns.length];
for (int i = 0; i < columns.length; i++) {
qualified[i] = suffix(columns[i], suffix);
}
return qualified;
}
private static String suffix(String name, String suffix) {
return (suffix == null) ? name : name + suffix;
}
public static String root(String qualifiedName) {
int loc = qualifiedName.indexOf(".");
return (loc < 0) ? qualifiedName : qualifiedName.substring(0, loc);
}
public static String unroot(String qualifiedName) {
int loc = qualifiedName.indexOf(".");
return (loc < 0) ? qualifiedName : qualifiedName.substring(loc + 1,
qualifiedName.length());
}
public static boolean booleanValue(String tfString) {
String trimmed = tfString.trim().toLowerCase();
return trimmed.equals("true") || trimmed.equals("t");
}
public static String toString(Object[] array) {
int len = array.length;
if (len == 0)
return "";
StringBuilder buf = new StringBuilder(len * 12);
for (int i = 0; i < len - 1; i++) {
buf.append(array[i]).append(", ");
}
return buf.append(array[len - 1]).toString();
}
public static String[] multiply(String string, Iterator placeholders,
Iterator replacements) {
String[] result = new String[] { string };
while (placeholders.hasNext()) {
result = multiply(result, (String) placeholders.next(),
(String[]) replacements.next());
}
return result;
}
private static String[] multiply(String[] strings, String placeholder,
String[] replacements) {
String[] results = new String[replacements.length * strings.length];
int n = 0;
for (int i = 0; i < replacements.length; i++) {
for (int j = 0; j < strings.length; j++) {
results[n++] = replaceOnce(strings[j], placeholder,
replacements[i]);
}
}
return results;
}
public static int countUnquoted(String string, char character) {
if ('\'' == character) {
throw new IllegalArgumentException(
"Unquoted count of quotes is invalid");
}
if (string == null)
return 0;
// Impl note: takes advantage of the fact that an escpaed single quote
// embedded within a quote-block can really be handled as two seperate
// quote-blocks for the purposes of this method...
int count = 0;
int stringLength = string.length();
boolean inQuote = false;
for (int indx = 0; indx < stringLength; indx++) {
char c = string.charAt(indx);
if (inQuote) {
if ('\'' == c) {
inQuote = false;
}
} else if ('\'' == c) {
inQuote = true;
} else if (c == character) {
count++;
}
}
return count;
}
public static int[] locateUnquoted(String string, char character) {
if ('\'' == character) {
throw new IllegalArgumentException(
"Unquoted count of quotes is invalid");
}
if (string == null) {
return new int[0];
}
ArrayList locations = new ArrayList(20);
// Impl note: takes advantage of the fact that an escpaed single quote
// embedded within a quote-block can really be handled as two seperate
// quote-blocks for the purposes of this method...
int stringLength = string.length();
boolean inQuote = false;
for (int indx = 0; indx < stringLength; indx++) {
char c = string.charAt(indx);
if (inQuote) {
if ('\'' == c) {
inQuote = false;
}
} else if ('\'' == c) {
inQuote = true;
} else if (c == character) {
locations.add(indx);
}
}
return ArrayHelper.toIntArray(locations);
}
public static String qualify(String prefix, String name) {
if (name == null || prefix == null) {
throw new NullPointerException();
}
return new StringBuilder(prefix.length() + name.length() + 1)
.append(prefix).append('.').append(name).toString();
}
public static String[] qualify(String prefix, String[] names) {
if (prefix == null)
return names;
int len = names.length;
String[] qualified = new String[len];
for (int i = 0; i < len; i++) {
qualified[i] = qualify(prefix, names[i]);
}
return qualified;
}
public static int firstIndexOfChar(String sqlString, String string,
int startindex) {
int matchAt = -1;
for (int i = 0; i < string.length(); i++) {
int curMatch = sqlString.indexOf(string.charAt(i), startindex);
if (curMatch >= 0) {
if (matchAt == -1) { // first time we find match!
matchAt = curMatch;
} else {
matchAt = Math.min(matchAt, curMatch);
}
}
}
return matchAt;
}
public static String truncate(String string, int length) {
if (string.length() <= length) {
return string;
} else {
return string.substring(0, length);
}
}
public static String generateAlias(String description) {
return generateAliasRoot(description) + '_';
}
/**
* Generate a nice alias for the given class name or collection role name
* and unique integer. Subclasses of Loader do <em>not</em> have to use
* aliases of this form.
*
* @param description
* The base name (usually an entity-name or collection-role)
* @param unique
* A uniquing value
*
* @return an alias of the form <samp>foo1_</samp>
*/
public static String generateAlias(String description, int unique) {
return generateAliasRoot(description) + Integer.toString(unique) + '_';
}
/**
* Generates a root alias by truncating the "root name" defined by the
* incoming decription and removing/modifying any non-valid alias
* characters.
*
* @param description
* The root name from which to generate a root alias.
* @return The generated root alias.
*/
private static String generateAliasRoot(String description) {
String result = truncate(unqualifyEntityName(description),
ALIAS_TRUNCATE_LENGTH).toLowerCase().replace('/', '_') // entityNames
// may
// now
// include
// slashes
// for
// the
// representations
.replace('$', '_'); // classname may be an inner class
result = cleanAlias(result);
if (Character.isDigit(result.charAt(result.length() - 1))) {
return result + "x"; // ick!
} else {
return result;
}
}
/**
* Clean the generated alias by removing any non-alpha characters from the
* beginning.
*
* @param alias
* The generated alias to be cleaned.
* @return The cleaned alias, stripped of any leading non-alpha characters.
*/
private static String cleanAlias(String alias) {
char[] chars = alias.toCharArray();
// short cut check...
if (!Character.isLetter(chars[0])) {
for (int i = 1; i < chars.length; i++) {
// as soon as we encounter our first letter, return the
// substring
// from that position
if (Character.isLetter(chars[i])) {
return alias.substring(i);
}
}
}
return alias;
}
public static String unqualifyEntityName(String entityName) {
String result = unqualify(entityName);
int slashPos = result.indexOf('/');
if (slashPos > 0) {
result = result.substring(0, slashPos - 1);
}
return result;
}
public static String toUpperCase(String str) {
return str == null ? null : str.toUpperCase();
}
public static String toLowerCase(String str) {
return str == null ? null : str.toLowerCase();
}
public static String moveAndToBeginning(String filter) {
if (filter.trim().length() > 0) {
filter += " and ";
if (filter.startsWith(" and "))
filter = filter.substring(4);
}
return filter;
}
/**
* Determine if the given string is quoted (wrapped by '`' characters at
* beginning and end).
*
* @param name
* The name to check.
* @return True if the given string starts and ends with '`'; false
* otherwise.
*/
public static boolean isQuoted(String name) {
return name != null && name.length() != 0 && name.charAt(0) == '`'
&& name.charAt(name.length() - 1) == '`';
}
/**
* Return a representation of the given name ensuring quoting (wrapped with
* '`' characters). If already wrapped return name.
*
* @param name
* The name to quote.
* @return The quoted version.
*/
public static String quote(String name) {
if (isEmpty(name) || isQuoted(name)) {
return name;
}
// Convert the JPA2 specific quoting character (double quote) to
// Hibernate's (back tick)
else if (name.startsWith("\"") && name.endsWith("\"")) {
name = name.substring(1, name.length() - 1);
}
return new StringBuilder(name.length() + 2).append('`').append(name)
.append('`').toString();
}
/**
* Return the unquoted version of name (stripping the start and end '`'
* characters if present).
*
* @param name
* The name to be unquoted.
* @return The unquoted version.
*/
public static String unquote(String name) {
return isQuoted(name) ? name.substring(1, name.length() - 1) : name;
}
/**
* Determine if the given name is quoted. It is considered quoted if either:
* <ol>
* <li>starts AND ends with backticks (`)</li>
* <li>starts with dialect-specified
* {@link org.hibernate.dialect.Dialect#openQuote() open-quote} AND ends
* with dialect-specified {@link org.hibernate.dialect.Dialect#closeQuote()
* close-quote}</li>
* </ol>
*
* @param name
* The name to check
* @param dialect
* The dialect (to determine the "real" quoting chars).
*
* @return True if quoted, false otherwise
*/
public static boolean isQuoted(String name, Dialect dialect) {
return name != null
&& name.length() != 0
&& (name.charAt(0) == '`'
&& name.charAt(name.length() - 1) == '`' || name
.charAt(0) == dialect.openQuote()
&& name.charAt(name.length() - 1) == dialect
.closeQuote());
}
/**
* Return the unquoted version of name stripping the start and end quote
* characters.
*
* @param name
* The name to be unquoted.
* @param dialect
* The dialect (to determine the "real" quoting chars).
*
* @return The unquoted version.
*/
public static String unquote(String name, Dialect dialect) {
return isQuoted(name, dialect) ? name.substring(1, name.length() - 1)
: name;
}
/**
* Return the unquoted version of name stripping the start and end quote
* characters.
*
* @param names
* The names to be unquoted.
* @param dialect
* The dialect (to determine the "real" quoting chars).
*
* @return The unquoted versions.
*/
public static String[] unquote(String[] names, Dialect dialect) {
if (names == null) {
return null;
}
String[] unquoted = new String[names.length];
for (int i = 0; i < names.length; i++) {
unquoted[i] = unquote(names[i], dialect);
}
return unquoted;
}
/**
* Blob字段的通用转换 注意可能出现乱码
*
* @return 转好的字符串,
* **/
public String BlobToString(Blob blob) {
StringBuffer str = new StringBuffer();
// 使用StringBuffer进行拼接
InputStream in = null;// 输入字节流
try {
in = blob.getBinaryStream();
// 一般接下来是把in的字节流写入一个文件中,但这里直接放进字符串
byte[] buff = new byte[(int) blob.length()];
// byte[] buff=new byte[1024];
// byte[] b = new byte[blob.getBufferSize()];
for (int i = 0; (i = in.read(buff)) > 0;) {
str = str.append(new String(buff));
}
return str.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
System.out.println("转换异常");
e.printStackTrace();
}
}
return null;
}
/**
* Clob字段的通用转换
*
* @return 转好的字符串,
* **/
public static String ClobToString(Clob clob) throws SQLException,
IOException {
String reString = ""; // 拼接变量
Reader is = clob.getCharacterStream();// 得到流
BufferedReader br = new BufferedReader(is);
String s = br.readLine();
StringBuffer sb = new StringBuffer();
while (s != null) {
sb.append(s);
s = br.readLine();
}
reString = sb.toString(); // 转换成字符串,进行返回
return reString;
}
public static String Html2Text(String inputString) {
String htmlStr = inputString; // 含html标签的字符串
String textStr = "";
java.util.regex.Pattern p_script;
java.util.regex.Matcher m_script;
java.util.regex.Pattern p_style;
java.util.regex.Matcher m_style;
java.util.regex.Pattern p_html;
java.util.regex.Matcher m_html;
java.util.regex.Pattern p_html1;
java.util.regex.Matcher m_html1;
try {
String regEx_script = "<[//s]*?script[^>]*?>[//s//S]*?<[//s]*?///[//s]*?script[//s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[//s//S]*?<///script>
String regEx_style = "<[//s]*?style[^>]*?>[//s//S]*?<[//s]*?///[//s]*?style[//s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[//s//S]*?<///style>
String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
String regEx_html1 = "<[^>]+";
p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll(""); // 过滤script标签
p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll(""); // 过滤style标签
p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll(""); // 过滤html标签
p_html1 = Pattern.compile(regEx_html1, Pattern.CASE_INSENSITIVE);
m_html1 = p_html1.matcher(htmlStr);
htmlStr = m_html1.replaceAll(""); // 过滤html标签
textStr = htmlStr;
} catch (Exception e) {
System.err.println("Html2Text: " + e.getMessage());
}
return textStr;// 返回文本字符串
}
@SuppressWarnings("deprecation")
public int getDutyDays(String strStartDate, String strEndDate) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = null;
Date endDate = null;
try {
startDate = df.parse(strStartDate);
endDate = df.parse(strEndDate);
} catch (ParseException e) {
System.out.println("非法的日期格式,无法进行转换");
e.printStackTrace();
}
int result = 0;
while (startDate.compareTo(endDate) <= 0) {
if (startDate.getDay() != 6 && startDate.getDay() != 0)
result++;
startDate.setDate(startDate.getDate() + 1);
}
return result;
}
}
* Copyright 2014, Brook. All rights reserved.
*/
package brook.common.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import org.hibernate.dialect.Dialect;
import org.hibernate.internal.util.collections.ArrayHelper;
public class StringUtil {
private static String[] straChineseUnit = { "分", "角", "圆", "拾", "佰", "仟",
"万", "拾", "佰", "仟", "亿", "拾", "佰", "仟" };
private static String[] straChineseNumber = { "零", "壹", "贰", "叁", "肆", "伍",
"陆", "柒", "捌", "玖" };
private static final int ALIAS_TRUNCATE_LENGTH = 10;
public static final String WHITESPACE = " \n\r\f\t";
private StringUtil() { /* static methods only - hide constructor */
}
public static String randomString(int length) {
StringBuilder sb = new StringBuilder(length);
Random rand = new Random();
for (int i = 0; i < length; ++i) {
int r = rand.nextInt(63);
if (r >= 37)
sb.append((char) (97 + r - 37));
else if (r == 36)
sb.append('_');
else if (r >= 10)
sb.append((char) (65 + r - 10));
else
sb.append((char) (48 + r));
}
return sb.toString();
}
public static boolean isNullOrSpace(String str) {
return ((str == null) || ("".equals(str)) || ("".equals(str.trim())));
}
public static final boolean isNotEmpty(String s) {
return (!(isEmpty(s)));
}
public static final boolean isEmpty(String s) {
if ((s == null) || (s.length() == 0))
return true;
for (int i = s.length() - 1; i >= 0; --i)
if (!(Character.isSpaceChar(s.charAt(i))))
return false;
return true;
}
/*public static boolean isNotEmpty(String string) {
return string != null && string.length() > 0;
}
public static boolean isEmpty(String string) {
return string == null || string.length() == 0;
}*/
public static byte[] hexStrToBytes(String hex) {
if (hex.length() % 2 != 0)
hex = '0' + hex;
byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < hex.length(); i += 2)
bytes[(i / 2)] = Integer.valueOf(hex.substring(i, i + 2), 16)
.byteValue();
return bytes;
}
public static String bytesToHexStr(byte[] bytes) {
StringBuffer buf = new StringBuffer();
String stmp = null;
for (int i = 0; i < bytes.length; ++i) {
stmp = Integer.toHexString(bytes[i] & 0xFF);
if (stmp.length() == 1)
buf.append('0');
buf.append(stmp);
}
return buf.toString().toUpperCase();
}
public static String concat(String[] strings) {
int capacity = 0;
for (int i = 0; i < strings.length; ++i)
capacity += strings[i].length();
StringBuilder sb = new StringBuilder(capacity);
for (int i = 0; i < strings.length; ++i)
sb.append(strings[i]);
return sb.toString();
}
public static String trimToSize(String src, int bytes) {
return trimToSize(src, bytes, null);
}
public static String trimToSize(String src, int bytes, String suffix) {
byte[] arr = src.getBytes();
if (arr.length <= bytes)
return src;
boolean hasSuffix = (suffix != null) && (suffix.length() > 0);
if (hasSuffix)
bytes -= suffix.getBytes().length;
int i = bytes - 1;
while ((i >= 0) && (arr[i] < 0))
--i;
if ((bytes - 1 - i & 0x1) == 1)
--bytes;
String str = new String(arr, 0, bytes);
return ((hasSuffix) ? str + suffix : str);
}
public static String fillAtLeft(String str, int totalLength, char ch) {
int count = totalLength - str.length();
if (count < 0)
throw new IllegalArgumentException(
"string length is great than total length");
StringBuilder buf = new StringBuilder(totalLength);
for (int i = 0; i < count; ++i)
buf.append(ch);
return str;
}
public static String fillToLength(int value, int length) {
String str = String.valueOf(value);
if (str.length() > length)
throw new RuntimeException("number overflow");
return fillAtLeft(str, length, '0');
}
public static String toCnCurrency(String number) {
return numberToChinse(new BigDecimal(number));
}
public static String toCnCurrency(double number) {
return numberToChinse(new BigDecimal(number));
}
public static String toCnCurrency(long number) {
return numberToChinse(new BigDecimal(number));
}
@Deprecated
/**
* 废弃,因为第228行有错误
*/
public static String numberToChinse(BigDecimal bigdMoneyNumber) {
String strChineseCurrency = "";
boolean bZero = true;
int ChineseUnitIndex = 0;
try {
if (bigdMoneyNumber.intValue() == 0) {
return "零圆整";
}
double doubMoneyNumber = Math
.round(bigdMoneyNumber.doubleValue() * 100.0D);
boolean bNegative = doubMoneyNumber < 0D;
doubMoneyNumber = Math.abs(doubMoneyNumber);
while (doubMoneyNumber > 0D) {
if ((ChineseUnitIndex == 2)
&& (strChineseCurrency.length() == 0)) {
strChineseCurrency = strChineseCurrency + "整";
}
if (doubMoneyNumber % 10.0D > 0D) {
strChineseCurrency = straChineseNumber[((int) doubMoneyNumber % 10)]
+ straChineseUnit[ChineseUnitIndex]
+ strChineseCurrency;
bZero = false;
} else {
if (ChineseUnitIndex == 2) {
if (doubMoneyNumber > 0D) {
strChineseCurrency = straChineseUnit[ChineseUnitIndex]
+ strChineseCurrency;
bZero = true;
}
} else if ((((ChineseUnitIndex == 6) || (ChineseUnitIndex == 10)))
&& (doubMoneyNumber % 1000.0D > 0D)) {
strChineseCurrency = straChineseUnit[ChineseUnitIndex]
+ strChineseCurrency;
}
if (!(bZero))
strChineseCurrency = straChineseNumber[0]
+ strChineseCurrency;
bZero = true;
}
doubMoneyNumber = Math.floor(doubMoneyNumber / 10.0D);
++ChineseUnitIndex;
}
if (!(bNegative))
// break label312;
strChineseCurrency = "负" + strChineseCurrency;
} catch (Exception e) {
e.printStackTrace();
return "";
}
label312: return strChineseCurrency;
}
public static String stringToHtml(String str) {
char ch;
if (str == null)
return "";
int len = str.length();
StringBuilder htm = new StringBuilder(len + len / 10);
for (int i = 0; i < len; ++i) {
ch = str.charAt(i);
switch (ch) {
case '<':
htm.append("<");
break;
case '>':
htm.append(">");
break;
case '&':
htm.append("&");
break;
case '"':
htm.append(""");
break;
case ' ':
htm.append(" ");
break;
case '\t':
htm.append(" ");
break;
case '\n':
htm.append("<br>");
break;
case '\r':
break;
default:
htm.append(ch);
}
}
return htm.toString();
}
public static String stringToXml(String str) {
char ch;
if (str == null)
return "";
int len = str.length();
StringBuilder xml = new StringBuilder(len + len / 10);
for (int i = 0; i < len; ++i) {
ch = str.charAt(i);
switch (ch) {
case '<':
xml.append("<");
break;
case '>':
xml.append(">");
break;
case '&':
xml.append("&");
break;
case '"':
xml.append(""");
break;
default:
xml.append(ch);
}
}
return xml.toString();
}
public static String htmlToString(String html) {
html = html.replaceAll(" ", " ");
html = html.replaceAll(""", "\"");
html = html.replaceAll("&", "&");
html = html.replaceAll("<", "<");
html = html.replaceAll(">", ">");
html = html.replaceAll("&", "&");
html = html.replaceAll("®", "(R)");
html = html.replaceAll("©", "(C)");
html = html.replaceAll(" ", "\t");
html = html.replaceAll(" ", "\t");
return html.replaceAll("™", "TM");
}
public static String toSQLString(String str) {
int len = str.length();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; ++i) {
char ch = str.charAt(i);
if (ch == '\'')
sb.append("\\'");
else if (ch == '"')
sb.append("\\\"");
else if (ch == ';')
sb.append("\\;");
else
sb.append(ch);
}
return sb.toString();
}
public static String toJsonString(String str) {
char ch;
int len = str.length();
StringBuilder sb = new StringBuilder(len + 16);
for (int i = 0; i < len; ++i) {
ch = str.charAt(i);
switch (ch) {
case '\'':
sb.append("\\'");
break;
case '"':
sb.append("\\\"");
break;
case '\n':
sb.append("\\n");
break;
case '\\':
sb.append("\\\\");
break;
default:
sb.append(ch);
}
}
return sb.toString();
}
/*
* public static boolean containsDigits(String string) { for ( int i=0;
* i<string.length(); i++ ) { if ( Character.isDigit( string.charAt(i) ) )
* return true; } return false; }
*/
public static int lastIndexOfLetter(String string) {
for (int i = 0; i < string.length(); i++) {
char character = string.charAt(i);
if (!Character.isLetter(character) /* && !('_'==character) */)
return i - 1;
}
return string.length() - 1;
}
public static String join(String seperator, String[] strings) {
int length = strings.length;
if (length == 0)
return "";
StringBuilder buf = new StringBuilder(length * strings[0].length())
.append(strings[0]);
for (int i = 1; i < length; i++) {
buf.append(seperator).append(strings[i]);
}
return buf.toString();
}
public static String join(String seperator, Iterator objects) {
StringBuilder buf = new StringBuilder();
if (objects.hasNext())
buf.append(objects.next());
while (objects.hasNext()) {
buf.append(seperator).append(objects.next());
}
return buf.toString();
}
public static String[] add(String[] x, String sep, String[] y) {
String[] result = new String[x.length];
for (int i = 0; i < x.length; i++) {
result[i] = x[i] + sep + y[i];
}
return result;
}
public static String repeat(String string, int times) {
StringBuilder buf = new StringBuilder(string.length() * times);
for (int i = 0; i < times; i++)
buf.append(string);
return buf.toString();
}
public static String repeat(char character, int times) {
char[] buffer = new char[times];
Arrays.fill(buffer, character);
return new String(buffer);
}
public static String replace(String template, String placeholder,
String replacement) {
return replace(template, placeholder, replacement, false);
}
public static String[] replace(String templates[], String placeholder,
String replacement) {
String[] result = new String[templates.length];
for (int i = 0; i < templates.length; i++) {
result[i] = replace(templates[i], placeholder, replacement);
}
return result;
}
public static String replace(String template, String placeholder,
String replacement, boolean wholeWords) {
return replace(template, placeholder, replacement, wholeWords, false);
}
public static String replace(String template, String placeholder,
String replacement, boolean wholeWords,
boolean encloseInParensIfNecessary) {
if (template == null) {
return template;
}
int loc = template.indexOf(placeholder);
if (loc < 0) {
return template;
} else {
String beforePlaceholder = template.substring(0, loc);
String afterPlaceholder = template.substring(loc
+ placeholder.length());
return replace(beforePlaceholder, afterPlaceholder, placeholder,
replacement, wholeWords, encloseInParensIfNecessary);
}
}
public static String replace(String beforePlaceholder,
String afterPlaceholder, String placeholder, String replacement,
boolean wholeWords, boolean encloseInParensIfNecessary) {
final boolean actuallyReplace = !wholeWords
|| afterPlaceholder.length() == 0
|| !Character.isJavaIdentifierPart(afterPlaceholder.charAt(0));
boolean encloseInParens = actuallyReplace && encloseInParensIfNecessary
&& !(getLastNonWhitespaceCharacter(beforePlaceholder) == '(')
&& !(getFirstNonWhitespaceCharacter(afterPlaceholder) == ')');
StringBuilder buf = new StringBuilder(beforePlaceholder);
if (encloseInParens) {
buf.append('(');
}
buf.append(actuallyReplace ? replacement : placeholder);
if (encloseInParens) {
buf.append(')');
}
buf.append(replace(afterPlaceholder, placeholder, replacement,
wholeWords, encloseInParensIfNecessary));
return buf.toString();
}
public static char getLastNonWhitespaceCharacter(String str) {
if (str != null && str.length() > 0) {
for (int i = str.length() - 1; i >= 0; i--) {
char ch = str.charAt(i);
if (!Character.isWhitespace(ch)) {
return ch;
}
}
}
return '\0';
}
public static char getFirstNonWhitespaceCharacter(String str) {
if (str != null && str.length() > 0) {
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (!Character.isWhitespace(ch)) {
return ch;
}
}
}
return '\0';
}
public static String replaceOnce(String template, String placeholder,
String replacement) {
if (template == null) {
return template; // returnign null!
}
int loc = template.indexOf(placeholder);
if (loc < 0) {
return template;
} else {
return new StringBuilder(template.substring(0, loc))
.append(replacement)
.append(template.substring(loc + placeholder.length()))
.toString();
}
}
public static String[] split(String seperators, String list) {
return split(seperators, list, false);
}
public static String[] split(String seperators, String list, boolean include) {
StringTokenizer tokens = new StringTokenizer(list, seperators, include);
String[] result = new String[tokens.countTokens()];
int i = 0;
while (tokens.hasMoreTokens()) {
result[i++] = tokens.nextToken();
}
return result;
}
public static String unqualify(String qualifiedName) {
int loc = qualifiedName.lastIndexOf(".");
return (loc < 0) ? qualifiedName : qualifiedName.substring(loc + 1);
}
public static String qualifier(String qualifiedName) {
int loc = qualifiedName.lastIndexOf(".");
return (loc < 0) ? "" : qualifiedName.substring(0, loc);
}
/**
* Collapses a name. Mainly intended for use with classnames, where an
* example might serve best to explain. Imagine you have a class named
* <samp>'org.hibernate.internal.util.StringHelper'</samp>; calling collapse
* on that classname will result in <samp>'o.h.u.StringHelper'<samp>.
*
* @param name
* The name to collapse.
* @return The collapsed name.
*/
public static String collapse(String name) {
if (name == null) {
return null;
}
int breakPoint = name.lastIndexOf('.');
if (breakPoint < 0) {
return name;
}
return collapseQualifier(name.substring(0, breakPoint), true)
+ name.substring(breakPoint); // includes last '.'
}
/**
* Given a qualifier, collapse it.
*
* @param qualifier
* The qualifier to collapse.
* @param includeDots
* Should we include the dots in the collapsed form?
*
* @return The collapsed form.
*/
public static String collapseQualifier(String qualifier, boolean includeDots) {
StringTokenizer tokenizer = new StringTokenizer(qualifier, ".");
String collapsed = Character.toString(tokenizer.nextToken().charAt(0));
while (tokenizer.hasMoreTokens()) {
if (includeDots) {
collapsed += '.';
}
collapsed += tokenizer.nextToken().charAt(0);
}
return collapsed;
}
/**
* Partially unqualifies a qualified name. For example, with a base of
* 'org.hibernate' the name 'org.hibernate.internal.util.StringHelper' would
* become 'util.StringHelper'.
*
* @param name
* The (potentially) qualified name.
* @param qualifierBase
* The qualifier base.
*
* @return The name itself, or the partially unqualified form if it begins
* with the qualifier base.
*/
public static String partiallyUnqualify(String name, String qualifierBase) {
if (name == null || !name.startsWith(qualifierBase)) {
return name;
}
return name.substring(qualifierBase.length() + 1); // +1 to start after
// the following '.'
}
/**
* Cross between {@link #collapse} and {@link #partiallyUnqualify}.
* Functions much like {@link #collapse} except that only the qualifierBase
* is collapsed. For example, with a base of 'org.hibernate' the name
* 'org.hibernate.internal.util.StringHelper' would become
* 'o.h.util.StringHelper'.
*
* @param name
* The (potentially) qualified name.
* @param qualifierBase
* The qualifier base.
*
* @return The name itself if it does not begin with the qualifierBase, or
* the properly collapsed form otherwise.
*/
public static String collapseQualifierBase(String name, String qualifierBase) {
if (name == null || !name.startsWith(qualifierBase)) {
return collapse(name);
}
return collapseQualifier(qualifierBase, true)
+ name.substring(qualifierBase.length());
}
public static String[] suffix(String[] columns, String suffix) {
if (suffix == null)
return columns;
String[] qualified = new String[columns.length];
for (int i = 0; i < columns.length; i++) {
qualified[i] = suffix(columns[i], suffix);
}
return qualified;
}
private static String suffix(String name, String suffix) {
return (suffix == null) ? name : name + suffix;
}
public static String root(String qualifiedName) {
int loc = qualifiedName.indexOf(".");
return (loc < 0) ? qualifiedName : qualifiedName.substring(0, loc);
}
public static String unroot(String qualifiedName) {
int loc = qualifiedName.indexOf(".");
return (loc < 0) ? qualifiedName : qualifiedName.substring(loc + 1,
qualifiedName.length());
}
public static boolean booleanValue(String tfString) {
String trimmed = tfString.trim().toLowerCase();
return trimmed.equals("true") || trimmed.equals("t");
}
public static String toString(Object[] array) {
int len = array.length;
if (len == 0)
return "";
StringBuilder buf = new StringBuilder(len * 12);
for (int i = 0; i < len - 1; i++) {
buf.append(array[i]).append(", ");
}
return buf.append(array[len - 1]).toString();
}
public static String[] multiply(String string, Iterator placeholders,
Iterator replacements) {
String[] result = new String[] { string };
while (placeholders.hasNext()) {
result = multiply(result, (String) placeholders.next(),
(String[]) replacements.next());
}
return result;
}
private static String[] multiply(String[] strings, String placeholder,
String[] replacements) {
String[] results = new String[replacements.length * strings.length];
int n = 0;
for (int i = 0; i < replacements.length; i++) {
for (int j = 0; j < strings.length; j++) {
results[n++] = replaceOnce(strings[j], placeholder,
replacements[i]);
}
}
return results;
}
public static int countUnquoted(String string, char character) {
if ('\'' == character) {
throw new IllegalArgumentException(
"Unquoted count of quotes is invalid");
}
if (string == null)
return 0;
// Impl note: takes advantage of the fact that an escpaed single quote
// embedded within a quote-block can really be handled as two seperate
// quote-blocks for the purposes of this method...
int count = 0;
int stringLength = string.length();
boolean inQuote = false;
for (int indx = 0; indx < stringLength; indx++) {
char c = string.charAt(indx);
if (inQuote) {
if ('\'' == c) {
inQuote = false;
}
} else if ('\'' == c) {
inQuote = true;
} else if (c == character) {
count++;
}
}
return count;
}
public static int[] locateUnquoted(String string, char character) {
if ('\'' == character) {
throw new IllegalArgumentException(
"Unquoted count of quotes is invalid");
}
if (string == null) {
return new int[0];
}
ArrayList locations = new ArrayList(20);
// Impl note: takes advantage of the fact that an escpaed single quote
// embedded within a quote-block can really be handled as two seperate
// quote-blocks for the purposes of this method...
int stringLength = string.length();
boolean inQuote = false;
for (int indx = 0; indx < stringLength; indx++) {
char c = string.charAt(indx);
if (inQuote) {
if ('\'' == c) {
inQuote = false;
}
} else if ('\'' == c) {
inQuote = true;
} else if (c == character) {
locations.add(indx);
}
}
return ArrayHelper.toIntArray(locations);
}
public static String qualify(String prefix, String name) {
if (name == null || prefix == null) {
throw new NullPointerException();
}
return new StringBuilder(prefix.length() + name.length() + 1)
.append(prefix).append('.').append(name).toString();
}
public static String[] qualify(String prefix, String[] names) {
if (prefix == null)
return names;
int len = names.length;
String[] qualified = new String[len];
for (int i = 0; i < len; i++) {
qualified[i] = qualify(prefix, names[i]);
}
return qualified;
}
public static int firstIndexOfChar(String sqlString, String string,
int startindex) {
int matchAt = -1;
for (int i = 0; i < string.length(); i++) {
int curMatch = sqlString.indexOf(string.charAt(i), startindex);
if (curMatch >= 0) {
if (matchAt == -1) { // first time we find match!
matchAt = curMatch;
} else {
matchAt = Math.min(matchAt, curMatch);
}
}
}
return matchAt;
}
public static String truncate(String string, int length) {
if (string.length() <= length) {
return string;
} else {
return string.substring(0, length);
}
}
public static String generateAlias(String description) {
return generateAliasRoot(description) + '_';
}
/**
* Generate a nice alias for the given class name or collection role name
* and unique integer. Subclasses of Loader do <em>not</em> have to use
* aliases of this form.
*
* @param description
* The base name (usually an entity-name or collection-role)
* @param unique
* A uniquing value
*
* @return an alias of the form <samp>foo1_</samp>
*/
public static String generateAlias(String description, int unique) {
return generateAliasRoot(description) + Integer.toString(unique) + '_';
}
/**
* Generates a root alias by truncating the "root name" defined by the
* incoming decription and removing/modifying any non-valid alias
* characters.
*
* @param description
* The root name from which to generate a root alias.
* @return The generated root alias.
*/
private static String generateAliasRoot(String description) {
String result = truncate(unqualifyEntityName(description),
ALIAS_TRUNCATE_LENGTH).toLowerCase().replace('/', '_') // entityNames
// may
// now
// include
// slashes
// for
// the
// representations
.replace('$', '_'); // classname may be an inner class
result = cleanAlias(result);
if (Character.isDigit(result.charAt(result.length() - 1))) {
return result + "x"; // ick!
} else {
return result;
}
}
/**
* Clean the generated alias by removing any non-alpha characters from the
* beginning.
*
* @param alias
* The generated alias to be cleaned.
* @return The cleaned alias, stripped of any leading non-alpha characters.
*/
private static String cleanAlias(String alias) {
char[] chars = alias.toCharArray();
// short cut check...
if (!Character.isLetter(chars[0])) {
for (int i = 1; i < chars.length; i++) {
// as soon as we encounter our first letter, return the
// substring
// from that position
if (Character.isLetter(chars[i])) {
return alias.substring(i);
}
}
}
return alias;
}
public static String unqualifyEntityName(String entityName) {
String result = unqualify(entityName);
int slashPos = result.indexOf('/');
if (slashPos > 0) {
result = result.substring(0, slashPos - 1);
}
return result;
}
public static String toUpperCase(String str) {
return str == null ? null : str.toUpperCase();
}
public static String toLowerCase(String str) {
return str == null ? null : str.toLowerCase();
}
public static String moveAndToBeginning(String filter) {
if (filter.trim().length() > 0) {
filter += " and ";
if (filter.startsWith(" and "))
filter = filter.substring(4);
}
return filter;
}
/**
* Determine if the given string is quoted (wrapped by '`' characters at
* beginning and end).
*
* @param name
* The name to check.
* @return True if the given string starts and ends with '`'; false
* otherwise.
*/
public static boolean isQuoted(String name) {
return name != null && name.length() != 0 && name.charAt(0) == '`'
&& name.charAt(name.length() - 1) == '`';
}
/**
* Return a representation of the given name ensuring quoting (wrapped with
* '`' characters). If already wrapped return name.
*
* @param name
* The name to quote.
* @return The quoted version.
*/
public static String quote(String name) {
if (isEmpty(name) || isQuoted(name)) {
return name;
}
// Convert the JPA2 specific quoting character (double quote) to
// Hibernate's (back tick)
else if (name.startsWith("\"") && name.endsWith("\"")) {
name = name.substring(1, name.length() - 1);
}
return new StringBuilder(name.length() + 2).append('`').append(name)
.append('`').toString();
}
/**
* Return the unquoted version of name (stripping the start and end '`'
* characters if present).
*
* @param name
* The name to be unquoted.
* @return The unquoted version.
*/
public static String unquote(String name) {
return isQuoted(name) ? name.substring(1, name.length() - 1) : name;
}
/**
* Determine if the given name is quoted. It is considered quoted if either:
* <ol>
* <li>starts AND ends with backticks (`)</li>
* <li>starts with dialect-specified
* {@link org.hibernate.dialect.Dialect#openQuote() open-quote} AND ends
* with dialect-specified {@link org.hibernate.dialect.Dialect#closeQuote()
* close-quote}</li>
* </ol>
*
* @param name
* The name to check
* @param dialect
* The dialect (to determine the "real" quoting chars).
*
* @return True if quoted, false otherwise
*/
public static boolean isQuoted(String name, Dialect dialect) {
return name != null
&& name.length() != 0
&& (name.charAt(0) == '`'
&& name.charAt(name.length() - 1) == '`' || name
.charAt(0) == dialect.openQuote()
&& name.charAt(name.length() - 1) == dialect
.closeQuote());
}
/**
* Return the unquoted version of name stripping the start and end quote
* characters.
*
* @param name
* The name to be unquoted.
* @param dialect
* The dialect (to determine the "real" quoting chars).
*
* @return The unquoted version.
*/
public static String unquote(String name, Dialect dialect) {
return isQuoted(name, dialect) ? name.substring(1, name.length() - 1)
: name;
}
/**
* Return the unquoted version of name stripping the start and end quote
* characters.
*
* @param names
* The names to be unquoted.
* @param dialect
* The dialect (to determine the "real" quoting chars).
*
* @return The unquoted versions.
*/
public static String[] unquote(String[] names, Dialect dialect) {
if (names == null) {
return null;
}
String[] unquoted = new String[names.length];
for (int i = 0; i < names.length; i++) {
unquoted[i] = unquote(names[i], dialect);
}
return unquoted;
}
/**
* Blob字段的通用转换 注意可能出现乱码
*
* @return 转好的字符串,
* **/
public String BlobToString(Blob blob) {
StringBuffer str = new StringBuffer();
// 使用StringBuffer进行拼接
InputStream in = null;// 输入字节流
try {
in = blob.getBinaryStream();
// 一般接下来是把in的字节流写入一个文件中,但这里直接放进字符串
byte[] buff = new byte[(int) blob.length()];
// byte[] buff=new byte[1024];
// byte[] b = new byte[blob.getBufferSize()];
for (int i = 0; (i = in.read(buff)) > 0;) {
str = str.append(new String(buff));
}
return str.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
System.out.println("转换异常");
e.printStackTrace();
}
}
return null;
}
/**
* Clob字段的通用转换
*
* @return 转好的字符串,
* **/
public static String ClobToString(Clob clob) throws SQLException,
IOException {
String reString = ""; // 拼接变量
Reader is = clob.getCharacterStream();// 得到流
BufferedReader br = new BufferedReader(is);
String s = br.readLine();
StringBuffer sb = new StringBuffer();
while (s != null) {
sb.append(s);
s = br.readLine();
}
reString = sb.toString(); // 转换成字符串,进行返回
return reString;
}
public static String Html2Text(String inputString) {
String htmlStr = inputString; // 含html标签的字符串
String textStr = "";
java.util.regex.Pattern p_script;
java.util.regex.Matcher m_script;
java.util.regex.Pattern p_style;
java.util.regex.Matcher m_style;
java.util.regex.Pattern p_html;
java.util.regex.Matcher m_html;
java.util.regex.Pattern p_html1;
java.util.regex.Matcher m_html1;
try {
String regEx_script = "<[//s]*?script[^>]*?>[//s//S]*?<[//s]*?///[//s]*?script[//s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[//s//S]*?<///script>
String regEx_style = "<[//s]*?style[^>]*?>[//s//S]*?<[//s]*?///[//s]*?style[//s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[//s//S]*?<///style>
String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
String regEx_html1 = "<[^>]+";
p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll(""); // 过滤script标签
p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll(""); // 过滤style标签
p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll(""); // 过滤html标签
p_html1 = Pattern.compile(regEx_html1, Pattern.CASE_INSENSITIVE);
m_html1 = p_html1.matcher(htmlStr);
htmlStr = m_html1.replaceAll(""); // 过滤html标签
textStr = htmlStr;
} catch (Exception e) {
System.err.println("Html2Text: " + e.getMessage());
}
return textStr;// 返回文本字符串
}
@SuppressWarnings("deprecation")
public int getDutyDays(String strStartDate, String strEndDate) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = null;
Date endDate = null;
try {
startDate = df.parse(strStartDate);
endDate = df.parse(strEndDate);
} catch (ParseException e) {
System.out.println("非法的日期格式,无法进行转换");
e.printStackTrace();
}
int result = 0;
while (startDate.compareTo(endDate) <= 0) {
if (startDate.getDay() != 6 && startDate.getDay() != 0)
result++;
startDate.setDate(startDate.getDate() + 1);
}
return result;
}
}