Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package de.unirostock.swt1321;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.net.ProtocolException;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.net.UnknownHostException;
- import java.util.ArrayList;
- import java.util.Locale;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import de.unirostock.swt1321.response.Response;
- import de.unirostock.swt1321.response.StringResponse;
- import de.unirostock.swt1321.routes.AliasRoute;
- import de.unirostock.swt1321.routes.DirectoryRoute;
- import de.unirostock.swt1321.routes.FileRoute;
- import de.unirostock.swt1321.routes.Route;
- import de.unirostock.swt1321.routes.ShutdownCommandRoute;
- import de.unirostock.swt1321.routes.StaticRoute;
- import de.unirostock.swt1321.utils.StringUtils;
- /**
- * Small webserver implementation. Should be used with default Locale set to
- * ENGLISH.
- *
- * @author hannes
- *
- */
- public class WebServer {
- private boolean running;
- private static Logger log = Logger.getLogger(WebServer.class
- .getCanonicalName());
- private ArrayList<Route> routes;
- public WebServer() {
- routes = new ArrayList<Route>();
- running = true;
- }
- public void shutdown() {
- running = false;
- }
- public void addRoute(Route route) {
- routes.add(route);
- }
- private Response getResponse(Request req) {
- for (Route route : routes) {
- if (route.servesRequest(req)) {
- return route.serve(req);
- }
- }
- if (!req.getUrl().endsWith("/")) {
- // Allow /index for /index/
- return getResponse(req.withURL(req.getUrl() + "/"));
- }
- return StringResponse.NotFoundResponse();
- }
- private void handleRequest(Request req, OutputStream out)
- throws IOException {
- if (req.getHTTPVersion().toUpperCase().equals("HTTP/1.1")) {
- Response resp;
- // I could make the routes do this,
- // but right now I'm thinking it would
- // make them do too much work
- switch (req.getVerb().toUpperCase()) {
- case "GET":
- resp = getResponse(req);
- resp.printOn(out);
- log.log(Level.INFO, "served: \n" + resp.toString());
- break;
- case "HEAD":
- resp = getResponse(req);
- resp.printHeaderOn(out);
- log.log(Level.INFO, "served: \n" + resp.getHeader());
- break;
- default:
- resp = StringResponse.NotImplementedResponse();
- resp.printOn(out);
- log.log(Level.INFO, "served: \n" + resp.toString());
- }
- } else {
- Response resp = StringResponse.HTTPVersionNotSupportedResponse();
- resp.printOn(out);
- log.log(Level.INFO, "served: \n" + resp.toString());
- }
- }
- public void start() throws IOException, InterruptedException {
- try (ServerSocket webSock = new ServerSocket(47000);) {
- log.log(Level.INFO,
- "Server Socket created on port: " + webSock.getLocalPort());
- while (running) {
- Socket sock = null;
- BufferedReader in = null;
- try {
- sock = webSock.accept();
- in = new BufferedReader(new InputStreamReader(
- sock.getInputStream()));
- if (in.ready()) {
- StringBuilder requestText = new StringBuilder(100);
- while (in.ready()) {
- requestText.append((char) in.read());
- }
- String requestString = requestText.toString();
- try {
- Request req = new Request(StringUtils.toNewlineTerminators(requestString));
- log.log(Level.INFO,
- "Got request:\n"
- + requestString);
- handleRequest(req, sock.getOutputStream());
- } catch (ProtocolException e) {
- StringResponse.BadRequestResponse(requestString);
- }
- }
- } finally {
- if (in != null) {
- in.close();
- in = null;
- }
- if (sock != null) {
- sock.close();
- sock = null;
- }
- }
- Thread.sleep(10);
- }
- }
- log.log(Level.INFO, "Server connection closed.");
- }
- /**
- * @param args
- * @throws IOException
- * @throws UnknownHostException
- */
- public static void main(String[] args) {
- Locale.setDefault(Locale.ENGLISH);
- try {
- WebServer web = new WebServer();
- Route indexRoute = new FileRoute("/", "content/index.html");
- web.addRoute(indexRoute);
- ArrayList<String> indexAliases = new ArrayList<String>(4);
- indexAliases.add("/index.html");
- indexAliases.add("/index/");
- web.addRoute(new AliasRoute("/", indexRoute, indexAliases));
- web.addRoute(new ShutdownCommandRoute("/shutdown", web));
- web.addRoute(new FileRoute("/kamina.gif", "content/img/e.gif"));
- web.addRoute(new StaticRoute("/static.html", "<html>" + "<head>"
- + "<title>Hello World!</title>" + "</head>" + "<body>"
- + "<h1>I am static</h1>" + "<p>Very static, in fact.</p>"
- + "</body>" + "</html>"));
- web.addRoute(new DirectoryRoute("content", "/"));
- web.start();
- } catch (IOException e) {
- System.err.println("IO Error");
- e.printStackTrace();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement