}
private void handle(HttpExchange httpExchange, String path, String query, Map<String, Object> params) throws IOException {
if (path.toLowerCase().endsWith(".html") || path.toLowerCase().endsWith(".htm")) {
TemplateRenderer renderer;
StringWriter sw = new StringWriter();
String rCharset;
try {
renderer = rendererFactory.create(path, null, null);
rCharset = renderer.charset == null ? "utf-8" : renderer.charset;
StringBuilder sb = new StringBuilder();
File file = new File(root, path);
char[] buf = new char[8192];
int rd;
InputStreamReader reader = new InputStreamReader(new FileInputStream(file), rCharset);
try {
while ((rd = reader.read(buf)) != -1) {
sb.append(buf, 0, rd);
}
} finally {
reader.close();
}
Map<String, Object> ctx = null;
Pattern pat = Pattern.compile("<script.*?>\\s*var _model\\s*=\\s*(.+?);?\\s*</script>",
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher matcher = pat.matcher(sb.toString());
if (matcher.find()) {
Map<String, Object> map = mapper.readValue(matcher.group(1), Map.class);
if (map.size() == 1) {
ctx = (Map) map.entrySet().iterator().next().getValue();
} else if (map.size() > 1) {
String mi = null;
try {
Object o = params.get("_model");
if (o instanceof String[]) {
mi = ((String[]) o)[0];
}
} catch (Exception ignored) {
}
ctx = (Map) map.get(mi);
if (ctx == null) {
ModelSelectDlg dlg = new ModelSelectDlg(path, map.keySet());
dlg.setVisible(true);
if (dlg.selected != null) {
ctx = (Map) map.get(dlg.selected);
}
}
}
}
if (ctx == null) ctx = Collections.emptyMap();
renderer.render(sw, ctx);
} catch (Exception e) {
except(httpExchange, e);
return;
}