Advertisement
Guest User

Java simple webserver

a guest
Nov 25th, 2012
519
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.91 KB | None | 0 0
  1. package de.unirostock.swt1321;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.io.OutputStream;
  7. import java.net.ProtocolException;
  8. import java.net.ServerSocket;
  9. import java.net.Socket;
  10. import java.net.UnknownHostException;
  11. import java.util.ArrayList;
  12. import java.util.Locale;
  13. import java.util.logging.Level;
  14. import java.util.logging.Logger;
  15.  
  16. import de.unirostock.swt1321.response.Response;
  17. import de.unirostock.swt1321.response.StringResponse;
  18. import de.unirostock.swt1321.routes.AliasRoute;
  19. import de.unirostock.swt1321.routes.DirectoryRoute;
  20. import de.unirostock.swt1321.routes.FileRoute;
  21. import de.unirostock.swt1321.routes.Route;
  22. import de.unirostock.swt1321.routes.ShutdownCommandRoute;
  23. import de.unirostock.swt1321.routes.StaticRoute;
  24. import de.unirostock.swt1321.utils.StringUtils;
  25.  
  26. /**
  27.  * Small webserver implementation. Should be used with default Locale set to
  28.  * ENGLISH.
  29.  *
  30.  * @author hannes
  31.  *
  32.  */
  33. public class WebServer {
  34.     private boolean running;
  35.     private static Logger log = Logger.getLogger(WebServer.class
  36.             .getCanonicalName());
  37.     private ArrayList<Route> routes;
  38.  
  39.     public WebServer() {
  40.         routes = new ArrayList<Route>();
  41.         running = true;
  42.     }
  43.  
  44.     public void shutdown() {
  45.         running = false;
  46.     }
  47.  
  48.     public void addRoute(Route route) {
  49.         routes.add(route);
  50.     }
  51.  
  52.     private Response getResponse(Request req) {
  53.         for (Route route : routes) {
  54.             if (route.servesRequest(req)) {
  55.                 return route.serve(req);
  56.             }
  57.         }
  58.         if (!req.getUrl().endsWith("/")) {
  59.             // Allow /index for /index/
  60.             return getResponse(req.withURL(req.getUrl() + "/"));
  61.         }
  62.         return StringResponse.NotFoundResponse();
  63.     }
  64.  
  65.     private void handleRequest(Request req, OutputStream out)
  66.             throws IOException {
  67.         if (req.getHTTPVersion().toUpperCase().equals("HTTP/1.1")) {
  68.             Response resp;
  69.             // I could make the routes do this,
  70.             // but right now I'm thinking it would
  71.             // make them do too much work
  72.             switch (req.getVerb().toUpperCase()) {
  73.             case "GET":
  74.                 resp = getResponse(req);
  75.                 resp.printOn(out);
  76.                 log.log(Level.INFO, "served: \n" + resp.toString());
  77.                 break;
  78.             case "HEAD":
  79.                 resp = getResponse(req);
  80.                 resp.printHeaderOn(out);
  81.                 log.log(Level.INFO, "served: \n" + resp.getHeader());
  82.                 break;
  83.             default:
  84.                 resp = StringResponse.NotImplementedResponse();
  85.                 resp.printOn(out);
  86.                 log.log(Level.INFO, "served: \n" + resp.toString());
  87.             }
  88.         } else {
  89.             Response resp = StringResponse.HTTPVersionNotSupportedResponse();
  90.             resp.printOn(out);
  91.             log.log(Level.INFO, "served: \n" + resp.toString());
  92.         }
  93.     }
  94.  
  95.     public void start() throws IOException, InterruptedException {
  96.         try (ServerSocket webSock = new ServerSocket(47000);) {
  97.             log.log(Level.INFO,
  98.                     "Server Socket created on port: " + webSock.getLocalPort());
  99.             while (running) {
  100.                 Socket sock = null;
  101.                 BufferedReader in = null;
  102.                 try {
  103.                     sock = webSock.accept();
  104.                     in = new BufferedReader(new InputStreamReader(
  105.                             sock.getInputStream()));
  106.                     if (in.ready()) {
  107.                         StringBuilder requestText = new StringBuilder(100);
  108.                         while (in.ready()) {
  109.                             requestText.append((char) in.read());
  110.                         }
  111.                         String requestString = requestText.toString();
  112.                         try {
  113.                             Request req = new Request(StringUtils.toNewlineTerminators(requestString));
  114.                             log.log(Level.INFO,
  115.                                     "Got request:\n"
  116.                                             + requestString);
  117.                             handleRequest(req, sock.getOutputStream());
  118.  
  119.                         } catch (ProtocolException e) {
  120.                             StringResponse.BadRequestResponse(requestString);
  121.                         }
  122.                     }
  123.                 } finally {
  124.                     if (in != null) {
  125.                         in.close();
  126.                         in = null;
  127.                     }
  128.                     if (sock != null) {
  129.                         sock.close();
  130.                         sock = null;
  131.                     }
  132.                 }
  133.                 Thread.sleep(10);
  134.             }
  135.  
  136.         }
  137.         log.log(Level.INFO, "Server connection closed.");
  138.  
  139.     }
  140.  
  141.     /**
  142.      * @param args
  143.      * @throws IOException
  144.      * @throws UnknownHostException
  145.      */
  146.     public static void main(String[] args) {
  147.         Locale.setDefault(Locale.ENGLISH);
  148.         try {
  149.             WebServer web = new WebServer();
  150.             Route indexRoute = new FileRoute("/", "content/index.html");
  151.             web.addRoute(indexRoute);
  152.             ArrayList<String> indexAliases = new ArrayList<String>(4);
  153.             indexAliases.add("/index.html");
  154.             indexAliases.add("/index/");
  155.             web.addRoute(new AliasRoute("/", indexRoute, indexAliases));
  156.             web.addRoute(new ShutdownCommandRoute("/shutdown", web));
  157.             web.addRoute(new FileRoute("/kamina.gif", "content/img/e.gif"));
  158.             web.addRoute(new StaticRoute("/static.html", "<html>" + "<head>"
  159.                     + "<title>Hello World!</title>" + "</head>" + "<body>"
  160.                     + "<h1>I am static</h1>" + "<p>Very static, in fact.</p>"
  161.                     + "</body>" + "</html>"));
  162.             web.addRoute(new DirectoryRoute("content", "/"));
  163.             web.start();
  164.         } catch (IOException e) {
  165.             System.err.println("IO Error");
  166.             e.printStackTrace();
  167.         } catch (InterruptedException e) {
  168.             e.printStackTrace();
  169.         }
  170.     }
  171.  
  172. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement