Skip to content
Snippets Groups Projects
Commit 1b40e688 authored by Jan Kožusznik's avatar Jan Kožusznik
Browse files

tasks: 1 - 3

parent fa49f347
No related merge requests found
package lab07; package lab07;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel; import java.nio.channels.SocketChannel;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
...@@ -25,7 +28,9 @@ class HttpHandler { ...@@ -25,7 +28,9 @@ class HttpHandler {
try { try {
request = getRequest(channel); request = getRequest(channel);
String resource = getResource(request); String resource = getResource(request);
CompletableFuture<Void> future = transferFile(resource, channel);
//task: #3
future.handle((r,exc) -> { close(channel); return null;});
} catch (IOException e) { } catch (IOException e) {
writeStatus(Status.INTERNAL_SERVER_ERROR, channel); writeStatus(Status.INTERNAL_SERVER_ERROR, channel);
writeString("", channel); writeString("", channel);
...@@ -35,14 +40,31 @@ class HttpHandler { ...@@ -35,14 +40,31 @@ class HttpHandler {
} }
} }
private CompletableFuture<Void> transferFile(String resource, SocketChannel channel) { private void close(SocketChannel channel) {
return null; 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) { private void doTransferFile(final String resource, SocketChannel channel) {
@SuppressWarnings("unused")
Path filePath = getFilePath(resource); 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) { private Path getFilePath(String resource) {
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment