Skip to content

Instantly share code, notes, and snippets.

@avbelyaev
Created July 5, 2019 11:49
Show Gist options
  • Save avbelyaev/29586da009c7fdff876580d6bc191ac3 to your computer and use it in GitHub Desktop.
Save avbelyaev/29586da009c7fdff876580d6bc191ac3 to your computer and use it in GitHub Desktop.
Minio. upload file via "presigned put object link"
public class MinioAdapter {
private MinioClient minio;
public MinioAdapter() {
try {
this.minio = new MinioClient(MINIO_URL, MINIO_ACCESS_KEY, MINIO_SECRET);
} catch (InvalidPortException | InvalidEndpointException e) {
throw new IllegalStateException("Could not start Minio client", e);
}
}
public String getUploadLink(String bucket, String key, int expirationSeconds) {
try {
// minio.presignedPutObject() didnt work
return this.minio.getPresignedObjectUrl(Method.PUT, bucket, key, expirationSeconds, null);
} catch (Exception e) { // whatever
throw new IllegalStateException(e);
}
}
public String getDownloadLink(String bucket, String key, int expirationSeconds) {
try {
return this.minio.presignedGetObject(bucket, key, expirationSeconds);
} catch (Exception e) { // whatever
throw new IllegalStateException(e);
}
}
}
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MinioAdapterTests {
private static final TEMPLINK_FILENAME = "uploadable.json";
private static final MinioAdapter MINIO_ADAPTER = new MinioAdapter();
@Test
public void test1_uploadFileViaTemplink() throws IOException {
String writeLink = MINIO_ADAPTER.getUploadLink("uploads", TEMPLINK_FILENAME, 60);
// file from src/test/resources
InputStream is = this.getClass().getClassLoader().getResourceAsStream("upload-to-s3.json");
URL url = new URL(writeLink);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, "application/json");
OutputStream out = connection.getOutputStream();
is.transferTo(out); // java 9+
is.close();
out.close();
int code = connection.getResponseCode();
assertEquals(200, code);
}
@Test
public void test2_downloadFileViaTempLink() throws IOException {
String readLink = MINIO_ADAPTER.getDownloadLink("uploads", TEMPLINK_FILENAME, 5);
String filepath = "/home/anthony/download-from-s3.json";
FileUtils.copyURLToFile(new URL(readLink), new File(filepath));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment