Mercurial Hosting > luan
comparison src/goodjava/webserver/handlers/DomainHandler.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/handlers/DomainHandler.java@ef1620aa99cb |
children | 546edc2df02c |
comparison
equal
deleted
inserted
replaced
1401:ef1620aa99cb | 1402:27efb1fcbcb5 |
---|---|
1 package goodjava.webserver.handlers; | |
2 | |
3 import java.io.Closeable; | |
4 import java.io.IOException; | |
5 import java.lang.ref.Reference; | |
6 //import java.lang.ref.WeakReference; | |
7 import java.lang.ref.SoftReference; | |
8 import java.lang.ref.ReferenceQueue; | |
9 import java.util.Map; | |
10 import java.util.HashMap; | |
11 import goodjava.logging.Logger; | |
12 import goodjava.logging.LoggerFactory; | |
13 import goodjava.webserver.Handler; | |
14 import goodjava.webserver.Request; | |
15 import goodjava.webserver.Response; | |
16 | |
17 | |
18 public final class DomainHandler implements Handler { | |
19 private static final Logger logger = LoggerFactory.getLogger(DomainHandler.class); | |
20 | |
21 public interface Factory { | |
22 public Handler newHandler(String domain); | |
23 } | |
24 | |
25 private static void close(Handler handler) { | |
26 if( handler instanceof Closeable ) { | |
27 try { | |
28 ((Closeable)handler).close(); | |
29 } catch(IOException e) { | |
30 logger.error(handler.toString(),e); | |
31 } | |
32 } | |
33 } | |
34 | |
35 private final Map<String,Reference<Handler>> map = new HashMap<String,Reference<Handler>>(); | |
36 | |
37 private final Factory factory; | |
38 | |
39 public DomainHandler(Factory factory) { | |
40 this.factory = factory; | |
41 } | |
42 | |
43 public Response handle(Request request) { | |
44 String host = (String)request.headers.get("host"); | |
45 if( host == null ) | |
46 return null; | |
47 int i = host.indexOf(':'); | |
48 String domain = i == -1 ? host : host.substring(0,i); | |
49 Handler handler = getHandler(domain); | |
50 return handler==null ? null : handler.handle(request); | |
51 } | |
52 | |
53 public Handler getHandler(String domain) { | |
54 domain = domain.toLowerCase(); | |
55 synchronized(map) { | |
56 Reference<Handler> ref = map.get(domain); | |
57 Handler handler = ref==null ? null : ref.get(); | |
58 if( handler == null ) { | |
59 //if(ref!=null) logger.info("gc "+domain); | |
60 handler = factory.newHandler(domain); | |
61 if( handler == null ) | |
62 return null; | |
63 map.put(domain,new SoftReference<Handler>(handler)); | |
64 } | |
65 return handler; | |
66 } | |
67 } | |
68 | |
69 public void removeHandler(String domain) { | |
70 logger.info("removeHandler "+domain); | |
71 domain = domain.toLowerCase(); | |
72 synchronized(map) { | |
73 Reference<Handler> ref = map.remove(domain); | |
74 Handler handler = ref==null ? null : ref.get(); | |
75 if( handler != null ) { | |
76 close(handler); | |
77 } | |
78 } | |
79 } | |
80 | |
81 } |