diff 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
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/goodjava/webserver/handlers/DomainHandler.java	Tue Sep 17 01:35:01 2019 -0400
@@ -0,0 +1,81 @@
+package goodjava.webserver.handlers;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.lang.ref.Reference;
+//import java.lang.ref.WeakReference;
+import java.lang.ref.SoftReference;
+import java.lang.ref.ReferenceQueue;
+import java.util.Map;
+import java.util.HashMap;
+import goodjava.logging.Logger;
+import goodjava.logging.LoggerFactory;
+import goodjava.webserver.Handler;
+import goodjava.webserver.Request;
+import goodjava.webserver.Response;
+
+
+public final class DomainHandler implements Handler {
+	private static final Logger logger = LoggerFactory.getLogger(DomainHandler.class);
+
+	public interface Factory {
+		public Handler newHandler(String domain);
+	}
+
+	private static void close(Handler handler) {
+		if( handler instanceof Closeable ) {
+			try {
+				((Closeable)handler).close();
+			} catch(IOException e) {
+				logger.error(handler.toString(),e);
+			}
+		}
+	}
+
+	private final Map<String,Reference<Handler>> map = new HashMap<String,Reference<Handler>>();
+
+	private final Factory factory;
+
+	public DomainHandler(Factory factory) {
+		this.factory = factory;
+	}
+
+	public Response handle(Request request) {
+		String host = (String)request.headers.get("host");
+		if( host == null )
+			return null;
+		int i = host.indexOf(':');
+		String domain = i == -1 ? host : host.substring(0,i);
+		Handler handler = getHandler(domain);
+		return handler==null ? null : handler.handle(request);
+	}
+
+	public Handler getHandler(String domain) {
+		domain = domain.toLowerCase();
+		synchronized(map) {
+			Reference<Handler> ref = map.get(domain);
+			Handler handler = ref==null ? null : ref.get();
+			if( handler == null ) {
+				//if(ref!=null) logger.info("gc "+domain);
+				handler = factory.newHandler(domain);
+				if( handler == null )
+					return null;
+				map.put(domain,new SoftReference<Handler>(handler));
+			}
+			return handler;
+		}
+	}
+
+	public void removeHandler(String domain) {
+		logger.info("removeHandler "+domain);
+		domain = domain.toLowerCase();
+		synchronized(map) {
+			Reference<Handler> ref = map.remove(domain);
+			Handler handler = ref==null ? null : ref.get();
+			if( handler != null ) {
+				close(handler);
+			}
+		}
+	}
+
+}