001: package liquibase.util;
002:
003: import java.util.ArrayList;
004: import java.util.Collection;
005: import java.util.List;
006:
007: /**
008: * Various utility methods for working with strings.
009: */
010: public class StringUtils {
011: public static String trimToEmpty(String string) {
012: if (string == null) {
013: return "";
014: }
015: return string.trim();
016: }
017:
018: public static String trimToNull(String string) {
019: if (string == null) {
020: return null;
021: }
022: String returnString = string.trim();
023: if (returnString.length() == 0) {
024: return null;
025: } else {
026: return returnString;
027: }
028: }
029:
030: /**
031: * Removes any comments from multiple line SQL using {@link #stripComments(String)}
032: * and then extracts each individual statement using {@link #splitSQL(String)}.
033: *
034: * @param multiLineSQL A String containing all the SQL statements
035: * @param stripComments If true then comments will be stripped, if false then they will be left in the code
036: */
037: public static String[] processMutliLineSQL(String multiLineSQL,
038: boolean stripComments) {
039:
040: String stripped = stripComments ? stripComments(multiLineSQL)
041: : multiLineSQL;
042: return splitSQL(stripped);
043: }
044:
045: /**
046: * Splits a (possible) multi-line SQL statement along ;'s and "go"'s.
047: */
048: public static String[] splitSQL(String multiLineSQL) {
049: return multiLineSQL
050: .split(";\\s*\n|;$|\n[gG][oO]\\s*\n|\n[Gg][oO]$");
051: }
052:
053: /**
054: * Searches through a String which contains SQL code and strips out
055: * any comments that are between \/**\/ or anything that matches
056: * SP--SP<text>\n (to support the ANSI standard commenting of --
057: * at the end of a line).
058: *
059: * @return The String without the comments in
060: */
061: public static String stripComments(String multiLineSQL) {
062: String strippedSingleLines = multiLineSQL.replaceAll(
063: "\\s--\\s.*", "");
064: return strippedSingleLines.replaceAll("/\\*[\n\\S\\s]*\\*/",
065: "\n");
066: }
067:
068: public static String join(Collection<String> collection,
069: String delimiter) {
070: if (collection == null) {
071: return null;
072: }
073:
074: if (collection.size() == 0) {
075: return "";
076: }
077:
078: StringBuffer buffer = new StringBuffer();
079: for (String val : collection) {
080: buffer.append(val).append(delimiter);
081: }
082:
083: String returnString = buffer.toString();
084: return returnString.substring(0, returnString.length()
085: - delimiter.length());
086: }
087:
088: public static List<String> splitAndTrim(String s, String regex) {
089: if (s == null) {
090: return null;
091: }
092: List<String> returnList = new ArrayList<String>();
093: for (String string : s.split(regex)) {
094: returnList.add(string.trim());
095: }
096:
097: return returnList;
098:
099: }
100: }
|