use of org.apache.velocity.tools.ToolContext in project openmrs-core by openmrs.
the class StartupFilter method renderTemplate.
/**
* All private attributes on this class are returned to the template via the velocity context
* and reflection
*
* @param templateName the name of the velocity file to render. This name is prepended with
* {@link #getTemplatePrefix()}
* @param referenceMap
* @param httpResponse
*/
protected void renderTemplate(String templateName, Map<String, Object> referenceMap, HttpServletResponse httpResponse) throws IOException {
// his http session) and merge that tools context with basic velocity context
if (referenceMap == null) {
return;
}
Object locale = referenceMap.get(FilterUtil.LOCALE_ATTRIBUTE);
ToolContext velocityToolContext = getToolContext(locale != null ? locale.toString() : Context.getLocale().toString());
VelocityContext velocityContext = new VelocityContext(velocityToolContext);
for (Map.Entry<String, Object> entry : referenceMap.entrySet()) {
velocityContext.put(entry.getKey(), entry.getValue());
}
Object model = getModel();
// put each of the private varibles into the template for convenience
for (Field field : model.getClass().getDeclaredFields()) {
try {
field.setAccessible(true);
velocityContext.put(field.getName(), field.get(model));
} catch (IllegalArgumentException | IllegalAccessException e) {
log.error("Error generated while getting field value: " + field.getName(), e);
}
}
String fullTemplatePath = getTemplatePrefix() + templateName;
InputStream templateInputStream = getClass().getClassLoader().getResourceAsStream(fullTemplatePath);
if (templateInputStream == null) {
throw new IOException("Unable to find " + fullTemplatePath);
}
velocityContext.put("errors", errors);
velocityContext.put("msgs", msgs);
// explicitly set the content type for the response because some servlet containers are assuming text/plain
httpResponse.setContentType("text/html");
try {
velocityEngine.evaluate(velocityContext, httpResponse.getWriter(), this.getClass().getName(), new InputStreamReader(templateInputStream, StandardCharsets.UTF_8));
} catch (Exception e) {
throw new APIException("Unable to process template: " + fullTemplatePath, e);
}
}
Aggregations