diff --git a/src/main/java/lab07/HttpHandler.java b/src/main/java/lab07/HttpHandler.java index 11d7c021e53b189f7c5034680c01d5ff03d3c600..b4da84eadb4a2101a19e962a4710893ea777e7b0 100644 --- a/src/main/java/lab07/HttpHandler.java +++ b/src/main/java/lab07/HttpHandler.java @@ -1,7 +1,10 @@ package lab07; +import java.io.FileNotFoundException; import java.io.IOException; +import java.io.RandomAccessFile; import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; import java.nio.channels.SocketChannel; import java.nio.file.Path; import java.nio.file.Paths; @@ -25,7 +28,9 @@ class HttpHandler { try { request = getRequest(channel); String resource = getResource(request); - + CompletableFuture<Void> future = transferFile(resource, channel); + //task: #3 + future.handle((r,exc) -> { close(channel); return null;}); } catch (IOException e) { writeStatus(Status.INTERNAL_SERVER_ERROR, channel); writeString("", channel); @@ -35,14 +40,31 @@ class HttpHandler { } } - private CompletableFuture<Void> transferFile(String resource, SocketChannel channel) { - return null; + private void close(SocketChannel channel) { + try { + channel.close(); + } catch (IOException e) { + log.warn("close", e); + } } + private CompletableFuture<Void> transferFile(final String resource,final SocketChannel channel) { + //task: #2 + return CompletableFuture.runAsync(() -> doTransferFile(resource, channel)); + } + + //task: #1 private void doTransferFile(final String resource, SocketChannel channel) { - @SuppressWarnings("unused") Path filePath = getFilePath(resource); - //TODO implement data transfer from file to socket + try(RandomAccessFile raf = new RandomAccessFile(filePath.toFile(), "rw"); FileChannel fc = raf.getChannel()) { + writeStatus(Status.OK, channel); + fc.transferTo(0, raf.length(),channel); + } catch (FileNotFoundException e) { + writeStatus(Status.NOT_FOUND, channel); + writeString("'%s' not found".formatted(resource), channel); + } catch (IOException e) { + log.error("read file:", e); + } } private Path getFilePath(String resource) {