Skip to content

Instantly share code, notes, and snippets.

@cx0der

cx0der/run.java

Created May 18, 2019
Embed
What would you like to do?
public void run() {
OutputStream dataOut = null;
try (BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream())) {
Map<String, String> requestHeaders = parseRequestHeaders(in);
String method = requestHeaders.get(METHOD);
String resource = requestHeaders.get(RESOURCE);
String protocol = requestHeaders.get(PROTOCOL);
String status;
String resolvedResourcePath;
File outputFile;
if (resource.contains("./") || resource.contains("../")) {
status = Http.Status.BAD_REQUEST;
outputFile = new File(this.serverRoot, BAD_REQUEST);
} else if (Http.Method.GET.equals(method)) {
resolvedResourcePath = resolveResource(resource);
outputFile = new File(this.webRoot, resolvedResourcePath);
if (!outputFile.exists()) {
status = Http.Status.NOT_FOUND;
outputFile = new File(this.serverRoot, NOT_FOUND);
} else {
if (outputFile.isDirectory()) {
outputFile = new File(outputFile, INDEX_HTML);
}
if (outputFile.exists()) {
status = Http.Status.OK;
} else {
status = Http.Status.NOT_FOUND;
outputFile = new File(this.serverRoot, NOT_FOUND);
}
}
} else {
outputFile = new File(this.serverRoot, NOT_IMPLEMENTED);
status = Http.Status.NOT_IMPLEMENTED;
}
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("GMT"));
String date = now.format(HTTP_FORMATTER);
String mimeType = Files.probeContentType(outputFile.toPath());
byte[] data = readFile(outputFile);
// write the headers
writeResponseHeaders(out, protocol, status, mimeType, date, data.length, getContentEncoding(requestHeaders));
// write the outputFile contents
dataOut = getDataOutputStream(requestHeaders, client.getOutputStream());
dataOut.write(data, 0, data.length);
if (dataOut instanceof GZIPOutputStream) {
((GZIPOutputStream) dataOut).finish();
} else {
dataOut.flush();
}
// log the request
log(client.getInetAddress(), date, method, status, requestHeaders.getOrDefault(UA, ""), resource);
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
if (dataOut != null) {
try {
dataOut.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.