it.espr.mvc.Dispatcher Maven / Gradle / Ivy
package it.espr.mvc;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import it.espr.injector.Injector;
import it.espr.mvc.converter.StringToTypeConverterFactory;
@SuppressWarnings("serial")
public class Dispatcher extends HttpServlet {
private static final Logger log = LoggerFactory.getLogger(Dispatcher.class);
private Injector injector;
private Router router;
private ViewResolver viewResolver;
private StringToTypeConverterFactory stringToTypeConverterFactory;
public void init() throws ServletException {
try {
Configuration configuration = (Configuration) Class.forName(this.getInitParameter("configuration")).newInstance();
this.injector = Injector.injector(configuration);
this.router = this.injector.get(Router.class);
this.viewResolver = this.injector.get(ViewResolver.class);
this.stringToTypeConverterFactory = this.injector.get(StringToTypeConverterFactory.class);
} catch (Exception e) {
log.error("Problem when loading configuration for mvc dispatcher", e);
throw new ServletException("Can't start app.", e);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.dispatch(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.dispatch(request, response);
}
private void dispatch(HttpServletRequest request, HttpServletResponse response) throws IOException {
String uri = URLDecoder.decode(request.getRequestURI(), "UTF-8");
String requestType = request.getMethod().toLowerCase();
Pair> pair = this.router.route(uri, requestType);
if (pair == null) {
return;
}
Route route = pair.p1;
Object model = injector.get(route.model);
List