/
FormatUtils.java
345 lines (294 loc) · 12.1 KB
/
FormatUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/**
* Licensed to JumpMind Inc under one or more contributor
* license agreements. See the NOTICE file distributed
* with this work for additional information regarding
* copyright ownership. JumpMind Inc licenses this file
* to you under the GNU General Public License, version 3.0 (GPLv3)
* (the "License"); you may not use this file except in compliance
* with the License.
*
* You should have received a copy of the GNU General Public License,
* version 3.0 (GPLv3) along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jumpmind.util;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.jumpmind.exception.ParseException;
public final class FormatUtils {
public static final String[] TIMESTAMP_PATTERNS = { "yyyy-MM-dd HH:mm:ss.S",
"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd HH:mm", "yyyy-MM-dd",
"HH:mm:ss.S", "HH:mm:ss" };
public static final String[] TIME_PATTERNS = { "HH:mm:ss.S", "HH:mm:ss",
"yyyy-MM-dd HH:mm:ss.S", "yyyy-MM-dd HH:mm:ss" };
public static final FastDateFormat TIMESTAMP_FORMATTER = FastDateFormat
.getInstance("yyyy-MM-dd HH:mm:ss.SSS");
public static final FastDateFormat TIME_FORMATTER = FastDateFormat.getInstance("HH:mm:ss.SSS");
public final static String WILDCARD = "*";
public final static String NEGATE_TOKEN = "!";
public final static int MAX_CHARS_TO_LOG = 1000;
private static Pattern pattern = Pattern.compile("\\$\\((.+?)\\)");
private static boolean isInfamousTurkey = false;
static {
isInfamousTurkey = Locale.getDefault().getCountry().equalsIgnoreCase("tr");
}
private FormatUtils() {
}
public static String replace(String prop, String replaceWith, String sourceString) {
return StringUtils.replace(sourceString, "$(" + prop + ")", replaceWith);
}
public static String replaceToken(String text, String tokenToReplace, String replaceWithText,
boolean matchUsingPrefixSuffix) {
Map<String, String> replacements = new HashMap<String, String>(1);
replacements.put(tokenToReplace, replaceWithText);
return replaceTokens(text, replacements, matchUsingPrefixSuffix);
}
/**
* Replace the keys found in the target text with the values found in the
* replacements map.
*
* @param text
* The text to replace
* @param replacements
* The map that contains the replacement values
* @param matchUsingPrefixSuffix
* If true, look for the $(key) pattern to replace. If false,
* just replace the key outright.
* @return The text with the token keys replaced
*/
public static String replaceTokens(String text, Map<String, String> replacements,
boolean matchUsingPrefixSuffix) {
if (text != null && replacements != null && replacements.size() > 0) {
if (matchUsingPrefixSuffix) {
Matcher matcher = pattern.matcher(text);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
String[] match = matcher.group(1).split("\\|");
String replacement = replacements.get(match[0]);
if (replacement != null) {
matcher.appendReplacement(buffer, "");
if (match.length == 2) {
replacement = formatString(match[1], replacement);
}
buffer.append(replacement);
}
}
matcher.appendTail(buffer);
text = buffer.toString();
} else {
for (Object key : replacements.keySet()) {
text = text.replaceAll(key.toString(), replacements.get(key));
}
}
}
return text;
}
public static String formatString(String format, String arg) {
if (format.indexOf("d") >= 0 || format.indexOf("u") >= 0 || format.indexOf("i") >= 0) {
return String.format(format, Long.parseLong(arg));
} else if (format.indexOf("e") >= 0 || format.indexOf("f") >= 0) {
return String.format(format, Double.valueOf(arg));
} else {
return String.format(format, arg);
}
}
public static boolean toBoolean(String value) {
if (StringUtils.isNotBlank(value)) {
if (value.equals("1")) {
return true;
} else if (value.equals("0")) {
return false;
} else {
return Boolean.parseBoolean(value);
}
} else {
return false;
}
}
public static boolean isMixedCase(String text) {
char[] chars = text.toCharArray();
boolean upper = false;
boolean lower = false;
for (char ch : chars) {
upper |= Character.isUpperCase(ch);
lower |= Character.isLowerCase(ch);
}
return upper && lower;
}
public static boolean isWildCardMatch(String text, String pattern, boolean ignoreCase) {
boolean match = isWildCardMatch(text, pattern);
if (ignoreCase && !match) {
match = isWildCardMatch(text.toLowerCase(), pattern);
if (!match) {
match = isWildCardMatch(text.toUpperCase(), pattern);
}
}
return match;
}
public static boolean isWildCardMatch(String text, String pattern) {
boolean match = true;
if (pattern.startsWith(NEGATE_TOKEN)) {
pattern = pattern.substring(1);
}
// Create the cards by splitting using a RegEx. If more speed
// is desired, a simpler character based splitting can be done.
String[] cards = pattern.split("\\" + WILDCARD);
for(int i = 0; i < cards.length; i++) {
String card = cards[i];
boolean foundToken = false;
if (i == 0 && !pattern.startsWith("*")) {
foundToken = text.startsWith(card);
} else {
foundToken = text.indexOf(card) != -1;
}
// Card not detected in the text.
if (!foundToken) {
return !match;
}
// Move ahead, towards the right of the text.
text = text.substring(text.indexOf(card) + card.length());
}
return match;
}
/**
* Word wrap a string where the line size for the first line is different
* than the lines sizes for the other lines.
*
* @param str
* @param firstLineSize
* @param nonFirstLineSize
* @return
*/
public static String[] wordWrap(String str, int firstLineSize, int nonFirstLineSize) {
String[] lines = wordWrap(str, firstLineSize);
if (lines.length > 1 && firstLineSize != nonFirstLineSize) {
// More than one line. Re-wrap the non-first lines with the non
// first line size
String notFirstLinesString = StringUtils.join(lines, " ", 1, lines.length);
String[] nonFirstLines = wordWrap(notFirstLinesString, nonFirstLineSize);
List<String> nonFirstLineCollection = Arrays.asList(nonFirstLines);
ArrayList<String> allLines = new ArrayList<String>();
allLines.add(lines[0]);
allLines.addAll(nonFirstLineCollection);
lines = allLines.toArray(lines);
}
return lines;
}
public static String[] wordWrap(String str, int lineSize) {
if (str != null && str.length() > lineSize) {
Pattern regex = Pattern.compile("(\\S\\S{" + lineSize + ",}|.{1," + lineSize
+ "})(\\s+|$)");
List<String> list = new ArrayList<String>();
Matcher m = regex.matcher(str);
while (m.find()) {
String group = m.group();
// Preserve multiple newlines
String[] lines = StringUtils.splitPreserveAllTokens(group, '\n');
for (String line : lines) {
// Trim whitespace from end since a space on the end can
// push line wrap and cause an unintentional blank line.
line = StringUtils.removeEnd(line, " ");
list.add(line);
}
}
return (String[]) list.toArray(new String[list.size()]);
} else {
return new String[] { str };
}
}
public static String abbreviateForLogging(String value) {
if (value != null) {
value = value.trim();
}
return StringUtils.abbreviate(value, MAX_CHARS_TO_LOG);
}
public static Date parseDate(String str, String[] parsePatterns) {
return parseDate(str, parsePatterns, null);
}
public static Date parseDate(String str, String[] parsePatterns, TimeZone timeZone) {
if (str == null || parsePatterns == null) {
throw new IllegalArgumentException("Date and Patterns must not be null");
}
SimpleDateFormat parser = null;
ParsePosition pos = new ParsePosition(0);
for (int i = 0; i < parsePatterns.length; i++) {
if (i == 0) {
parser = new SimpleDateFormat(parsePatterns[0]);
if (timeZone != null) {
parser.setTimeZone(timeZone);
}
} else {
parser.applyPattern(parsePatterns[i]);
}
pos.setIndex(0);
Date date = parser.parse(str, pos);
if (date != null && pos.getIndex() == str.length()) {
return date;
}
}
try {
Date date = new Date(Long.parseLong(str));
return date;
} catch (NumberFormatException e) {
}
throw new ParseException("Unable to parse the date: " + str);
}
public static String[] splitOnSpacePreserveQuotedStrings(String source) {
List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'");
Matcher regexMatcher = regex.matcher(source);
while (regexMatcher.find()) {
if (regexMatcher.group(1) != null) {
// Add double-quoted string without the quotes
matchList.add(regexMatcher.group(1));
} else if (regexMatcher.group(2) != null) {
// Add single-quoted string without the quotes
matchList.add(regexMatcher.group(2));
} else {
// Add unquoted word
matchList.add(regexMatcher.group());
}
}
return matchList.toArray(new String[matchList.size()]);
}
public static String replaceCharsToShortenName(String name) {
return name.replaceAll("[^a-zA-Z0-9_]|[a|e|i|o|u|A|E|I|O|U]", "");
}
public static String lower(String str) {
if (isInfamousTurkey) {
return str.toLowerCase(Locale.US);
}
return str.toLowerCase();
}
public static String upper(String str) {
if (isInfamousTurkey) {
return str.toUpperCase(Locale.US);
}
return str.toUpperCase();
}
public static boolean isInfamousTurkey() {
return isInfamousTurkey;
}
public static String stripTurkeyDottedI(String str) {
return str.replace("\u0130", "I").replace("\u0131", "i");
}
}