Commit ffe7b4ea authored by Sefa Eyeoglu's avatar Sefa Eyeoglu

Added HTTPDefaultHandler. Restructured handler, preprocessor and rawhandler

parent a727562f
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
......
......@@ -8,8 +8,9 @@ import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
public class HTTPUtils {
......@@ -45,6 +46,23 @@ public class HTTPUtils {
return string;
}
public static Map<String, String> parseParameterString(String parameterString) {
Map<String, String> parameters = new HashMap<>();
if (parameterString.contains("&")) {
//Multiple parameters
String[] params = parameterString.split("&");
for (String param : params) {
String[] parts = param.split("=", 2);
parameters.put(parts[0], HTTPUtils.decodeString(parts[1]));
}
} else {
//Just one parameter
String[] parts = parameterString.split("=", 2);
parameters.put(parts[0], HTTPUtils.decodeString(parts[1]));
}
return parameters;
}
public static HTTPResponse getInternalServerErrorResponse(ImplifyServer serverInstance, HTTPRequest request) {
HTTPResponse response = new HTTPResponse(serverInstance, request);
response.setStatusCode(HTTPResponse.Code.INTERNAL_SERVER_ERROR);
......
......@@ -12,7 +12,6 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
......@@ -52,19 +51,14 @@ public class ImplifyServer {
this.port = port;
this.backlog = backlog;
this.identifier = identifier;
initialize();
}
private void initialize() {
exceptionHandler = new ImplifyExceptionHandler(this);
threadFactory = new ImplifyThreadFactory(this);
rawSocketHandler = new RawSocketHandler(this);
httpPreprocessor = new HTTPDefaultPreprocessor(this);
try {
//Default Configuration
httpHandler = new HTTPFileSystemHandler(this, new File(".").getCanonicalFile());
} catch (IOException ignored) {
}
//May be changed by user if needed
rawSocketHandler = new RawSocketHandler();
httpPreprocessor = new HTTPDefaultPreprocessor();
//Should be changed by user
httpHandler = new HTTPExampleHandler();
this.logger = LogManager.getLogger("implify_" + identifier);
}
......@@ -80,20 +74,20 @@ public class ImplifyServer {
}
mainThread = getThreadFactory().newThread(() -> {
while (true) {
while (running) {
try {
Socket socket = serverSocket.accept();
getThreadFactory().newThread(() -> {
try {
HTTPRequest request = getRawSocketHandler().handle(socket);
HTTPRequest request = getRawSocketHandler().handle(this, socket);
if (request == null)
if (!socket.isClosed())
socket.close();
HTTPResponse response = getHttpPreprocessor().process(request);
HTTPResponse response = getHttpPreprocessor().process(this, request);
if (response == null) {
response = HTTPUtils.getInternalServerErrorResponse(this, request);
}
response = getHttpHandler().handle(request, response);
response = getHttpHandler().handle(this, request, response);
if (response == null) {
response = HTTPUtils.getInternalServerErrorResponse(this, request);
}
......@@ -131,7 +125,9 @@ public class ImplifyServer {
mainThread.start();
}
public void stop() {
public void stop() throws ImplifyException {
if (!running)
throw new ImplifyException("Instance " + identifier + " not running!");
mainThread.interrupt();
try {
if (!serverSocket.isClosed())
......
......@@ -4,21 +4,14 @@ import net.scrumplex.implify.core.ImplifyServer;
import net.scrumplex.implify.exceptions.ImplifyException;
import net.scrumplex.implify.lang.HTTPPreprocessor;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
public class HTTPDefaultPreprocessor implements HTTPPreprocessor {
private final ImplifyServer serverInstance;
public HTTPDefaultPreprocessor(ImplifyServer serverInstance) {
this.serverInstance = serverInstance;
}
@Override
public HTTPResponse process(HTTPRequest request) throws ImplifyException {
public HTTPResponse process(ImplifyServer serverInstance, HTTPRequest request) throws ImplifyException {
try {
HTTPResponse response = new HTTPResponse(serverInstance, request);
......@@ -47,7 +40,7 @@ public class HTTPDefaultPreprocessor implements HTTPPreprocessor {
response.setHeaders(responseHeaders);
return response;
} catch (Exception e) {
throw new ImplifyException(e);
throw new ImplifyException(e);
}
}
}
package net.scrumplex.implify.core.exchange;
import net.scrumplex.implify.core.ImplifyServer;
import net.scrumplex.implify.exceptions.ImplifyException;
import net.scrumplex.implify.lang.HTTPHandler;
public class HTTPExampleHandler implements HTTPHandler {
@Override
public HTTPResponse handle(ImplifyServer serverInstance, HTTPRequest request, HTTPResponse response) throws ImplifyException {
response.setResponseData(getClass().getResourceAsStream("/demo.html"));
return response;
}
}
......@@ -4,24 +4,23 @@ import net.scrumplex.implify.core.HTTPUtils;
import net.scrumplex.implify.core.ImplifyServer;
import net.scrumplex.implify.exceptions.ImplifyException;
import net.scrumplex.implify.lang.HTTPHandler;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class HTTPFileSystemHandler implements HTTPHandler {
private final ImplifyServer serverInstance;
private final File parentDirectory;
public HTTPFileSystemHandler(ImplifyServer serverInstance, File parentDirectory) {
this.serverInstance = serverInstance;
public HTTPFileSystemHandler(File parentDirectory) {
this.parentDirectory = parentDirectory;
}
public HTTPResponse handle(HTTPRequest request, HTTPResponse response) throws ImplifyException {
public HTTPResponse handle(ImplifyServer serverInstance, HTTPRequest request, HTTPResponse response) throws ImplifyException {
try {
File f = new File(parentDirectory, request.getRequestPath().substring(1));
if (f.isDirectory())
f = new File(f, "index.html");
f = new File(parentDirectory, "demo.html");
if (!f.exists()) {
response.getHeaders().put("Content-Type", "text/plain; charset=UTF-8");
......
package net.scrumplex.implify.core.exchange;
import net.scrumplex.implify.core.HTTPUtils;
import net.scrumplex.implify.core.ImplifyServer;
import java.io.IOException;
......@@ -15,6 +16,7 @@ public class HTTPRequest {
private String requestMethod;
private String httpVersion;
private Map<String, String> headers;
private Map<String, String> getParameters;
private HTTPResponse response;
public HTTPRequest(ImplifyServer serverInstance, Socket socket) {
......@@ -88,4 +90,12 @@ public class HTTPRequest {
public boolean isClosed() {
return socket == null || socket.isClosed();
}
public Map<String, String> getGETParameters() {
return getParameters;
}
public void setGETParameterString(String parameterString) {
this.getParameters = HTTPUtils.parseParameterString(parameterString);
}
}
......@@ -59,14 +59,14 @@ public class HTTPResponse {
return statusCode;
}
public void setStatusCode(Code statusCode) {
this.statusCode = statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = Code.fromStatusCodeNumber(statusCode);
}
public void setStatusCode(Code statusCode) {
this.statusCode = statusCode;
}
public boolean isCompressed() {
return compressed;
}
......@@ -87,6 +87,10 @@ public class HTTPResponse {
return responseData;
}
public void setResponseData(String responseData) {
setResponseData(responseData.getBytes());
}
public void setResponseData(InputStream responseData) {
this.responseData = responseData;
}
......@@ -96,10 +100,6 @@ public class HTTPResponse {
setResponseData(new ByteArrayInputStream(responseData));
}
public void setResponseData(String responseData) {
setResponseData(responseData.getBytes());
}
public void close() throws IOException {
request.close();
......@@ -164,14 +164,6 @@ public class HTTPResponse {
this.codeName = codeName;
}
public String getCodeName() {
return codeName;
}
public int getCode() {
return code;
}
public static Code fromStatusCodeNumber(int statusCode) {
for (Code code : Code.values()) {
if (code.getCode() == statusCode)
......@@ -179,5 +171,13 @@ public class HTTPResponse {
}
return null;
}
public String getCodeName() {
return codeName;
}
public int getCode() {
return code;
}
}
}
......@@ -14,16 +14,14 @@ import java.util.regex.Pattern;
public class RawSocketHandler implements RawHandler {
private final ImplifyServer serverInstance;
private final Pattern httpPattern;
public RawSocketHandler(ImplifyServer serverInstance) {
this.serverInstance = serverInstance;
this.httpPattern = Pattern.compile("(GET|POST)\\s(.*)\\sHTTP\\/(\\d\\.\\d)");
public RawSocketHandler() {
this.httpPattern = Pattern.compile("(GET|POST)\\s(.*?)(?:\\?(.*)\\s)?HTTP\\/(\\d\\.\\d)");
}
@Override
public HTTPRequest handle(Socket socket) throws ImplifyException {
public HTTPRequest handle(ImplifyServer serverInstance, Socket socket) throws ImplifyException {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
......@@ -50,7 +48,9 @@ public class RawSocketHandler implements RawHandler {
HTTPRequest request = new HTTPRequest(serverInstance, socket);
request.setRequestMethod(matcher.group(1));
request.setRequestPath(matcher.group(2));
request.setHttpVersion(matcher.group(3));
if (matcher.group(3) != null && matcher.group(3).length() > 0)
request.setGETParameterString(matcher.group(3));
request.setHttpVersion(matcher.group(4));
request.setHeaders(headers);
//TODO: Request Body
......
package net.scrumplex.implify.lang;
import net.scrumplex.implify.core.ImplifyServer;
import net.scrumplex.implify.core.exchange.HTTPRequest;
import net.scrumplex.implify.core.exchange.HTTPResponse;
import net.scrumplex.implify.exceptions.ImplifyException;
import java.io.IOException;
public interface HTTPHandler {
HTTPResponse handle(HTTPRequest request, HTTPResponse response) throws ImplifyException;
HTTPResponse handle(ImplifyServer serverInstance, HTTPRequest request, HTTPResponse response) throws ImplifyException;
}
package net.scrumplex.implify.lang;
import net.scrumplex.implify.core.ImplifyServer;
import net.scrumplex.implify.core.exchange.HTTPRequest;
import net.scrumplex.implify.core.exchange.HTTPResponse;
import net.scrumplex.implify.exceptions.ImplifyException;
import java.io.IOException;
public interface HTTPPreprocessor {
HTTPResponse process(HTTPRequest request) throws ImplifyException;
HTTPResponse process(ImplifyServer serverInstance, HTTPRequest request) throws ImplifyException;
}
package net.scrumplex.implify.lang;
import net.scrumplex.implify.core.ImplifyServer;
import net.scrumplex.implify.core.exchange.HTTPRequest;
import net.scrumplex.implify.exceptions.ImplifyException;
......@@ -7,6 +8,6 @@ import java.net.Socket;
public interface RawHandler {
HTTPRequest handle(Socket socket) throws ImplifyException;
HTTPRequest handle(ImplifyServer serverInstance, Socket socket) throws ImplifyException;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>implify Demo</title>
</head>
<h1>Implify works!</h1>
<p>This is the default page for the implify Server. You have successfully started the HTTP Server, but did not specify a
HTTPHandler. Please refer to the documentation.</p>
</html>
\ No newline at end of file
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
......
Markdown is supported
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