66 lines
2.1 KiB
Java
66 lines
2.1 KiB
Java
package de.srsoftware.widerhall.web;
|
|
|
|
import de.srsoftware.widerhall.Configuration;
|
|
import org.stringtemplate.v4.ST;
|
|
import org.stringtemplate.v4.STGroup;
|
|
import org.stringtemplate.v4.STRawGroupDir;
|
|
|
|
import javax.servlet.http.HttpServlet;
|
|
import javax.servlet.http.HttpServletResponse;
|
|
import java.io.File;
|
|
import java.io.IOException;
|
|
import java.nio.file.Files;
|
|
import java.util.Map;
|
|
|
|
import static de.srsoftware.widerhall.Util.t;
|
|
|
|
public abstract class TemplateServlet extends HttpServlet {
|
|
private STGroup templates;
|
|
private final String baseDir;
|
|
|
|
public TemplateServlet(){
|
|
var config = Configuration.instance();
|
|
baseDir = config.baseDir();
|
|
loadTemplates();
|
|
}
|
|
|
|
protected ST getTemplate(String name){
|
|
return templates.getInstanceOf(name);
|
|
}
|
|
|
|
protected String loadFile(String filename, HttpServletResponse resp) {
|
|
var path = String.join(File.separator,baseDir,"static",filename);
|
|
var file = new File(path);
|
|
if (!file.exists()) return t("File {} does not exist!",filename);
|
|
try {
|
|
var content = Files.readAllBytes(file.toPath());
|
|
var out = resp.getOutputStream();
|
|
out.write(content);
|
|
out.flush();
|
|
} catch (IOException e) {
|
|
return t("Failed to load file '{}'!",filename);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
protected String loadTemplate(String path, Map<String, ? extends Object> data, HttpServletResponse resp) {
|
|
var template = templates.getInstanceOf(path);
|
|
if (template != null){
|
|
try {
|
|
resp.setCharacterEncoding("UTF-8");
|
|
template.add("data",data);
|
|
resp.getWriter().println(template.render());
|
|
return null;
|
|
} catch (IOException e) {
|
|
return t("Failed to load template '{}'!",path);
|
|
}
|
|
}
|
|
return t("No template for path '{}'!",path);
|
|
}
|
|
|
|
protected void loadTemplates() {
|
|
var templateDir = String.join(File.separator,baseDir,"static","templates");
|
|
templates = new STRawGroupDir(templateDir,'«','»');
|
|
}
|
|
}
|