2017-03-03 64 views
0

我想下面的代碼從斯卡拉轉換成Java:阿卡-HTTP使用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)); 
    } 
} 

我想不出如何在第二種方法中創建分塊源。 有人可以提出一種方法嗎?另外,我通常是在正確的道路上?

回答

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)); 
    } 
}