-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathS3Test.java
More file actions
202 lines (172 loc) · 7.25 KB
/
S3Test.java
File metadata and controls
202 lines (172 loc) · 7.25 KB
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
package io.github.nejckorasa.s3;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.AnonymousAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.AmazonS3URI;
import com.amazonaws.services.s3.model.CreateBucketRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import io.findify.s3mock.S3Mock;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.lang.Thread.currentThread;
import static java.util.Comparator.reverseOrder;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
@Slf4j
public class S3Test implements BeforeEachCallback, AfterEachCallback {
public static final String US_EAST_1 = "us-east-1";
String localFileBackendPath;
String defaultBucketName;
S3Mock api;
int port;
AmazonS3 s3Client;
public S3Test withLocalFileBackend(String path) {
localFileBackendPath = path;
return this;
}
public S3Test withDefaultBucket(String bucketName) {
defaultBucketName = bucketName;
return this;
}
@Override
public void beforeEach(ExtensionContext extensionContext) {
var apiBuilder = new S3Mock.Builder().withPort(0);
if (localFileBackendPath != null) {
apiBuilder.withFileBackend(localFileBackendPath);
} else {
apiBuilder.withInMemoryBackend();
}
api = apiBuilder.build();
var serverBinding = api.start();
port = serverBinding.localAddress().getPort();
s3Client = AmazonS3ClientBuilder.standard()
.withPathStyleAccessEnabled(true)
.withEndpointConfiguration(new EndpointConfiguration("http://localhost:" + port, US_EAST_1))
.withCredentials(new AWSStaticCredentialsProvider(new AnonymousAWSCredentials()))
.build();
if (defaultBucketName != null) {
createBuckets(defaultBucketName);
}
}
@Override
public void afterEach(ExtensionContext extensionContext) {
api.shutdown();
if (localFileBackendPath != null) {
try (var files = Files.walk(Path.of(localFileBackendPath))) {
files.sorted(reverseOrder()).map(Path::toFile).forEach(File::delete);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
public S3Test createBuckets(String bucketName, String... otherBuckets) {
s3Client.createBucket(new CreateBucketRequest(bucketName, US_EAST_1));
for (var otherBucket : otherBuckets) {
s3Client.createBucket(new CreateBucketRequest(otherBucket, US_EAST_1));
}
return this;
}
public S3Test verifyBucketFileCount(String s3Path, int expectedCount) {
var uri = new AmazonS3URI(s3Path);
var objectSummaries = s3Client.listObjects(uri.getBucket(), uri.getKey()).getObjectSummaries();
log.debug("Object summaries {}", objectSummaries.stream().map(S3ObjectSummary::getKey).collect(joining(",", "[", "]")));
var fileCount = objectSummaries.size();
if (fileCount != expectedCount) {
throw new AssertionError(String.format("Expected %d got %d files in %s", expectedCount, fileCount, uri.getBucket()));
}
return this;
}
public S3Test verifyContainsFiles(String s3Path, String... expectedObjectKeys) {
var uri = new AmazonS3URI(s3Path);
var objectSummaries = s3Client.listObjects(uri.getBucket(), uri.getKey()).getObjectSummaries();
List<String> objectKeys = objectSummaries.stream().map(S3ObjectSummary::getKey).collect(toList());
assertThat(objectKeys).containsAll(Arrays.asList(expectedObjectKeys));
return this;
}
public Upload uploadFrom(String path) {
return new Upload(path);
}
public S3Object download(String s3Path) {
var uri = new AmazonS3URI(s3Path);
if (s3Client.doesObjectExist(uri.getBucket(), uri.getKey())) {
return s3Client.getObject(uri.getBucket(), uri.getKey());
} else {
throw new IllegalStateException("Expected s3 object to exist but did not " + s3Path);
}
}
public String downloadAsString(String s3Path) {
var s3Object = download(s3Path);
try (var inputStream = s3Object.getObjectContent()) {
return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public byte[] downloadAsBytes(String s3Path) {
var s3Object = download(s3Path);
try (var inputStream = s3Object.getObjectContent()) {
return inputStream.readAllBytes();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public final class Upload {
private final Map<String, String> resources;
private boolean createBuckets = false;
private String contentType = null;
@SneakyThrows
private Upload(String path) {
resources = new HashMap<>();
URL resource = currentThread().getContextClassLoader().getResource(path);
try (var files = Files.list(Paths.get(requireNonNull(resource).toURI()))) {
files.forEach(p -> resources.put(p.toString(), p.getFileName().toString()));
}
}
public Upload creatingBuckets() {
createBuckets = true;
return this;
}
public Upload contentType(String contentType) {
this.contentType = contentType;
return this;
}
public void to(String destination) {
resources.forEach((path, name) -> {
try (var inputStream = Files.newInputStream(Path.of(path))) {
var uri = new AmazonS3URI(destination);
if (createBuckets && !s3Client.doesBucketExistV2(uri.getBucket())) {
s3Client.createBucket(uri.getBucket());
}
var metadata = new ObjectMetadata();
if (contentType != null) {
metadata.setContentType(contentType);
}
s3Client.putObject(uri.getBucket(), uri.getKey() + "/" + name, inputStream, metadata);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
}
}