Skip to content

Commit 47c4ce9

Browse files
authored
Merge pull request #25 from onlyskin/exception-handling
Exception handling
2 parents 54195e6 + b401dae commit 47c4ce9

17 files changed

+130
-56
lines changed

src/main/java/httpserver/App.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ public static void main(String[] args) throws IOException {
1616
PathExaminer pathExaminer = new PathExaminer();
1717
Path root = pathExaminer.getPath(fileDirectory);
1818
Path logPath = pathExaminer.concatenate(root,"logs");
19-
AppConfig appConfig = new AppConfig(root, new Logger(logPath, new FileOperator()));
19+
AppConfig appConfig = new AppConfig(root, new Logger(logPath, new FileOperator(), System.err));
2020

2121
ServerFactory serverFactory = new ServerFactory(new ServerSocketFactory(), appConfig);
2222
SocketHandlerFactory socketHandlerFactory = new SocketHandlerFactory();

src/main/java/httpserver/Hasher.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,7 @@ public String getHash(byte[] input) {
1414
byte[] hash = messageDigest.digest(input);
1515
return bytesToHex(hash);
1616
} catch (NoSuchAlgorithmException e) {
17-
System.out.println("Unable to get hash.");
18-
return "";
17+
throw new RuntimeException(e);
1918
}
2019
}
2120

src/main/java/httpserver/Logger.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,18 @@
33
import httpserver.file.FileOperator;
44

55
import java.io.IOException;
6+
import java.io.PrintStream;
67
import java.nio.file.Path;
78

89
public class Logger {
910
private final FileOperator fileOperator;
1011
private final Path logPath;
12+
private final PrintStream errorStream;
1113

12-
public Logger(Path logPath, FileOperator fileOperator) {
14+
public Logger(Path logPath, FileOperator fileOperator, PrintStream errorStream) {
1315
this.fileOperator = fileOperator;
1416
this.logPath = logPath;
17+
this.errorStream = errorStream;
1518
createFileIfDoesntExist(logPath);
1619
}
1720

@@ -20,14 +23,14 @@ public void log(String logString) {
2023
try {
2124
fileOperator.appendToFile(logPath, logBytes);
2225
} catch (IOException e) {
23-
e.printStackTrace();
26+
errorStream.print(e);
2427
}
2528
}
2629

2730
private void createFileIfDoesntExist(Path path) {
2831
try {
2932
fileOperator.createFileAtPath(path);
30-
} catch (IOException e) {}
33+
} catch (IOException e) { }
3134
}
3235

3336
public byte[] readLog() throws IOException {

src/main/java/httpserver/ResponseWriter.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,11 @@
1111
public class ResponseWriter {
1212
private final HashMap<Integer, String> statuses;
1313
private final OutputStream outputStream;
14+
private final Logger logger;
1415

15-
public ResponseWriter(OutputStream outputStream) {
16+
public ResponseWriter(OutputStream outputStream, Logger logger) {
1617
this.outputStream = outputStream;
18+
this.logger = logger;
1719
this.statuses = new HashMap<>();
1820
statuses.put(200, "OK");
1921
statuses.put(204, "No Content");
@@ -35,7 +37,7 @@ public void write(Response response) {
3537
writeEmptyLine();
3638
writePayload(response);
3739
} catch (IOException e) {
38-
System.out.println("Error while writing to output stream.");
40+
logger.log(e.toString());
3941
}
4042
}
4143

src/main/java/httpserver/Server.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,13 @@ public Server(ServerSocket serverSocket, AppConfig appConfig) {
1414
this.appConfig = appConfig;
1515
}
1616

17-
public void acceptConnection(ExecutorService executorService, SocketHandlerFactory socketHandlerFactory){
17+
public void acceptConnection(ExecutorService executorService, SocketHandlerFactory socketHandlerFactory) {
1818
try {
1919
Socket clientSocket = serverSocket.accept();
2020
SocketHandler socketHandler = socketHandlerFactory.newSocketHandler(appConfig, clientSocket);
2121
executorService.submit(socketHandler);
2222
} catch (IOException e) {
23-
System.out.println("Server socket error");
24-
e.printStackTrace();
23+
appConfig.getLogger().log(e.toString());
2524
}
2625
}
2726
}

src/main/java/httpserver/SocketHandler.java

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
import httpserver.request.Request;
44
import httpserver.request.RequestParser;
55
import httpserver.responder.Responder;
6-
import httpserver.response.BadRequestResponse;
76
import httpserver.response.MethodNotAllowedResponse;
87
import httpserver.response.Response;
8+
import httpserver.response.ServerErrorResponse;
99

1010
import java.io.IOException;
1111
import java.io.InputStream;
@@ -38,15 +38,19 @@ public void run() {
3838
} catch (IllegalArgumentException e) {
3939
response = new MethodNotAllowedResponse();
4040
} catch (Exception e) {
41-
response = new BadRequestResponse();
41+
response = new ServerErrorResponse();
4242
}
4343

4444
responseWriter.write(response);
4545

46+
closeStream();
47+
}
48+
49+
private void closeStream() {
4650
try {
4751
inputStream.close();
4852
} catch (IOException e) {
49-
System.out.println("The inputStream could not be closed.");
53+
appConfig.getLogger().log(e.toString());
5054
}
5155
}
5256
}

src/main/java/httpserver/SocketHandlerFactory.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,14 @@ public SocketHandler newSocketHandler(AppConfig appConfig, Socket clientSocket)
1414
clientSocket.getInputStream(),
1515
new RequestParser(appConfig),
1616
new Responder(new MethodResponderSupplierFactory().makeResponderSupplier()),
17-
new ResponseWriter(clientSocket.getOutputStream()));
17+
new ResponseWriter(clientSocket.getOutputStream(), appConfig.getLogger()));
1818
}
1919

2020
public SocketHandler newSocketHandlerFromStreams(AppConfig appConfig, InputStream inputStream, OutputStream outputStream) throws IOException {
2121
return new SocketHandler(appConfig,
2222
inputStream,
2323
new RequestParser(appConfig),
2424
new Responder(new MethodResponderSupplierFactory().makeResponderSupplier()),
25-
new ResponseWriter(outputStream));
25+
new ResponseWriter(outputStream, appConfig.getLogger()));
2626
}
2727
}

src/main/java/httpserver/file/PathExaminer.java

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -34,22 +34,15 @@ public boolean isFile(Path path) {
3434
return exists(path) && !isDirectory(path);
3535
}
3636

37-
public byte[] fileContents(Path file) {
38-
try {
39-
return readAllBytes(file);
40-
} catch (IOException e) {
41-
return new byte[0];
42-
}
37+
public byte[] fileContents(Path file) throws IOException {
38+
return readAllBytes(file);
4339
}
4440

45-
public Path[] directoryContents(Path dir) {
41+
public Path[] directoryContents(Path dir) throws IOException {
4642
List<Path> result = new ArrayList<>();
47-
try (DirectoryStream<Path> stream = newDirectoryStream(dir)) {
48-
for (Path entry: stream) {
49-
result.add(entry);
50-
}
51-
} catch (IOException e) {
52-
System.out.println("Couldn't retrieve directory contents for directory at " + dir.toString());
43+
DirectoryStream<Path> stream = newDirectoryStream(dir);
44+
for (Path entry: stream) {
45+
result.add(entry);
5346
}
5447
return result.toArray(new Path[0]);
5548
}

src/main/java/httpserver/request/UrlDecoder.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ public String decode(String urlString) {
77
try {
88
return java.net.URLDecoder.decode(urlString, "UTF-8");
99
} catch (UnsupportedEncodingException e) {
10-
return urlString;
10+
throw new RuntimeException(e);
1111
}
1212
}
1313
}

src/main/java/httpserver/responder/GetResponder.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ public Response respond(AppConfig appConfig, Request request) throws IOException
5656
return responseForFile(fullPath, request);
5757
}
5858

59-
private Response responseForDir(Path root, Path path) {
59+
private Response responseForDir(Path root, Path path) throws IOException {
6060
Path[] paths = pathExaminer.directoryContents(path);
6161
String result = htmlLinksForContents(root, paths);
6262
return new OkResponse(result.getBytes());
@@ -70,7 +70,7 @@ private String htmlLinksForContents(Path root, Path[] paths) {
7070
return stringBuilder.toString();
7171
}
7272

73-
private Response responseForFile(Path path, Request request) {
73+
private Response responseForFile(Path path, Request request) throws IOException {
7474
byte[] payload = pathExaminer.fileContents(path);
7575

7676
Response response;

0 commit comments

Comments
 (0)