我正在尝试将以下代码从Scala转换为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))
}
但我遇到了第二种方法的实施问题。到目前为止,我到目前为止:
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));
}
}
我无法弄清楚如何在第二种方法中创建分块源。 有人可以建议一种方法吗?另外,我通常走在正确的道路上吗?
答案 0 :(得分:1)
如果您只想从文件中读取的每个Chunk
元素中创建ByteString
,您可以利用Chunked.fromData
(JavaDSL中的HttpEntities.createChunked
)。
以下是Scala方面的结果
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))
}
这将是它的JavaDSL对应
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));
}
}