comparison src/goodjava/webserver/examples/Example.java @ 1402:27efb1fcbcb5

move luan.lib to goodjava
author Franklin Schmidt <fschmidt@gmail.com>
date Tue, 17 Sep 2019 01:35:01 -0400
parents src/luan/lib/webserver/examples/Example.java@643cf1c37723
children 219f2b937f2b
comparison
equal deleted inserted replaced
1401:ef1620aa99cb 1402:27efb1fcbcb5
1 package goodjava.webserver.examples;
2
3 import java.io.Writer;
4 import java.io.OutputStreamWriter;
5 import java.io.IOException;
6 import java.util.Map;
7 import java.util.HashMap;
8 import org.apache.log4j.EnhancedPatternLayout;
9 import org.apache.log4j.ConsoleAppender;
10 import org.apache.log4j.Logger;
11 import goodjava.webserver.Handler;
12 import goodjava.webserver.Request;
13 import goodjava.webserver.Response;
14 import goodjava.webserver.ResponseOutputStream;
15 import goodjava.webserver.Server;
16 import goodjava.webserver.handlers.MapHandler;
17 import goodjava.webserver.handlers.SafeHandler;
18 import goodjava.webserver.handlers.LogHandler;
19 import goodjava.webserver.handlers.FileHandler;
20 import goodjava.webserver.handlers.DirHandler;
21 import goodjava.webserver.handlers.ListHandler;
22 import goodjava.webserver.handlers.ContentTypeHandler;
23
24
25 public class Example implements Handler {
26
27 public Response handle(Request request) {
28 Response response = new Response();
29 response.headers.put( "content-type", "text/plain; charset=utf-8" );
30 try {
31 Writer writer = new OutputStreamWriter( new ResponseOutputStream(response) );
32 writer.write("Hello World\n");
33 writer.close();
34 } catch(IOException e) {
35 throw new RuntimeException("shouldn't happen",e);
36 }
37 return response;
38 }
39
40 public static void simple() throws IOException {
41 Handler handler = new Example();
42 new Server(8080,handler).start();
43 }
44
45 public static void fancy() throws IOException {
46 Map<String,Handler> map = new HashMap<String,Handler>();
47 map.put( "/hello", new Example() );
48 map.put( "/headers", new Headers() );
49 map.put( "/params", new Params() );
50 map.put( "/cookies", new Cookies() );
51 Handler mapHandler = new MapHandler(map);
52 FileHandler fileHandler = new FileHandler();
53 Handler dirHandler = new DirHandler(fileHandler);
54 Handler handler = new ListHandler( mapHandler, fileHandler, dirHandler );
55 handler = new ContentTypeHandler(handler);
56 handler = new SafeHandler(handler);
57 handler = new LogHandler(handler);
58 new Server(8080,handler).start();
59 }
60
61 public static void initLogging() {
62 // Logger.getRootLogger().setLevel(Level.INFO);
63 EnhancedPatternLayout layout = new EnhancedPatternLayout("%d{HH:mm:ss} %-5p %c - %m%n");
64 ConsoleAppender appender = new ConsoleAppender(layout,"System.err");
65 Logger.getRootLogger().addAppender(appender);
66 }
67
68 public static void main(String[] args) throws Exception {
69 initLogging();
70 fancy();
71 }
72 }