Skip to content

Commit 728ac98

Browse files
harshil1712elithrar
authored andcommitted
add example for java (#17850)
1 parent a9ff39f commit 728ac98

File tree

1 file changed

+204
-0
lines changed

1 file changed

+204
-0
lines changed
Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
---
2+
title: aws-sdk-java
3+
pcx_content_type: example
4+
---
5+
6+
import { Render } from "~/components";
7+
8+
<Render file="keys" />
9+
<br />
10+
11+
This example uses version 2 of the [aws-sdk-java](https://github.com/aws/aws-sdk-java-v2/#using-the-sdk) package. You must pass in the R2 configuration credentials when instantiating your `S3` service client:
12+
13+
```java
14+
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
15+
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
16+
import software.amazon.awssdk.regions.Region;
17+
import software.amazon.awssdk.services.s3.S3Client;
18+
import software.amazon.awssdk.services.s3.model.*;
19+
import software.amazon.awssdk.services.s3.S3Configuration;
20+
import java.net.URI;
21+
import java.util.List;
22+
23+
/**
24+
* Client for interacting with Cloudflare R2 Storage using AWS SDK S3 compatibility
25+
*/
26+
public class CloudflareR2Client {
27+
private final S3Client s3Client;
28+
29+
/**
30+
* Creates a new CloudflareR2Client with the provided configuration
31+
*/
32+
public CloudflareR2Client(S3Config config) {
33+
this.s3Client = buildS3Client(config);
34+
}
35+
36+
/**
37+
* Configuration class for R2 credentials and endpoint
38+
*/
39+
public static class S3Config {
40+
private final String accountId;
41+
private final String accessKey;
42+
private final String secretKey;
43+
private final String endpoint;
44+
45+
public S3Config(String accountId, String accessKey, String secretKey) {
46+
this.accountId = accountId;
47+
this.accessKey = accessKey;
48+
this.secretKey = secretKey;
49+
this.endpoint = String.format("https://%s.r2.cloudflarestorage.com", accountId);
50+
}
51+
52+
public String getAccessKey() { return accessKey; }
53+
public String getSecretKey() { return secretKey; }
54+
public String getEndpoint() { return endpoint; }
55+
}
56+
57+
/**
58+
* Builds and configures the S3 client with R2-specific settings
59+
*/
60+
private static S3Client buildS3Client(S3Config config) {
61+
AwsBasicCredentials credentials = AwsBasicCredentials.create(
62+
config.getAccessKey(),
63+
config.getSecretKey()
64+
);
65+
66+
S3Configuration serviceConfiguration = S3Configuration.builder()
67+
.pathStyleAccessEnabled(true)
68+
.build();
69+
70+
return S3Client.builder()
71+
.endpointOverride(URI.create(config.getEndpoint()))
72+
.credentialsProvider(StaticCredentialsProvider.create(credentials))
73+
.region(Region.of("auto"))
74+
.serviceConfiguration(serviceConfiguration)
75+
.build();
76+
}
77+
78+
/**
79+
* Lists all buckets in the R2 storage
80+
*/
81+
public List<Bucket> listBuckets() {
82+
try {
83+
return s3Client.listBuckets().buckets();
84+
} catch (S3Exception e) {
85+
throw new RuntimeException("Failed to list buckets: " + e.getMessage(), e);
86+
}
87+
}
88+
89+
/**
90+
* Lists all objects in the specified bucket
91+
*/
92+
public List<S3Object> listObjects(String bucketName) {
93+
try {
94+
ListObjectsV2Request request = ListObjectsV2Request.builder()
95+
.bucket(bucketName)
96+
.build();
97+
98+
return s3Client.listObjectsV2(request).contents();
99+
} catch (S3Exception e) {
100+
throw new RuntimeException("Failed to list objects in bucket " + bucketName + ": " + e.getMessage(), e);
101+
}
102+
}
103+
104+
public static void main(String[] args) {
105+
S3Config config = new S3Config(
106+
"your_account_id",
107+
"your_access_key",
108+
"your_secret_key"
109+
);
110+
111+
CloudflareR2Client r2Client = new CloudflareR2Client(config);
112+
113+
// List buckets
114+
System.out.println("Available buckets:");
115+
r2Client.listBuckets().forEach(bucket ->
116+
System.out.println("* " + bucket.name())
117+
);
118+
119+
// List objects in a specific bucket
120+
String bucketName = "demos";
121+
System.out.println("\nObjects in bucket '" + bucketName + "':");
122+
r2Client.listObjects(bucketName).forEach(object ->
123+
System.out.printf("* %s (size: %d bytes, modified: %s)%n",
124+
object.key(),
125+
object.size(),
126+
object.lastModified())
127+
);
128+
}
129+
}
130+
```
131+
132+
## Generate presigned URLs
133+
134+
You can also generate presigned links that can be used to temporarily share public write access to a bucket.
135+
136+
```java
137+
// import required packages for presigning
138+
// Rest of the packages are same as above
139+
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
140+
import software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest;
141+
import software.amazon.awssdk.services.s3.presigner.model.PresignedPutObjectRequest;
142+
import java.time.Duration;
143+
144+
public class CloudflareR2Client {
145+
private final S3Client s3Client;
146+
private final S3Presigner presigner;
147+
148+
/**
149+
* Creates a new CloudflareR2Client with the provided configuration
150+
*/
151+
public CloudflareR2Client(S3Config config) {
152+
this.s3Client = buildS3Client(config);
153+
this.presigner = buildS3Presigner(config);
154+
}
155+
156+
/**
157+
* Builds and configures the S3 presigner with R2-specific settings
158+
*/
159+
private static S3Presigner buildS3Presigner(S3Config config) {
160+
AwsBasicCredentials credentials = AwsBasicCredentials.create(
161+
config.getAccessKey(),
162+
config.getSecretKey()
163+
);
164+
165+
return S3Presigner.builder()
166+
.endpointOverride(URI.create(config.getEndpoint()))
167+
.credentialsProvider(StaticCredentialsProvider.create(credentials))
168+
.region(Region.of("auto"))
169+
.serviceConfiguration(S3Configuration.builder()
170+
.pathStyleAccessEnabled(true)
171+
.build())
172+
.build();
173+
}
174+
175+
public String generatePresignedUploadUrl(String bucketName, String objectKey, Duration expiration) {
176+
PutObjectPresignRequest presignRequest = PutObjectPresignRequest.builder()
177+
.signatureDuration(expiration)
178+
.putObjectRequest(builder -> builder
179+
.bucket(bucketName)
180+
.key(objectKey)
181+
.build())
182+
.build();
183+
184+
PresignedPutObjectRequest presignedRequest = presigner.presignPutObject(presignRequest);
185+
return presignedRequest.url().toString();
186+
}
187+
188+
// Rest of the methods remains the same
189+
190+
public static void main(String[] args) {
191+
// config the client as before
192+
193+
// Generate a pre-signed upload URL valid for 15 minutes
194+
String uploadUrl = r2Client.generatePresignedUploadUrl(
195+
"demos",
196+
"README.md",
197+
Duration.ofMinutes(15)
198+
);
199+
System.out.println("Pre-signed Upload URL (valid for 15 minutes):");
200+
System.out.println(uploadUrl);
201+
}
202+
203+
}
204+
```

0 commit comments

Comments
 (0)