use of com.linecorp.armeria.unsafe.ByteBufHttpData in project curiostack by curioswitch.
the class StorageClient method createFile.
/**
* Create a new file for uploading data to cloud storage.
*/
public ListenableFuture<FileWriter> createFile(String filename, Map<String, String> metadata, RequestContext ctx) {
FileRequest request = ImmutableFileRequest.builder().name(filename).metadata(metadata).build();
ByteBuf buf = ctx.alloc().buffer();
try (ByteBufOutputStream os = new ByteBufOutputStream(buf)) {
OBJECT_MAPPER.writeValue((DataOutput) os, request);
} catch (IOException e) {
buf.release();
throw new UncheckedIOException("Could not serialize resource JSON to buffer.", e);
}
HttpData data = new ByteBufHttpData(buf, true);
HttpHeaders headers = HttpHeaders.of(HttpMethod.POST, uploadUrl).contentType(MediaType.JSON_UTF_8);
HttpResponse res = httpClient.execute(headers, data);
return CompletableFuturesExtra.toListenableFuture(res.aggregate(ctx.contextAwareEventLoop()).handle((msg, t) -> {
if (t != null) {
throw new RuntimeException("Unexpected error creating new file.", t);
}
HttpHeaders responseHeaders = msg.headers();
if (!responseHeaders.status().equals(HttpStatus.OK)) {
throw new RuntimeException("Non-successful response when creating new file: " + responseHeaders + "\n" + msg.content().toStringUtf8());
}
String location = responseHeaders.get(HttpHeaderNames.LOCATION);
String pathAndQuery = location.substring("https://www.googleapis.com/upload/storage/v1".length());
return new FileWriter(pathAndQuery, ctx, httpClient);
}));
}
Aggregations