You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

StringUtils.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. /*
  2. * Copyright 2004-2011 H2 Group.
  3. * Copyright 2011 James Moger.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package com.iciql.util;
  18. import java.io.BufferedReader;
  19. import java.io.File;
  20. import java.io.FileInputStream;
  21. import java.io.InputStreamReader;
  22. import java.io.UnsupportedEncodingException;
  23. import java.nio.charset.Charset;
  24. import java.security.MessageDigest;
  25. import java.security.NoSuchAlgorithmException;
  26. import java.util.ArrayList;
  27. /**
  28. * Common string utilities.
  29. */
  30. public class StringUtils {
  31. /**
  32. * Replace all occurrences of the before string with the after string.
  33. *
  34. * @param s the string
  35. * @param before the old text
  36. * @param after the new text
  37. * @return the string with the before string replaced
  38. */
  39. public static String replaceAll(String s, String before, String after) {
  40. int next = s.indexOf(before);
  41. if (next < 0) {
  42. return s;
  43. }
  44. StringBuilder buff = new StringBuilder(s.length() - before.length() + after.length());
  45. int index = 0;
  46. while (true) {
  47. buff.append(s.substring(index, next)).append(after);
  48. index = next + before.length();
  49. next = s.indexOf(before, index);
  50. if (next < 0) {
  51. buff.append(s.substring(index));
  52. break;
  53. }
  54. }
  55. return buff.toString();
  56. }
  57. /**
  58. * Check if a String is null or empty (the length is null).
  59. *
  60. * @param s the string to check
  61. * @return true if it is null or empty
  62. */
  63. public static boolean isNullOrEmpty(String s) {
  64. return s == null || s.length() == 0;
  65. }
  66. /**
  67. * Convert a string to a Java literal using the correct escape sequences.
  68. * The literal is not enclosed in double quotes. The result can be used in
  69. * properties files or in Java source code.
  70. *
  71. * @param s the text to convert
  72. * @return the Java representation
  73. */
  74. public static String javaEncode(String s) {
  75. int length = s.length();
  76. StringBuilder buff = new StringBuilder(length);
  77. for (int i = 0; i < length; i++) {
  78. char c = s.charAt(i);
  79. switch (c) {
  80. // case '\b':
  81. // // BS backspace
  82. // // not supported in properties files
  83. // buff.append("\\b");
  84. // break;
  85. case '\t':
  86. // HT horizontal tab
  87. buff.append("\\t");
  88. break;
  89. case '\n':
  90. // LF linefeed
  91. buff.append("\\n");
  92. break;
  93. case '\f':
  94. // FF form feed
  95. buff.append("\\f");
  96. break;
  97. case '\r':
  98. // CR carriage return
  99. buff.append("\\r");
  100. break;
  101. case '"':
  102. // double quote
  103. buff.append("\\\"");
  104. break;
  105. case '\\':
  106. // backslash
  107. buff.append("\\\\");
  108. break;
  109. default:
  110. int ch = c & 0xffff;
  111. if (ch >= ' ' && (ch < 0x80)) {
  112. buff.append(c);
  113. // not supported in properties files
  114. // } else if(ch < 0xff) {
  115. // buff.append("\\");
  116. // // make sure it's three characters (0x200 is octal 1000)
  117. // buff.append(Integer.toOctalString(0x200 |
  118. // ch).substring(1));
  119. } else {
  120. buff.append("\\u");
  121. // make sure it's four characters
  122. buff.append(Integer.toHexString(0x10000 | ch).substring(1));
  123. }
  124. }
  125. }
  126. return buff.toString();
  127. }
  128. /**
  129. * Pad a string. This method is used for the SQL function RPAD and LPAD.
  130. *
  131. * @param string the original string
  132. * @param n the target length
  133. * @param padding the padding string
  134. * @param right true if the padding should be appended at the end
  135. * @return the padded string
  136. */
  137. public static String pad(String string, int n, String padding, boolean right) {
  138. if (n < 0) {
  139. n = 0;
  140. }
  141. if (n < string.length()) {
  142. return string.substring(0, n);
  143. } else if (n == string.length()) {
  144. return string;
  145. }
  146. char paddingChar;
  147. if (padding == null || padding.length() == 0) {
  148. paddingChar = ' ';
  149. } else {
  150. paddingChar = padding.charAt(0);
  151. }
  152. StringBuilder buff = new StringBuilder(n);
  153. n -= string.length();
  154. if (right) {
  155. buff.append(string);
  156. }
  157. for (int i = 0; i < n; i++) {
  158. buff.append(paddingChar);
  159. }
  160. if (!right) {
  161. buff.append(string);
  162. }
  163. return buff.toString();
  164. }
  165. /**
  166. * Convert a string to a SQL literal. Null is converted to NULL. The text is
  167. * enclosed in single quotes. If there are any special characters, the
  168. * method STRINGDECODE is used.
  169. *
  170. * @param s the text to convert.
  171. * @return the SQL literal
  172. */
  173. public static String quoteStringSQL(String s) {
  174. if (s == null) {
  175. return "NULL";
  176. }
  177. int length = s.length();
  178. StringBuilder buff = new StringBuilder(length + 2);
  179. buff.append('\'');
  180. for (int i = 0; i < length; i++) {
  181. char c = s.charAt(i);
  182. if (c == '\'') {
  183. buff.append(c);
  184. } else if (c < ' ' || c > 127) {
  185. // need to start from the beginning because maybe there was a \
  186. // that was not quoted
  187. return "STRINGDECODE(" + quoteStringSQL(javaEncode(s)) + ")";
  188. }
  189. buff.append(c);
  190. }
  191. buff.append('\'');
  192. return buff.toString();
  193. }
  194. /**
  195. * Split a string into an array of strings using the given separator. A null
  196. * string will result in a null array, and an empty string in a zero element
  197. * array.
  198. *
  199. * @param s the string to split
  200. * @param separatorChar the separator character
  201. * @param trim whether each element should be trimmed
  202. * @return the array list
  203. */
  204. public static String[] arraySplit(String s, char separatorChar, boolean trim) {
  205. if (s == null) {
  206. return null;
  207. }
  208. int length = s.length();
  209. if (length == 0) {
  210. return new String[0];
  211. }
  212. ArrayList<String> list = Utils.newArrayList();
  213. StringBuilder buff = new StringBuilder(length);
  214. for (int i = 0; i < length; i++) {
  215. char c = s.charAt(i);
  216. if (c == separatorChar) {
  217. String e = buff.toString();
  218. list.add(trim ? e.trim() : e);
  219. buff.setLength(0);
  220. } else if (c == '\\' && i < length - 1) {
  221. buff.append(s.charAt(++i));
  222. } else {
  223. buff.append(c);
  224. }
  225. }
  226. String e = buff.toString();
  227. list.add(trim ? e.trim() : e);
  228. String[] array = new String[list.size()];
  229. list.toArray(array);
  230. return array;
  231. }
  232. /**
  233. * Calculates the SHA1 of the string.
  234. *
  235. * @param text
  236. * @return sha1 of the string
  237. */
  238. public static String calculateSHA1(String text) {
  239. try {
  240. byte[] bytes = text.getBytes("iso-8859-1");
  241. return calculateSHA1(bytes);
  242. } catch (UnsupportedEncodingException u) {
  243. throw new RuntimeException(u);
  244. }
  245. }
  246. /**
  247. * Calculates the SHA1 of the byte array.
  248. *
  249. * @param bytes
  250. * @return sha1 of the byte array
  251. */
  252. public static String calculateSHA1(byte[] bytes) {
  253. try {
  254. MessageDigest md = MessageDigest.getInstance("SHA-1");
  255. md.update(bytes, 0, bytes.length);
  256. byte[] digest = md.digest();
  257. StringBuilder sb = new StringBuilder(digest.length * 2);
  258. for (int i = 0; i < digest.length; i++) {
  259. if (((int) digest[i] & 0xff) < 0x10) {
  260. sb.append('0');
  261. }
  262. sb.append(Integer.toHexString((int) digest[i] & 0xff));
  263. }
  264. return sb.toString();
  265. } catch (NoSuchAlgorithmException t) {
  266. throw new RuntimeException(t);
  267. }
  268. }
  269. /**
  270. * Counts the occurrences of char c in the given string.
  271. *
  272. * @param c the character to count
  273. * @param value the source string
  274. * @return the count of c in value
  275. */
  276. public static int count(char c, String value) {
  277. int count = 0;
  278. for (char cv : value.toCharArray()) {
  279. if (cv == c) {
  280. count++;
  281. }
  282. }
  283. return count;
  284. }
  285. /**
  286. * Prepare text for html presentation. Replace sensitive characters with
  287. * html entities.
  288. *
  289. * @param inStr
  290. * @param changeSpace
  291. * @return plain text escaped for html
  292. */
  293. public static String escapeForHtml(String inStr, boolean changeSpace) {
  294. StringBuffer retStr = new StringBuffer();
  295. int i = 0;
  296. while (i < inStr.length()) {
  297. if (inStr.charAt(i) == '&') {
  298. retStr.append("&amp;");
  299. } else if (inStr.charAt(i) == '<') {
  300. retStr.append("&lt;");
  301. } else if (inStr.charAt(i) == '>') {
  302. retStr.append("&gt;");
  303. } else if (inStr.charAt(i) == '\"') {
  304. retStr.append("&quot;");
  305. } else if (changeSpace && inStr.charAt(i) == ' ') {
  306. retStr.append("&nbsp;");
  307. } else if (changeSpace && inStr.charAt(i) == '\t') {
  308. retStr.append(" &nbsp; &nbsp;");
  309. } else {
  310. retStr.append(inStr.charAt(i));
  311. }
  312. i++;
  313. }
  314. return retStr.toString();
  315. }
  316. /**
  317. * Replaces carriage returns and line feeds with html line breaks.
  318. *
  319. * @param string
  320. * @return plain text with html line breaks
  321. */
  322. public static String breakLinesForHtml(String string) {
  323. return string.replace("\r\n", "<br/>").replace("\r", "<br/>").replace("\n", "<br/>");
  324. }
  325. /**
  326. * Returns the string content of the specified file.
  327. *
  328. * @param file
  329. * @param lineEnding
  330. * @return the string content of the file
  331. */
  332. public static String readContent(File file, String lineEnding) {
  333. StringBuilder sb = new StringBuilder();
  334. try {
  335. InputStreamReader is = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"));
  336. BufferedReader reader = new BufferedReader(is);
  337. String line = null;
  338. while ((line = reader.readLine()) != null) {
  339. sb.append(line);
  340. if (lineEnding != null) {
  341. sb.append(lineEnding);
  342. }
  343. }
  344. reader.close();
  345. } catch (Throwable t) {
  346. System.err.println("Failed to read content of " + file.getAbsolutePath());
  347. t.printStackTrace();
  348. }
  349. return sb.toString();
  350. }
  351. }