0
# Utility Classes & Helpers
1
2
The AWS Java SDK Core provides comprehensive utility classes for common operations including string manipulation, I/O operations, encoding/decoding, hashing, JSON processing, and validation.
3
4
## Core Utilities
5
6
### String Utilities
7
8
```java { .api }
9
// String manipulation utilities
10
class StringUtils {
11
// Null/empty checks
12
public static boolean isNullOrEmpty(String value);
13
public static boolean hasValue(String str);
14
public static String trim(String value);
15
public static String defaultString(String str);
16
public static String defaultString(String str, String defaultStr);
17
18
// String operations
19
public static String join(String delimiter, String... strings);
20
public static String join(String delimiter, Collection<String> strings);
21
public static String[] split(String toSplit, char splitChar);
22
public static String lowerCase(String str);
23
public static String upperCase(String str);
24
25
// Replacement operations
26
public static String replace(String originalString, String partToMatch, String replacement);
27
public static String replaceAll(String originalString, String partToMatch, String replacement);
28
29
// Comparison operations
30
public static boolean equals(String str1, String str2);
31
public static boolean equalsIgnoreCase(String str1, String str2);
32
33
// Encoding/decoding
34
public static String urlEncode(String url, boolean keepPathSlash);
35
public static String urlDecode(String url);
36
public static byte[] utf8(String str);
37
public static String fromUtf8(byte[] bytes);
38
39
// Validation
40
public static void assertNotNullOrEmpty(String value, String fieldName);
41
public static void assertStringNotEmpty(String value, String fieldName);
42
}
43
```
44
45
### I/O Utilities
46
47
```java { .api }
48
// Input/output stream utilities
49
class IOUtils {
50
// Stream to byte array conversion
51
public static byte[] toByteArray(InputStream input) throws IOException;
52
public static byte[] toByteArray(InputStream input, long length) throws IOException;
53
54
// Stream to string conversion
55
public static String toString(InputStream input) throws IOException;
56
public static String toString(InputStream input, String encoding) throws IOException;
57
58
// Resource management
59
public static void closeQuietly(Closeable closeable);
60
public static void closeQuietly(Closeable... closeables);
61
62
// Stream operations
63
public static long copy(InputStream input, OutputStream output) throws IOException;
64
public static void drainInputStream(InputStream inputStream);
65
66
// Buffer operations
67
public static InputStream toInputStream(String input);
68
public static InputStream toInputStream(byte[] input);
69
70
// Release operations
71
public static void release(Closeable is, Level level);
72
}
73
```
74
75
### Binary Utilities
76
77
```java { .api }
78
// Binary data utilities
79
class BinaryUtils {
80
// Base64 encoding/decoding
81
public static String toBase64(byte[] data);
82
public static byte[] fromBase64(String b64Data);
83
public static String toBase64(ByteBuffer data);
84
public static ByteBuffer fromBase64(String b64Data, ByteBuffer byteBuffer);
85
86
// Hex encoding/decoding
87
public static String toHex(byte[] data);
88
public static byte[] fromHex(String hexData);
89
90
// ByteBuffer operations
91
public static ByteBuffer copyBytesFrom(String s);
92
public static ByteBuffer copyBytesFrom(byte[] bytes);
93
public static byte[] copyAllBytesFrom(ByteBuffer bb);
94
public static String toStream(ByteBuffer byteBuffer);
95
96
// Hash operations
97
public static byte[] hash(String text);
98
public static byte[] hash(byte[] data);
99
public static byte[] hash(InputStream input) throws IOException;
100
101
// Comparison operations
102
public static boolean equals(byte[] a, byte[] b);
103
}
104
```
105
106
### Date Utilities
107
108
```java { .api }
109
// Date and time utilities
110
class DateUtils {
111
// Date formatting
112
public static String formatISO8601Date(Date date);
113
public static String formatRFC822Date(Date date);
114
public static String formatUnixTimestamp(Date date);
115
public static String formatServiceSpecificDate(Date date);
116
117
// Date parsing
118
public static Date parseISO8601Date(String dateString);
119
public static Date parseRFC822Date(String dateString);
120
public static Date parseUnixTimestamp(String dateString);
121
public static Date parseServiceSpecificDate(String dateString);
122
public static Date parseCompressedISO8601Date(String dateString);
123
124
// Date operations
125
public static Date cloneDate(Date date);
126
public static long numberOfDaysSinceEpoch(long milliSinceEpoch);
127
128
// Thread-safe date formatters
129
public static final DateFormat ISO8601_DATE_FORMAT;
130
public static final DateFormat RFC822_DATE_FORMAT;
131
public static final DateFormat COMPRESSED_ISO8601_DATE_FORMAT;
132
public static final DateFormat UNIX_TIMESTAMP_FORMAT;
133
}
134
```
135
136
### Validation Utilities
137
138
```java { .api }
139
// Input validation utilities
140
class ValidationUtils {
141
// Null checks
142
public static <T> T assertNotNull(T object, String fieldName) throws IllegalArgumentException;
143
public static void assertNotEmpty(Collection<?> collection, String fieldName) throws IllegalArgumentException;
144
public static void assertNotEmpty(Map<?, ?> map, String fieldName) throws IllegalArgumentException;
145
public static void assertNotEmpty(String string, String fieldName) throws IllegalArgumentException;
146
147
// String validation
148
public static void assertStringNotEmpty(String string, String fieldName) throws IllegalArgumentException;
149
public static String assertStringNotEmpty(String string, String fieldName, String errorMessage) throws IllegalArgumentException;
150
151
// Numeric validation
152
public static void assertIsPositive(int num, String fieldName) throws IllegalArgumentException;
153
public static void assertIsPositive(long num, String fieldName) throws IllegalArgumentException;
154
public static void assertIsPositive(double num, String fieldName) throws IllegalArgumentException;
155
156
// Collection validation
157
public static <T> List<T> assertNotNullOrEmpty(List<T> list, String fieldName) throws IllegalArgumentException;
158
public static <T> T[] assertNotNullOrEmpty(T[] array, String fieldName) throws IllegalArgumentException;
159
160
// Boolean validation
161
public static void assertTrue(boolean expression, String errorMessage) throws IllegalArgumentException;
162
public static void assertFalse(boolean expression, String errorMessage) throws IllegalArgumentException;
163
}
164
```
165
166
## Encoding and Hashing
167
168
### Base Encodings
169
170
```java { .api }
171
// Base16 encoding/decoding
172
class Base16 {
173
public static String encodeAsString(byte[] bytes);
174
public static byte[] encode(byte[] bytes);
175
public static byte[] decode(String b16);
176
public static byte[] decode(byte[] b16);
177
}
178
179
// Base32 encoding/decoding
180
class Base32 {
181
public static String encodeAsString(byte[] bytes);
182
public static byte[] encode(byte[] bytes);
183
public static byte[] decode(String b32);
184
public static byte[] decode(byte[] b32);
185
}
186
187
// Base64 encoding/decoding
188
class Base64 {
189
public static String encodeAsString(byte[] bytes);
190
public static byte[] encode(byte[] bytes);
191
public static byte[] decode(String b64);
192
public static byte[] decode(byte[] b64);
193
public static boolean isBase64(String str);
194
}
195
```
196
197
### MD5 Utilities
198
199
```java { .api }
200
// MD5 hashing utilities
201
class Md5Utils {
202
// MD5 hash computation
203
public static byte[] computeMD5Hash(InputStream is) throws IOException;
204
public static byte[] computeMD5Hash(byte[] input);
205
public static String md5AsBase64(byte[] input);
206
public static String md5AsBase64(InputStream is) throws IOException;
207
208
// MD5 hash validation
209
public static byte[] md5(String text);
210
public static String md5Hex(String text);
211
public static String md5Hex(byte[] data);
212
213
// Stream MD5 computation
214
public static DigestInputStream md5DigestStream(InputStream stream);
215
}
216
```
217
218
## HTTP and Network Utilities
219
220
### HTTP Utilities
221
222
```java { .api }
223
// HTTP utilities for SDK
224
class SdkHttpUtils {
225
// URL encoding/decoding
226
public static String urlEncode(String value, boolean path);
227
public static String urlDecode(String value);
228
public static String encodeParameters(Request<?> request);
229
230
// Header operations
231
public static boolean isValidHostnameForURI(String hostname);
232
public static String appendUri(String baseUri, String path);
233
public static String appendUri(String baseUri, String path, boolean escapeDoubleSlash);
234
235
// Query parameter operations
236
public static Map<String, List<String>> parseQueryString(String queryString);
237
public static String encodeQueryString(Map<String, List<String>> parameters);
238
239
// Content operations
240
public static long getContentLength(Request<?> request);
241
public static InputStream getRequestPayloadStream(Request<?> request);
242
243
// Utility methods
244
public static boolean usePayloadForQueryParameters(Request<?> request);
245
}
246
247
// Runtime HTTP utilities
248
class RuntimeHttpUtils {
249
// Content type operations
250
public static String toContentType(String contentType);
251
public static String toContentEncoding(String contentEncoding);
252
253
// Header utilities
254
public static String fetchUserAgent();
255
public static Map<String, String> convertHeadersToMap(Header[] headers);
256
}
257
258
// AWS hostname utilities
259
class AwsHostNameUtils {
260
// Hostname parsing
261
public static String parseRegionName(String hostname, String serviceHint);
262
public static String parseServiceName(String hostname);
263
public static String parseRegion(String host, String serviceHint);
264
265
// S3 specific utilities
266
public static String parseS3BucketName(String host, String serviceHint);
267
public static boolean isS3USStandardEndpoint(String endpoint);
268
}
269
```
270
271
## JSON Processing
272
273
### JSON Utilities
274
275
```java { .api }
276
// JSON manipulation utilities
277
class JsonUtils {
278
// JSON parsing
279
public static <T> T jsonToObject(String json, Class<T> clazz) throws IOException;
280
public static String objectToJson(Object obj) throws IOException;
281
282
// JSON node operations
283
public static JsonNode getJsonNodeFromJsonText(String json);
284
public static String getStringFromJsonNode(JsonNode node, String key);
285
public static Integer getIntegerFromJsonNode(JsonNode node, String key);
286
public static Boolean getBooleanFromJsonNode(JsonNode node, String key);
287
public static Date getDateFromJsonNode(JsonNode node, String key);
288
289
// JSON validation
290
public static boolean isValidJson(String json);
291
public static void assertValidJson(String json, String fieldName);
292
}
293
294
// Jackson JSON processing utilities
295
class Jackson {
296
// ObjectMapper operations
297
public static final ObjectMapper OBJECT_MAPPER;
298
299
// JSON string operations
300
public static String toJsonString(Object value);
301
public static <T> T fromJsonString(String json, Class<T> valueType);
302
public static <T> T fromJsonString(String json, TypeReference<T> typeReference);
303
304
// JSON pretty printing
305
public static String toJsonPrettyString(Object value);
306
307
// JSON validation
308
public static boolean isValidJson(String json);
309
310
// Stream operations
311
public static JsonGenerator jsonGeneratorOf(OutputStream out) throws IOException;
312
public static JsonParser jsonParserOf(String json) throws IOException;
313
public static JsonParser jsonParserOf(InputStream json) throws IOException;
314
}
315
```
316
317
## Collection and Data Utilities
318
319
### Collection Utilities
320
321
```java { .api }
322
// Collection manipulation utilities
323
class CollectionUtils {
324
// Null/empty checks
325
public static boolean isNullOrEmpty(Collection<?> collection);
326
public static boolean isNullOrEmpty(Map<?, ?> map);
327
328
// Collection operations
329
public static <T> List<T> mergeLists(List<T>... lists);
330
public static <T> Set<T> mergeSets(Set<T>... sets);
331
332
// Map operations
333
public static <K, V> Map<K, V> mergeMaps(Map<K, V>... maps);
334
public static <K, V> void putIfNotNull(Map<K, V> map, K key, V value);
335
336
// Conversion operations
337
public static <T> List<T> join(List<T> list1, List<T> list2);
338
public static String joinWithComma(Collection<String> toJoin);
339
340
// Utility methods
341
public static <T> boolean equals(Collection<T> list1, Collection<T> list2);
342
}
343
```
344
345
### Class Loading Utilities
346
347
```java { .api }
348
// Class loading utilities
349
class Classes {
350
// Class loading
351
public static Class<?> childClassOf(Class<?> childClass, Class<?> parentClass);
352
public static <T> Class<T> jarFileOf(Class<T> klass);
353
354
// Resource loading
355
public static URL getResource(String resource);
356
public static InputStream getResourceAsStream(String resource);
357
358
// Class information
359
public static String getClassName(Class<?> clazz);
360
public static String getClassPath(Class<?> clazz);
361
}
362
```
363
364
## Specialized Utilities
365
366
### Version Information
367
368
```java { .api }
369
// Version information utilities
370
class VersionInfoUtils {
371
// Version retrieval
372
public static String getVersion();
373
public static String getPlatform();
374
public static String getUserAgent();
375
public static String getVersionFromFullVersionString(String fullVersionString);
376
377
// User agent operations
378
public static String formatUserAgent(String clientName, String clientVersion);
379
public static String formatUserAgent(String clientName, String clientVersion,
380
String platformInfo, String languageInfo);
381
}
382
```
383
384
### Input Stream Utilities
385
386
```java { .api }
387
// Fake IO exception for testing
388
class FakeIOException extends IOException {
389
public FakeIOException(String message);
390
}
391
392
// Input stream with length checking
393
class LengthCheckInputStream extends InputStream {
394
public LengthCheckInputStream(InputStream in, long expectedLength, boolean includeSkipped);
395
public int read() throws IOException;
396
public int read(byte[] b, int off, int len) throws IOException;
397
public long skip(long n) throws IOException;
398
public void close() throws IOException;
399
}
400
401
// Input stream with byte counting
402
class CountingInputStream extends FilterInputStream {
403
public CountingInputStream(InputStream in);
404
public long getByteCount();
405
public int read() throws IOException;
406
public int read(byte[] b, int off, int len) throws IOException;
407
public long skip(long n) throws IOException;
408
}
409
```
410
411
### SDK Runtime
412
413
```java { .api }
414
// SDK runtime utilities
415
class SdkRuntime {
416
// Runtime information
417
public static String getApplicationName();
418
public static String getApplicationVersion();
419
public static String getClientName();
420
public static String getClientVersion();
421
422
// System information
423
public static String getJavaVersion();
424
public static String getJavaVendor();
425
public static String getJavaVmName();
426
public static String getJavaVmVersion();
427
public static String getOsName();
428
public static String getOsVersion();
429
public static String getOsArch();
430
431
// User agent construction
432
public static String getUserAgent();
433
public static String getUserAgentFromClientName(String clientName);
434
}
435
```
436
437
### Timestamp Formatting
438
439
```java { .api }
440
// Timestamp format utilities
441
class TimestampFormat {
442
// Timestamp formats
443
public static final String ISO_8601 = "iso8601";
444
public static final String UNIX_TIMESTAMP = "unixTimestamp";
445
public static final String RFC_822 = "rfc822";
446
447
// Format operations
448
public static String format(String format, Date date);
449
public static Date parse(String format, String dateString);
450
public static boolean isValidFormat(String format);
451
452
// Validation
453
public static void validateFormat(String format);
454
}
455
```
456
457
## Usage Examples
458
459
### String Operations
460
461
```java
462
import com.amazonaws.util.StringUtils;
463
464
// Basic string operations
465
String input = " Hello World ";
466
boolean isEmpty = StringUtils.isNullOrEmpty(input); // false
467
String trimmed = StringUtils.trim(input); // "Hello World"
468
String defaultValue = StringUtils.defaultString(null, "N/A"); // "N/A"
469
470
// String joining and splitting
471
String[] parts = {"Hello", "World", "AWS"};
472
String joined = StringUtils.join(", ", parts); // "Hello, World, AWS"
473
String[] split = StringUtils.split("a,b,c", ','); // ["a", "b", "c"]
474
475
// URL encoding
476
String url = "https://example.com/path with spaces";
477
String encoded = StringUtils.urlEncode(url, true); // Keep path slashes
478
String decoded = StringUtils.urlDecode(encoded);
479
480
// UTF-8 operations
481
byte[] utf8Bytes = StringUtils.utf8("Hello World");
482
String utf8String = StringUtils.fromUtf8(utf8Bytes);
483
484
// Validation
485
try {
486
StringUtils.assertNotNullOrEmpty(input, "input");
487
StringUtils.assertStringNotEmpty(trimmed, "trimmed");
488
} catch (IllegalArgumentException e) {
489
System.err.println("Validation failed: " + e.getMessage());
490
}
491
```
492
493
### I/O Operations
494
495
```java
496
import com.amazonaws.util.IOUtils;
497
import java.io.*;
498
499
// Stream to byte array conversion
500
try (InputStream inputStream = new FileInputStream("example.txt")) {
501
byte[] content = IOUtils.toByteArray(inputStream);
502
String contentString = IOUtils.toString(new ByteArrayInputStream(content));
503
504
// Create input stream from string
505
InputStream stringStream = IOUtils.toInputStream("Hello World");
506
507
// Copy streams
508
try (OutputStream output = new FileOutputStream("copy.txt")) {
509
long bytesCopied = IOUtils.copy(stringStream, output);
510
System.out.println("Copied " + bytesCopied + " bytes");
511
}
512
} catch (IOException e) {
513
e.printStackTrace();
514
} finally {
515
// Safe resource cleanup
516
IOUtils.closeQuietly(inputStream, outputStream);
517
}
518
519
// Drain input stream
520
try (InputStream stream = new URL("https://example.com").openStream()) {
521
IOUtils.drainInputStream(stream);
522
}
523
```
524
525
### Binary Data Operations
526
527
```java
528
import com.amazonaws.util.BinaryUtils;
529
import java.nio.ByteBuffer;
530
531
// Base64 operations
532
String text = "Hello World";
533
byte[] data = text.getBytes();
534
String base64 = BinaryUtils.toBase64(data); // SGVsbG8gV29ybGQ=
535
byte[] decoded = BinaryUtils.fromBase64(base64);
536
537
// Hex operations
538
String hex = BinaryUtils.toHex(data); // 48656c6c6f20576f726c64
539
byte[] fromHex = BinaryUtils.fromHex(hex);
540
541
// ByteBuffer operations
542
ByteBuffer buffer = BinaryUtils.copyBytesFrom(text);
543
byte[] allBytes = BinaryUtils.copyAllBytesFrom(buffer);
544
String streamString = BinaryUtils.toStream(buffer);
545
546
// Hash operations
547
byte[] hash = BinaryUtils.hash(text);
548
String hashHex = BinaryUtils.toHex(hash);
549
550
// ByteBuffer from Base64
551
ByteBuffer base64Buffer = ByteBuffer.allocate(1024);
552
BinaryUtils.fromBase64(base64, base64Buffer);
553
```
554
555
### Date Operations
556
557
```java
558
import com.amazonaws.util.DateUtils;
559
import java.util.Date;
560
561
Date now = new Date();
562
563
// Format dates in different formats
564
String iso8601 = DateUtils.formatISO8601Date(now); // 2023-12-01T10:30:00.000Z
565
String rfc822 = DateUtils.formatRFC822Date(now); // Fri, 01 Dec 2023 10:30:00 GMT
566
String unixTimestamp = DateUtils.formatUnixTimestamp(now); // 1701426600
567
568
// Parse dates from different formats
569
try {
570
Date parsedISO = DateUtils.parseISO8601Date("2023-12-01T10:30:00.000Z");
571
Date parsedRFC = DateUtils.parseRFC822Date("Fri, 01 Dec 2023 10:30:00 GMT");
572
Date parsedUnix = DateUtils.parseUnixTimestamp("1701426600");
573
574
// Clone date safely
575
Date cloned = DateUtils.cloneDate(now);
576
577
// Calculate days since epoch
578
long days = DateUtils.numberOfDaysSinceEpoch(now.getTime());
579
580
} catch (Exception e) {
581
System.err.println("Date parsing failed: " + e.getMessage());
582
}
583
```
584
585
### Validation Operations
586
587
```java
588
import com.amazonaws.util.ValidationUtils;
589
import java.util.*;
590
591
// Object validation
592
String name = "John Doe";
593
ValidationUtils.assertNotNull(name, "name");
594
ValidationUtils.assertStringNotEmpty(name, "name");
595
596
// Collection validation
597
List<String> items = Arrays.asList("item1", "item2", "item3");
598
ValidationUtils.assertNotEmpty(items, "items");
599
ValidationUtils.assertNotNullOrEmpty(items, "items");
600
601
// Numeric validation
602
int count = 10;
603
ValidationUtils.assertIsPositive(count, "count");
604
605
// Boolean validation
606
boolean condition = true;
607
ValidationUtils.assertTrue(condition, "Condition must be true");
608
609
// Custom validation with error messages
610
try {
611
ValidationUtils.assertStringNotEmpty("", "username", "Username cannot be empty");
612
} catch (IllegalArgumentException e) {
613
System.err.println("Validation error: " + e.getMessage());
614
}
615
```
616
617
### JSON Processing
618
619
```java
620
import com.amazonaws.util.JsonUtils;
621
import com.amazonaws.util.Jackson;
622
import java.util.Map;
623
624
// JSON string to object conversion
625
String jsonString = "{\"name\":\"John\",\"age\":30,\"active\":true}";
626
627
try {
628
// Using JsonUtils
629
Map<String, Object> map = JsonUtils.jsonToObject(jsonString, Map.class);
630
String backToJson = JsonUtils.objectToJson(map);
631
632
// Using Jackson
633
Map<String, Object> jacksonMap = Jackson.fromJsonString(jsonString, Map.class);
634
String prettyJson = Jackson.toJsonPrettyString(jacksonMap);
635
636
// JSON validation
637
boolean isValid = JsonUtils.isValidJson(jsonString);
638
if (!isValid) {
639
throw new IllegalArgumentException("Invalid JSON");
640
}
641
642
System.out.println("Pretty JSON: " + prettyJson);
643
644
} catch (Exception e) {
645
System.err.println("JSON processing failed: " + e.getMessage());
646
}
647
```
648
649
### MD5 Hashing
650
651
```java
652
import com.amazonaws.util.Md5Utils;
653
import java.io.*;
654
655
// MD5 hash computation
656
String text = "Hello World";
657
byte[] textBytes = text.getBytes();
658
659
// Hash from byte array
660
byte[] md5Hash = Md5Utils.computeMD5Hash(textBytes);
661
String md5Base64 = Md5Utils.md5AsBase64(textBytes);
662
String md5Hex = Md5Utils.md5Hex(textBytes);
663
664
System.out.println("MD5 Base64: " + md5Base64);
665
System.out.println("MD5 Hex: " + md5Hex);
666
667
// Hash from input stream
668
try (InputStream stream = new ByteArrayInputStream(textBytes)) {
669
byte[] streamMd5 = Md5Utils.computeMD5Hash(stream);
670
String streamMd5Base64 = Md5Utils.md5AsBase64(stream);
671
672
// Create MD5 digest stream for progressive hashing
673
DigestInputStream digestStream = Md5Utils.md5DigestStream(stream);
674
// Read from digestStream to compute hash progressively
675
676
} catch (IOException e) {
677
e.printStackTrace();
678
}
679
```
680
681
## Best Practices
682
683
1. **Null Safety**: Always use validation utilities to check for null values before processing.
684
685
2. **Resource Management**: Use `IOUtils.closeQuietly()` for safe resource cleanup in finally blocks.
686
687
3. **String Operations**: Use `StringUtils` for null-safe string operations and proper encoding.
688
689
4. **Date Handling**: Use appropriate date formats for different contexts (ISO8601 for APIs, RFC822 for headers).
690
691
5. **JSON Processing**: Validate JSON strings before parsing and handle parsing exceptions appropriately.
692
693
6. **Binary Data**: Use appropriate encoding (Base64, Hex) based on the target system requirements.
694
695
7. **Collection Safety**: Check for null or empty collections before iteration or processing.
696
697
8. **Input Validation**: Validate all inputs at service boundaries using validation utilities.
698
699
9. **Hash Operations**: Use MD5 for checksums and integrity verification, not for security purposes.
700
701
10. **Performance**: Use streaming operations for large data sets to avoid memory issues.
702
703
The utility classes provide comprehensive support for common operations, enabling robust and efficient data processing with proper error handling and validation throughout AWS SDK operations.