0
# Utilities
1
2
Utility classes for string manipulation, time handling, encoding, and other common operations used throughout the driver.
3
4
**WARNING: Most utilities documented in this file are internal implementation classes located in `com.mysql.cj.util` and other core-impl packages. These are NOT part of the official public API and may change without notice between versions. Use at your own risk. Only rely on public API interfaces from `com.mysql.cj.jdbc` and `com.mysql.cj.xdevapi` packages for stable, supported functionality.**
5
6
## Capabilities
7
8
### String Utilities
9
10
Comprehensive string manipulation utilities.
11
12
```java { .api }
13
package com.mysql.cj.util;
14
15
public class StringUtils {
16
// String to byte array conversion
17
public static String toString(byte[] bytes);
18
public static String toString(byte[] bytes, int offset, int length);
19
public static String toString(byte[] bytes, String encoding);
20
public static String toString(byte[] bytes, int offset, int length, String encoding);
21
22
public static byte[] getBytes(String s);
23
public static byte[] getBytes(String s, String encoding);
24
public static byte[] getBytes(char[] chars);
25
public static byte[] getBytes(char[] chars, String encoding);
26
27
// String checks
28
public static boolean isNullOrEmpty(String str);
29
public static boolean isEmptyOrWhitespaceOnly(String str);
30
31
// Comment stripping
32
public static String stripComments(String src, String stringOpens, String stringCloses,
33
boolean slashStarComments, boolean slashSlashComments,
34
boolean hashComments, boolean dashDashComments);
35
36
// Case-insensitive operations
37
public static int indexOfIgnoreCase(String searchIn, String searchFor);
38
public static int indexOfIgnoreCase(int startingPosition, String searchIn, String searchFor);
39
public static int lastIndexOfIgnoreCase(String searchIn, String searchFor);
40
public static boolean startsWithIgnoreCase(String searchIn, String searchFor);
41
public static boolean endsWithIgnoreCase(String searchIn, String searchFor);
42
43
// String splitting
44
public static List<String> split(String stringVal, String delimiter, boolean trim);
45
public static String[] split(String stringVal, String delimiter, String markers,
46
String markerCloses, boolean trim);
47
48
// String joining
49
public static String join(Collection<?> collection, String delimiter);
50
public static String join(Object[] array, String delimiter);
51
52
// Escaping
53
public static String escapeQuote(String x, String quoteChar);
54
55
// Wildcards
56
public static String wildcardCompareToRegex(String wildcard);
57
58
// Padding
59
public static String padString(String stringVal, int length);
60
public static String safeTrim(String toTrim);
61
62
// Other utilities
63
public static boolean isValidIdChar(char c);
64
public static String stripEnclosure(String source, String prefix, String suffix);
65
public static String getUniqueSavepointId();
66
}
67
```
68
69
Usage:
70
71
```java
72
// Convert strings to bytes with encoding
73
byte[] bytes = StringUtils.getBytes("Hello", "UTF-8");
74
String str = StringUtils.toString(bytes, "UTF-8");
75
76
// Check if string is null or empty
77
if (StringUtils.isNullOrEmpty(userName)) {
78
throw new IllegalArgumentException("Username required");
79
}
80
81
// Case-insensitive search
82
int index = StringUtils.indexOfIgnoreCase("SELECT * FROM users", "from");
83
84
// Split string
85
List<String> parts = StringUtils.split("host1,host2,host3", ",", true);
86
87
// Join strings
88
String joined = StringUtils.join(parts, ", ");
89
90
// Strip SQL comments
91
String sql = "SELECT * FROM users /* comment */ WHERE id = 1";
92
String stripped = StringUtils.stripComments(sql, "'\"", "'\"", true, true, true, true);
93
```
94
95
### String Inspector
96
97
Advanced string inspection with marker support.
98
99
```java { .api }
100
package com.mysql.cj.util;
101
102
public class StringInspector {
103
// Constructor - requires all parameters for full marker-aware parsing
104
public StringInspector(String source, String openingMarkers, String closingMarkers,
105
String overridingMarkers, Set<SearchMode> defaultSearchMode);
106
107
// Search methods
108
public int indexOfIgnoreCase(String searchFor, Set<SearchMode> searchMode);
109
110
public int indexOf(String searchFor);
111
112
// Character checks
113
public boolean startsWith(String searchFor);
114
public char charAt(int index);
115
116
// Length
117
public int length();
118
}
119
120
public enum SearchMode {
121
ALLOW_BACKSLASH_ESCAPE,
122
SKIP_BETWEEN_MARKERS,
123
SKIP_BLOCK_COMMENTS,
124
SKIP_LINE_COMMENTS,
125
SKIP_WHITE_SPACE;
126
}
127
```
128
129
Usage:
130
131
```java
132
import java.util.EnumSet;
133
134
String sql = "SELECT * FROM users WHERE name = 'O''Reilly'";
135
// Full constructor with opening markers, closing markers, overriding markers, and search modes
136
StringInspector inspector = new StringInspector(sql, "'\"", "'\"", "",
137
EnumSet.of(SearchMode.SKIP_BETWEEN_MARKERS));
138
139
// Find WHERE keyword ignoring string literals
140
int wherePos = inspector.indexOfIgnoreCase("WHERE",
141
EnumSet.of(SearchMode.SKIP_BETWEEN_MARKERS));
142
```
143
144
### Time Utilities
145
146
Date and time conversion utilities.
147
148
**Note:** TimeUtil is primarily an internal implementation class. For date/time conversion, most applications should use standard `java.sql` types and ResultSet methods (`getTimestamp()`, `getDate()`, `getTime()`) which handle conversions automatically.
149
150
```java { .api }
151
package com.mysql.cj.util;
152
153
public class TimeUtil {
154
// Time adjustment methods (internal use - adjust times between calendars/timezones)
155
public static Time adjustTime(Time time, Calendar fromCal, Calendar toCal);
156
public static Timestamp adjustTimestamp(Timestamp timestamp, Calendar fromCal, Calendar toCal);
157
public static Timestamp adjustTimestamp(Timestamp timestamp, TimeZone fromTz, TimeZone toTz);
158
159
// Timezone utilities
160
public static TimeZone getCanonicalTimeZone(String timezoneStr);
161
}
162
```
163
164
Usage:
165
166
```java
167
// Adjust timezone (internal implementation detail - normally handled by driver)
168
TimeZone serverTz = TimeZone.getTimeZone("UTC");
169
TimeZone clientTz = TimeZone.getTimeZone("America/New_York");
170
Timestamp ts = new Timestamp(System.currentTimeMillis());
171
Timestamp adjusted = TimeUtil.adjustTimestamp(ts, serverTz, clientTz);
172
```
173
174
### Base64 Decoder
175
176
Base64 decoding utility.
177
178
```java { .api }
179
package com.mysql.cj.util;
180
181
public class Base64Decoder {
182
// Constructor
183
public Base64Decoder();
184
185
// Decode operations
186
public byte[] decode(byte[] base64Data, int offset, int length);
187
}
188
```
189
190
Usage:
191
192
```java
193
Base64Decoder decoder = new Base64Decoder();
194
String base64 = "SGVsbG8gV29ybGQ=";
195
byte[] base64Bytes = base64.getBytes("UTF-8");
196
byte[] decoded = decoder.decode(base64Bytes, 0, base64Bytes.length);
197
String text = new String(decoded, "UTF-8"); // "Hello World"
198
```
199
200
### DNS SRV Utilities
201
202
DNS SRV record lookup and sorting.
203
204
```java { .api }
205
package com.mysql.cj.util;
206
207
public class DnsSrv {
208
// SRV record representation
209
public static class SrvRecord {
210
public String getHost();
211
public int getPort();
212
public int getPriority();
213
public int getWeight();
214
}
215
216
// Lookup SRV records
217
public static List<SrvRecord> lookupSrvRecords(String serviceName);
218
219
// Sort SRV records according to RFC 2782
220
public static List<SrvRecord> sortSrvRecords(List<SrvRecord> records);
221
}
222
```
223
224
Usage:
225
226
```java
227
// Lookup MySQL SRV records
228
List<DnsSrv.SrvRecord> records = DnsSrv.lookupSrvRecords("_mysql._tcp.example.com");
229
230
// Sort by priority and weight
231
List<DnsSrv.SrvRecord> sorted = DnsSrv.sortSrvRecords(records);
232
233
for (DnsSrv.SrvRecord record : sorted) {
234
System.out.println(record.getHost() + ":" + record.getPort() +
235
" (priority: " + record.getPriority() +
236
", weight: " + record.getWeight() + ")");
237
}
238
```
239
240
### LRU Cache
241
242
Least Recently Used cache implementation.
243
244
```java { .api }
245
package com.mysql.cj.util;
246
247
public class LRUCache<K, V> {
248
// Constructor
249
public LRUCache(int maxElements);
250
251
// Cache operations
252
public void put(K key, V value);
253
public V get(K key);
254
public void clear();
255
public int size();
256
public void remove(K key);
257
}
258
```
259
260
Usage:
261
262
```java
263
// Create LRU cache for prepared statements
264
LRUCache<String, PreparedStatement> stmtCache = new LRUCache<>(100);
265
266
// Cache prepared statement
267
stmtCache.put(sql, pstmt);
268
269
// Retrieve from cache
270
PreparedStatement cached = stmtCache.get(sql);
271
if (cached != null) {
272
// Reuse cached statement
273
}
274
```
275
276
### Data Type Utilities
277
278
Utilities for data type manipulation.
279
280
```java { .api }
281
package com.mysql.cj.util;
282
283
public class DataTypeUtil {
284
// JDBC type mapping
285
public static int getJdbcType(String mysqlType);
286
public static String getJavaClassName(int jdbcType);
287
288
// Character encoding
289
public static String getJavaEncodingFromMysqlCharset(String mysqlCharset);
290
public static String getMysqlCharsetFromJavaEncoding(String javaEncoding);
291
292
// Type checks
293
public static boolean isNumericalType(int jdbcType);
294
public static boolean isCharacterType(int jdbcType);
295
public static boolean isBinaryType(int jdbcType);
296
public static boolean isDateTimeType(int jdbcType);
297
}
298
```
299
300
Usage:
301
302
```java
303
// Convert MySQL type to JDBC type
304
int jdbcType = DataTypeUtil.getJdbcType("VARCHAR");
305
306
// Get Java class for JDBC type
307
String javaClass = DataTypeUtil.getJavaClassName(Types.VARCHAR);
308
309
// Character set conversion
310
String javaEncoding = DataTypeUtil.getJavaEncodingFromMysqlCharset("utf8mb4");
311
```
312
313
### Escape Tokenizer
314
315
Tokenizer for JDBC escape sequences.
316
317
```java { .api }
318
package com.mysql.cj.util;
319
320
public class EscapeTokenizer {
321
// Constructor
322
public EscapeTokenizer(String s);
323
324
// Tokenization
325
public boolean hasMoreTokens();
326
public String nextToken();
327
public char getLastChar();
328
}
329
```
330
331
Usage:
332
333
```java
334
String sql = "{call myproc(?, ?)}";
335
EscapeTokenizer tokenizer = new EscapeTokenizer(sql);
336
337
while (tokenizer.hasMoreTokens()) {
338
String token = tokenizer.nextToken();
339
// Process token
340
}
341
```
342
343
### Lazy String
344
345
Lazy string evaluation for efficient memory usage.
346
347
```java { .api }
348
package com.mysql.cj.util;
349
350
public class LazyString {
351
// Constructor
352
public LazyString(byte[] buffer, int offset, int length, String encoding);
353
354
// String operations
355
public String toString();
356
public int length();
357
}
358
```
359
360
### SASLprep
361
362
SASL string preparation (RFC 4013).
363
364
```java { .api }
365
package com.mysql.cj.util;
366
367
public class SaslPrep {
368
// Prepare string according to SASLprep profile
369
public static String prepare(String str);
370
public static String prepare(String str, boolean allowUnassigned);
371
}
372
```
373
374
Usage:
375
376
```java
377
// Prepare password for SASL authentication
378
String password = "pässwörd";
379
String prepared = SaslPrep.prepare(password);
380
```
381
382
### Sequential ID Lease
383
384
Sequential ID allocation for connection pools.
385
386
```java { .api }
387
package com.mysql.cj.util;
388
389
public class SequentialIdLease {
390
// Constructor
391
public SequentialIdLease();
392
393
// Allocate ID
394
public int allocate();
395
396
// Release ID
397
public void release(int id);
398
}
399
```
400
401
Usage:
402
403
```java
404
SequentialIdLease idLease = new SequentialIdLease();
405
406
// Allocate ID for new connection
407
int connId = idLease.allocate();
408
409
// Use connection...
410
411
// Release ID when connection closed
412
idLease.release(connId);
413
```
414
415
### Utility Methods
416
417
General utility methods.
418
419
```java { .api }
420
package com.mysql.cj.util;
421
422
public class Util {
423
// Version checks
424
public static boolean isJdbc4();
425
public static boolean isJdbc42();
426
427
// Stack trace
428
public static String stackTraceToString(Throwable t);
429
430
// MySQL edition checks
431
public static boolean isCommunityEdition(String serverVersion);
432
public static boolean isEnterpriseEdition(String serverVersion);
433
434
// System properties
435
public static String getSystemProperty(String key);
436
437
// Class loading
438
public static <T> T getInstance(String className, Class<T> interfaceClass);
439
}
440
```
441
442
### Log Utilities
443
444
See logging-monitoring.md for LogUtils details.
445
446
### Test Utilities
447
448
Utilities for testing (not for production use).
449
450
```java { .api }
451
package com.mysql.cj.util;
452
453
public class TestUtils {
454
// Get properties from test suite
455
public static Properties getPropertiesFromTestsuiteUrl();
456
457
// Build test URL
458
public static String getBuildTestUrl(Properties props);
459
460
// Get test connection
461
public static Connection getConnection() throws SQLException;
462
463
// Check if running in test environment
464
public static boolean isRunningOnTestServer();
465
}
466
```
467
468
### Per-VM Server Config Cache Factory
469
470
Factory for creating server configuration caches.
471
472
```java { .api }
473
package com.mysql.cj.util;
474
475
public class PerVmServerConfigCacheFactory {
476
// Get or create cache for server
477
public static CacheAdapter<String, Map<String, String>> getCacheAdapter(String serverConfigCacheKey);
478
}
479
```
480