From 1b40e688f942cee3a7383bb4be5b22cf487ed979 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Ko=C5=BEusznik?= <jan@kozusznik.cz> Date: Mon, 21 Mar 2022 14:50:26 +0100 Subject: [PATCH] tasks: 1 - 3 --- src/main/java/lab07/HttpHandler.java | 32 +++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/src/main/java/lab07/HttpHandler.java b/src/main/java/lab07/HttpHandler.java index 11d7c02..b4da84e 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) { -- GitLab