0
# ARN Support & Resource Management
1
2
Amazon Resource Names (ARNs) uniquely identify AWS resources. The AWS Java SDK Core provides comprehensive ARN parsing, validation, and manipulation capabilities for working with AWS resources programmatically.
3
4
## Core ARN Classes
5
6
### ARN Class
7
8
```java { .api }
9
// Core ARN parsing and manipulation class
10
class Arn {
11
// Static factory methods
12
public static Arn fromString(String arn);
13
public static Builder builder();
14
15
// ARN component accessors
16
public String getPartition();
17
public String getService();
18
public String getRegion();
19
public String getAccountId();
20
public ArnResource getResource();
21
22
// ARN formatting
23
public String toString();
24
25
// ARN builder for constructing ARNs
26
interface Builder {
27
Builder partition(String partition);
28
Builder service(String service);
29
Builder region(String region);
30
Builder accountId(String accountId);
31
Builder resource(String resource);
32
Builder resource(String resourceType, String resourceId);
33
Builder resource(ArnResource resource);
34
Arn build();
35
}
36
}
37
```
38
39
### ARN Resource
40
41
```java { .api }
42
// ARN resource component representation
43
class ArnResource {
44
public static ArnResource fromString(String resource);
45
46
public String getResourceType();
47
public String getResource();
48
public String getQualifier();
49
50
// Check if resource has a type
51
public boolean hasResourceType();
52
53
// String representation
54
public String toString();
55
}
56
57
// AWS resource abstraction
58
interface AwsResource {
59
String getPartition();
60
String getService();
61
String getRegion();
62
String getAccount();
63
String getResourceType();
64
String getResourceId();
65
66
// Convert to ARN
67
Arn getArn();
68
}
69
```
70
71
### ARN Converter
72
73
```java { .api }
74
// ARN conversion utilities
75
class ArnConverter {
76
// Convert between ARN and resource representations
77
public static <T extends AwsResource> T convertArn(Arn arn, Class<T> resourceClass);
78
public static Arn convertResource(AwsResource resource);
79
80
// Resource-specific converters
81
public static S3ObjectIdentifier toS3ObjectIdentifier(Arn arn);
82
public static DynamoDbTableIdentifier toDynamoDbTableIdentifier(Arn arn);
83
public static LambdaFunctionIdentifier toLambdaFunctionIdentifier(Arn arn);
84
}
85
```
86
87
## ARN Validation
88
89
### ARN Validation Utilities
90
91
```java { .api }
92
// ARN validation and format checking
93
class ArnValidator {
94
// Validate ARN format
95
public static boolean isValidArn(String arn);
96
public static boolean isValidArnFormat(String arn);
97
98
// Service-specific validation
99
public static boolean isValidS3Arn(String arn);
100
public static boolean isValidDynamoDbArn(String arn);
101
public static boolean isValidLambdaArn(String arn);
102
public static boolean isValidIamArn(String arn);
103
104
// Validation with detailed errors
105
public static ValidationResult validateArn(String arn);
106
}
107
108
// Validation result with detailed error information
109
class ValidationResult {
110
public boolean isValid();
111
public List<String> getErrors();
112
public List<String> getWarnings();
113
}
114
```
115
116
## Basic Usage Examples
117
118
### ARN Parsing
119
120
```java
121
import com.amazonaws.arn.Arn;
122
import com.amazonaws.arn.ArnResource;
123
124
// Parse an ARN string
125
String arnString = "arn:aws:s3:::my-bucket/my-object";
126
Arn arn = Arn.fromString(arnString);
127
128
// Access ARN components
129
System.out.println("Partition: " + arn.getPartition()); // "aws"
130
System.out.println("Service: " + arn.getService()); // "s3"
131
System.out.println("Region: " + arn.getRegion()); // "" (empty for S3)
132
System.out.println("Account: " + arn.getAccountId()); // "" (empty for S3)
133
134
// Access resource information
135
ArnResource resource = arn.getResource();
136
System.out.println("Resource: " + resource.getResource()); // "my-bucket/my-object"
137
```
138
139
### ARN Construction
140
141
```java
142
import com.amazonaws.arn.Arn;
143
144
// Build an ARN using the builder pattern
145
Arn dynamoArn = Arn.builder()
146
.partition("aws")
147
.service("dynamodb")
148
.region("us-east-1")
149
.accountId("123456789012")
150
.resource("table", "my-table")
151
.build();
152
153
System.out.println(dynamoArn.toString());
154
// Output: arn:aws:dynamodb:us-east-1:123456789012:table/my-table
155
```
156
157
### ARN Validation
158
159
```java
160
import com.amazonaws.arn.ArnValidator;
161
import com.amazonaws.arn.ValidationResult;
162
163
// Simple validation
164
String arnString = "arn:aws:lambda:us-west-2:123456789012:function:my-function";
165
boolean isValid = ArnValidator.isValidArn(arnString);
166
167
// Detailed validation with error reporting
168
ValidationResult result = ArnValidator.validateArn(arnString);
169
if (!result.isValid()) {
170
System.err.println("ARN validation errors:");
171
result.getErrors().forEach(System.err::println);
172
}
173
174
// Service-specific validation
175
boolean isValidLambda = ArnValidator.isValidLambdaArn(arnString);
176
```
177
178
## Service-Specific ARN Handling
179
180
### S3 ARN Handling
181
182
```java
183
import com.amazonaws.arn.Arn;
184
185
// S3 bucket ARN
186
Arn s3BucketArn = Arn.builder()
187
.partition("aws")
188
.service("s3")
189
.resource("my-bucket")
190
.build();
191
192
// S3 object ARN
193
Arn s3ObjectArn = Arn.builder()
194
.partition("aws")
195
.service("s3")
196
.resource("my-bucket/path/to/object.txt")
197
.build();
198
199
// Parse S3 ARNs
200
String s3ArnString = "arn:aws:s3:::my-bucket/my-object";
201
Arn parsedS3Arn = Arn.fromString(s3ArnString);
202
ArnResource resource = parsedS3Arn.getResource();
203
204
// Extract bucket and key
205
String fullResource = resource.getResource(); // "my-bucket/my-object"
206
String[] parts = fullResource.split("/", 2);
207
String bucket = parts[0];
208
String key = parts.length > 1 ? parts[1] : null;
209
```
210
211
### DynamoDB ARN Handling
212
213
```java
214
// DynamoDB table ARN
215
Arn dynamoTableArn = Arn.builder()
216
.partition("aws")
217
.service("dynamodb")
218
.region("us-east-1")
219
.accountId("123456789012")
220
.resource("table", "Users")
221
.build();
222
223
// DynamoDB stream ARN
224
Arn dynamoStreamArn = Arn.builder()
225
.partition("aws")
226
.service("dynamodb")
227
.region("us-east-1")
228
.accountId("123456789012")
229
.resource("table/Users/stream/2023-01-01T00:00:00.000")
230
.build();
231
232
// Parse and extract table name
233
String dynamoArnString = "arn:aws:dynamodb:us-east-1:123456789012:table/Users";
234
Arn parsedDynamoArn = Arn.fromString(dynamoArnString);
235
ArnResource resource = parsedDynamoArn.getResource();
236
String tableName = resource.getResource(); // "Users"
237
```
238
239
### Lambda ARN Handling
240
241
```java
242
// Lambda function ARN
243
Arn lambdaArn = Arn.builder()
244
.partition("aws")
245
.service("lambda")
246
.region("us-west-2")
247
.accountId("123456789012")
248
.resource("function", "my-function")
249
.build();
250
251
// Lambda function version ARN
252
Arn lambdaVersionArn = Arn.builder()
253
.partition("aws")
254
.service("lambda")
255
.region("us-west-2")
256
.accountId("123456789012")
257
.resource("function:my-function:1")
258
.build();
259
260
// Parse Lambda ARN and extract function name
261
String lambdaArnString = "arn:aws:lambda:us-west-2:123456789012:function:my-function:$LATEST";
262
Arn parsedLambdaArn = Arn.fromString(lambdaArnString);
263
ArnResource resource = parsedLambdaArn.getResource();
264
265
// Handle function name and qualifier
266
String resourceStr = resource.getResource();
267
if (resourceStr.contains(":")) {
268
String[] parts = resourceStr.split(":", 2);
269
String functionName = parts[0]; // "my-function"
270
String qualifier = parts[1]; // "$LATEST"
271
}
272
```
273
274
### IAM ARN Handling
275
276
```java
277
// IAM role ARN
278
Arn iamRoleArn = Arn.builder()
279
.partition("aws")
280
.service("iam")
281
.accountId("123456789012")
282
.resource("role", "my-role")
283
.build();
284
285
// IAM user ARN
286
Arn iamUserArn = Arn.builder()
287
.partition("aws")
288
.service("iam")
289
.accountId("123456789012")
290
.resource("user", "my-user")
291
.build();
292
293
// IAM policy ARN
294
Arn iamPolicyArn = Arn.builder()
295
.partition("aws")
296
.service("iam")
297
.accountId("123456789012")
298
.resource("policy", "my-policy")
299
.build();
300
```
301
302
## Advanced ARN Operations
303
304
### ARN Pattern Matching
305
306
```java
307
import java.util.regex.Pattern;
308
309
// Match ARNs by pattern
310
public class ArnMatcher {
311
private static final Pattern S3_ARN_PATTERN =
312
Pattern.compile("arn:aws:s3:::([^/]+)(/.*)?");
313
314
private static final Pattern LAMBDA_ARN_PATTERN =
315
Pattern.compile("arn:aws:lambda:([^:]+):([^:]+):function:([^:]+)(:.*)?");
316
317
public static boolean isS3Arn(String arn) {
318
return S3_ARN_PATTERN.matcher(arn).matches();
319
}
320
321
public static boolean isLambdaArn(String arn) {
322
return LAMBDA_ARN_PATTERN.matcher(arn).matches();
323
}
324
}
325
```
326
327
### ARN Transformation
328
329
```java
330
// Transform ARNs for different contexts
331
public class ArnTransformer {
332
333
// Convert S3 object ARN to bucket ARN
334
public static Arn toBucketArn(Arn s3ObjectArn) {
335
if (!"s3".equals(s3ObjectArn.getService())) {
336
throw new IllegalArgumentException("Not an S3 ARN");
337
}
338
339
String resource = s3ObjectArn.getResource().getResource();
340
String bucket = resource.split("/")[0];
341
342
return Arn.builder()
343
.partition(s3ObjectArn.getPartition())
344
.service(s3ObjectArn.getService())
345
.region(s3ObjectArn.getRegion())
346
.accountId(s3ObjectArn.getAccountId())
347
.resource(bucket)
348
.build();
349
}
350
351
// Extract region from ARN
352
public static String extractRegion(Arn arn) {
353
return arn.getRegion();
354
}
355
356
// Extract account ID from ARN
357
public static String extractAccountId(Arn arn) {
358
return arn.getAccountId();
359
}
360
}
361
```
362
363
### Bulk ARN Processing
364
365
```java
366
import java.util.List;
367
import java.util.stream.Collectors;
368
369
// Process multiple ARNs
370
public class ArnProcessor {
371
372
// Filter ARNs by service
373
public static List<Arn> filterByService(List<String> arnStrings, String service) {
374
return arnStrings.stream()
375
.map(Arn::fromString)
376
.filter(arn -> service.equals(arn.getService()))
377
.collect(Collectors.toList());
378
}
379
380
// Group ARNs by region
381
public static Map<String, List<Arn>> groupByRegion(List<Arn> arns) {
382
return arns.stream()
383
.collect(Collectors.groupingBy(Arn::getRegion));
384
}
385
386
// Extract unique account IDs
387
public static Set<String> extractAccountIds(List<Arn> arns) {
388
return arns.stream()
389
.map(Arn::getAccountId)
390
.filter(Objects::nonNull)
391
.filter(accountId -> !accountId.isEmpty())
392
.collect(Collectors.toSet());
393
}
394
}
395
```
396
397
## Error Handling
398
399
### ARN Parsing Errors
400
401
```java
402
import com.amazonaws.arn.Arn;
403
import com.amazonaws.SdkClientException;
404
405
try {
406
Arn arn = Arn.fromString("invalid-arn-format");
407
} catch (IllegalArgumentException e) {
408
System.err.println("Invalid ARN format: " + e.getMessage());
409
} catch (SdkClientException e) {
410
System.err.println("SDK error parsing ARN: " + e.getMessage());
411
}
412
```
413
414
### Safe ARN Operations
415
416
```java
417
// Safe ARN parsing with validation
418
public static Optional<Arn> safeParseArn(String arnString) {
419
try {
420
if (ArnValidator.isValidArn(arnString)) {
421
return Optional.of(Arn.fromString(arnString));
422
}
423
} catch (Exception e) {
424
// Log error but don't propagate
425
System.err.println("Failed to parse ARN: " + arnString + ", error: " + e.getMessage());
426
}
427
return Optional.empty();
428
}
429
430
// Usage
431
String arnString = "arn:aws:s3:::my-bucket/my-object";
432
Optional<Arn> arn = safeParseArn(arnString);
433
if (arn.isPresent()) {
434
System.out.println("Successfully parsed ARN: " + arn.get().toString());
435
} else {
436
System.out.println("Failed to parse ARN");
437
}
438
```
439
440
## Best Practices
441
442
### ARN Validation Best Practices
443
444
1. **Always validate ARNs** before parsing when handling user input
445
2. **Use service-specific validation** when possible for stricter checks
446
3. **Handle parsing exceptions** gracefully in production code
447
4. **Cache parsed ARNs** when processing the same ARN multiple times
448
449
### Performance Considerations
450
451
1. **Reuse Arn objects** rather than re-parsing the same ARN string
452
2. **Use batch processing** for multiple ARN operations
453
3. **Consider ARN pattern matching** for high-volume filtering operations
454
455
### Security Considerations
456
457
1. **Validate ARN ownership** before performing operations
458
2. **Check account boundaries** when processing cross-account ARNs
459
3. **Sanitize ARN inputs** from external sources
460
4. **Use least-privilege principles** when working with ARN-based policies
461
462
ARN support in the AWS Java SDK Core provides the foundation for resource identification and manipulation across all AWS services, enabling robust and type-safe resource management in Java applications.