Reputation: 2682
I am trying to convert the following code from Scala to Java:
object ChunkedStaticResponse {
private def createStaticSource(fileName : String) =
FileIO
.fromPath(Paths get fileName)
.map(p => ChunkStreamPart.apply(p))
private def createChunkedSource(fileName : String) =
Chunked(ContentTypes.`text/html(UTF-8)`, createStaticSource(fileName))
def staticResponse(page:String) =
HttpResponse(status = StatusCodes.NotFound,
entity = createChunkedSource(page))
}
But I am having trouble with the implementation of the second method. So far I got this far:
class ChunkedStaticResponseJ {
private Source<HttpEntity.ChunkStreamPart, CompletionStage<IOResult>>
createStaticSource(String fileName) {
return FileIO
.fromPath(Paths.get(fileName))
.map(p -> HttpEntity.ChunkStreamPart.create(p));
}
private HttpEntity.Chunked createChunkedSource(String fileName) {
return HttpEntities.create(ContentTypes.TEXT_HTML_UTF8,
createStaticSource(fileName)); // not working
}
public HttpResponse staticResponse(String page) {
HttpResponse resp = HttpResponse.create();
return resp.withStatus(StatusCodes.NOT_FOUND).withEntity(createChunkedSource(page));
}
}
I can't figure out how to create the chunked source in the second method. Can someone suggest an approach? Also, am I generally on the right path?
Upvotes: 0
Views: 368
Reputation: 9023
If you want to just create a Chunk
out of every ByteString
element read from your file, you can leverage Chunked.fromData
(HttpEntities.createChunked
in the JavaDSL).
Here's how the result would look on the Scala side
object ChunkedStaticResponse {
private def createChunkedSource(fileName : String) =
Chunked.fromData(ContentTypes.`text/html(UTF-8)`, FileIO.fromPath(Paths get fileName))
def staticResponse(page:String) =
HttpResponse(status = StatusCodes.NotFound,
entity = createChunkedSource(page))
}
and this would be its JavaDSL counterpart
class ChunkedStaticResponseJ {
private HttpEntity.Chunked createChunkedSource(String fileName) {
return HttpEntities.createChunked(ContentTypes.TEXT_HTML_UTF8, FileIO.fromPath(Paths.get(fileName)));
}
public HttpResponse staticResponse(String page) {
HttpResponse resp = HttpResponse.create();
return resp.withStatus(StatusCodes.NOT_FOUND).withEntity(createChunkedSource(page));
}
}
Upvotes: 1