/*
http-base - Extensions to jdk.httpserver
Copyright (C) 2021 Ulrich Hilger
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
*/
package de.uhilger.httpserver.base.actor;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import de.uhilger.httpserver.base.handler.AttributeHandler;
import de.uhilger.httpserver.base.handler.HandlerDescriptor;
import de.uhilger.httpserver.base.handler.PatternDelegator;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import java.util.logging.Level;
/**
* Der DelegateActor delegiert die Bearbeitung einer HTTP-Anfrage an einen
* HttpHandler. Zu einem bestimmten
* Muster passende URLs werden an den zum Muster hinterlegten HttpHandler
* weitergegeben.
*
* @author Ulrich Hilger
* @version 1, 03.07.2021
*/
public class DelegateActor {
/** Der Logger dieser Klasse */
private static final Logger logger = Logger.getLogger(DelegateActor.class.getName());
public boolean handle(HttpExchange exchange, Map handlers) throws IOException {
String path = exchange.getRequestURI().getPath();
logger.fine("path: " + path);
Set keys = handlers.keySet();
Iterator i = keys.iterator();
boolean noMatch = true;
while(i.hasNext() && noMatch) {
String regex = i.next();
logger.fine("regex: " + regex);
if(path.matches(regex)) {
try {
noMatch = false;
logger.fine("match");
//HttpHandler handler = handlers.get(regex);
HandlerDescriptor hd = handlers.get(regex);
String handlerClass = hd.getHandlerClassName();
Object o = Class.forName(handlerClass).getConstructors()[0].newInstance();
if(o instanceof AttributeHandler) {
AttributeHandler handler = (AttributeHandler) o;
Map attrs = hd.getAttributes();
Iterator it = attrs.keySet().iterator();
while(it.hasNext()) {
String key = it.next();
String value = attrs.get(key);
handler.setAttribute(key, value);
}
handler.handle(exchange);
} else if(o instanceof HttpHandler) {
HttpHandler handler = (HttpHandler) o;
handler.handle(exchange);
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(PatternDelegator.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return noMatch;
}
}