package org.aplikator.server;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import freemarker.core.Environment;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
/**
*
*/
@WebServlet(
name = "IndexServlet",
urlPatterns = {"/index.html"})
public class IndexServlet extends HttpServlet {
private static final String CHAR_ENCODING = "UTF-8";
private static Configuration getFreemarkerConfig() {
return LazyHolder.instance;
}
private static Configuration instance() {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
cfg.setClassForTemplateLoading(IndexServlet.class, "");
cfg.setDefaultEncoding(CHAR_ENCODING);
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
return cfg;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Map<String, String> root = new HashMap<String, String>();
root.put("context", req.getContextPath().replace("/", ""));
root.put("title", Configurator.get().getLocalizedString("aplikator.brand", req.getLocale()));
/* Get the template (uses cache internally) */
Template temp = getFreemarkerConfig().getTemplate("index.ftlh");
/* Merge data-model with template */
Writer out = new OutputStreamWriter(resp.getOutputStream(), CHAR_ENCODING);
try {
//temp.process(root, out);
Environment env = temp.createProcessingEnvironment(root, out);
env.setOutputEncoding(CHAR_ENCODING);
env.process();
} catch (TemplateException e) {
throw new ServletException(e);
}
}
private static class LazyHolder {
private static Configuration instance = instance();
}
}