From 7b3d9cd366388ae6d83a8d7a58b6153b07f23e05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=CC=88rg=20Prante?= Date: Fri, 17 Aug 2018 18:25:59 +0200 Subject: [PATCH] directory context handler --- .../context/DirectoryContextHandler.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 netty-http-server/src/main/java/org/xbib/netty/http/server/context/DirectoryContextHandler.java diff --git a/netty-http-server/src/main/java/org/xbib/netty/http/server/context/DirectoryContextHandler.java b/netty-http-server/src/main/java/org/xbib/netty/http/server/context/DirectoryContextHandler.java new file mode 100644 index 0000000..9f032fb --- /dev/null +++ b/netty-http-server/src/main/java/org/xbib/netty/http/server/context/DirectoryContextHandler.java @@ -0,0 +1,46 @@ +package org.xbib.netty.http.server.context; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import org.xbib.netty.http.server.transport.ServerRequest; +import org.xbib.netty.http.server.transport.ServerResponse; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.channels.Channels; +import java.nio.channels.SeekableByteChannel; +import java.nio.file.Files; +import java.nio.file.Path; + +public class DirectoryContextHandler implements ContextHandler { + + private Path path; + + private ByteBufAllocator allocator; + + public DirectoryContextHandler(Path path, ByteBufAllocator allocator) { + this.path = path; + this.allocator = allocator; + } + + @Override + public void serve(ServerRequest serverRequest, ServerResponse serverResponse) throws IOException { + String uri = serverRequest.getRequest().uri(); + Path p = path.resolve(uri); + ByteBuf byteBuf = read(allocator, p); + serverResponse.write(200, "application/octet-stream", byteBuf); + byteBuf.release(); + } + + + public static ByteBuf read(ByteBufAllocator allocator, Path path) + throws IOException { + try (SeekableByteChannel sbc = Files.newByteChannel(path); + InputStream in = Channels.newInputStream(sbc)) { + int size = Math.toIntExact(sbc.size()); + ByteBuf byteBuf = allocator.directBuffer(size, size); + byteBuf.writeBytes(in, size); + return byteBuf; + } + } +}