use of freemarker.template.Template in project leopard by tanhaichao.
the class FtlView method getTemplate.
@Override
protected Template getTemplate(String name, Locale locale) throws IOException {
// TemplateLoader tl = getConfiguration().getTemplateLoader();
Configuration conf = getConfiguration();
conf.setTemplateLoader(new ClassTemplateLoader(this.getClass(), folder));
Template tmp = (getEncoding() != null ? conf.getTemplate(name, locale, getEncoding()) : conf.getTemplate(name, locale));
return tmp;
// return super.getTemplate(name, locale);
}
use of freemarker.template.Template in project leopard by tanhaichao.
the class AbstractTemplateView method render.
public void render(HttpServletRequest request, HttpServletResponse response) throws IOException {
RequestHolder.setRequest(request);
Configuration config = new Configuration();
ConfigurationHolder.setConfiguration(config);
// 设置要解析的模板所在的目录,并加载模板文件
// config.setDirectoryForTemplateLoading(templateFile);
config.setTemplateLoader(new ClassTemplateLoader(this.getClass(), folder));
// 设置包装器,并将对象包装为数据模型
config.setObjectWrapper(new DefaultObjectWrapper());
config.setDefaultEncoding("UTF-8");
Map<String, Object> freemarkerVariables = new HashMap<String, Object>();
freemarkerVariables.put("xml_escape", "fmXmlEscape");
List<TemplateVariable> variables = this.getVariables();
if (variables != null) {
for (TemplateVariable variable : variables) {
freemarkerVariables.put(variable.getKey(), variable);
}
}
// freemarkerVariables.put("time", new TimeTemplateMethod());
// freemarkerVariables.put("url", new UrlTemplateMethod());
// freemarkerVariables.put("underline", new UnderlineTemplateMethod());
Properties freemarkerSettings = new Properties();
freemarkerSettings.put("template_update_delay", "1");
freemarkerSettings.put("defaultEncoding", "UTF-8");
try {
config.setSettings(freemarkerSettings);
config.setAllSharedVariables(new SimpleHash(freemarkerVariables, config.getObjectWrapper()));
} catch (TemplateException e) {
throw new IOException(e);
}
// 获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致
// 否则会出现乱码
Template template = config.getTemplate(templateName + ".ftl", Locale.CHINA, "UTF-8");
template.setCustomAttribute("request", request);
model.put("request", request);
StringWriter writer = new StringWriter();
// Writer out = response.getWriter();
try {
template.process(model, writer);
} catch (TemplateException e) {
throw new IOException(e);
}
output(writer, response);
// Template tmp = (getEncoding() != null ? conf.getTemplate(name,
// locale, getEncoding()) : conf.getTemplate(name, locale));
}
use of freemarker.template.Template in project leopard by tanhaichao.
the class BodyTemplateDirective method execute.
@Override
public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
// String folder = ((SimpleScalar) params.get("template_folder")).getAsString();
String templateName = ((SimpleScalar) params.get("template_name")).getAsString();
// String templateName = (String) params.get("template_name");
Template template = env.getConfiguration().getTemplate(templateName + ".ftl");
template.process(DATA.get(), env.getOut());
}
use of freemarker.template.Template in project camel by apache.
the class FreemarkerEndpoint method onExchange.
@Override
protected void onExchange(Exchange exchange) throws Exception {
String path = getResourceUri();
ObjectHelper.notNull(configuration, "configuration");
ObjectHelper.notNull(path, "resourceUri");
String newResourceUri = exchange.getIn().getHeader(FreemarkerConstants.FREEMARKER_RESOURCE_URI, String.class);
if (newResourceUri != null) {
exchange.getIn().removeHeader(FreemarkerConstants.FREEMARKER_RESOURCE_URI);
log.debug("{} set to {} creating new endpoint to handle exchange", FreemarkerConstants.FREEMARKER_RESOURCE_URI, newResourceUri);
FreemarkerEndpoint newEndpoint = findOrCreateEndpoint(getEndpointUri(), newResourceUri);
newEndpoint.onExchange(exchange);
return;
}
Reader reader = null;
String content = exchange.getIn().getHeader(FreemarkerConstants.FREEMARKER_TEMPLATE, String.class);
if (content != null) {
// use content from header
reader = new StringReader(content);
// remove the header to avoid it being propagated in the routing
exchange.getIn().removeHeader(FreemarkerConstants.FREEMARKER_TEMPLATE);
}
Object dataModel = exchange.getIn().getHeader(FreemarkerConstants.FREEMARKER_DATA_MODEL, Object.class);
if (dataModel == null) {
dataModel = ExchangeHelper.createVariableMap(exchange);
}
// let freemarker parse and generate the result in buffer
Template template;
if (reader != null) {
log.debug("Freemarker is evaluating template read from header {} using context: {}", FreemarkerConstants.FREEMARKER_TEMPLATE, dataModel);
template = new Template("temp", reader, new Configuration());
} else {
log.debug("Freemarker is evaluating {} using context: {}", path, dataModel);
if (getEncoding() != null) {
template = configuration.getTemplate(path, getEncoding());
} else {
template = configuration.getTemplate(path);
}
}
StringWriter buffer = new StringWriter();
template.process(dataModel, buffer);
buffer.flush();
// now lets output the results to the exchange
Message out = exchange.getOut();
out.setBody(buffer.toString());
out.setHeaders(exchange.getIn().getHeaders());
out.setAttachments(exchange.getIn().getAttachments());
}
use of freemarker.template.Template in project opennms by OpenNMS.
the class RScriptExecutor method exec.
/**
* Executes by given script by:
* - Searching both the classpath and the filesystem for the path
* - Copying the script at the given path to a temporary file and
* performing variable substitution with the arguments using Freemarker.
* - Invoking the script with commons-exec
* - Converting the input table to CSV and passing this to the process via stdin
* - Parsing stdout, expecting CSV output, and converting this to an immutable table
*/
public RScriptOutput exec(String script, RScriptInput input) throws RScriptException {
Preconditions.checkNotNull(script, "script argument");
Preconditions.checkNotNull(input, "input argument");
// Grab the script/template
Template template;
try {
template = m_freemarkerConfiguration.getTemplate(script);
} catch (IOException e) {
throw new RScriptException("Failed to read the script.", e);
}
// Create a temporary file
File scriptOnDisk;
try {
scriptOnDisk = File.createTempFile("Rcsript", "R");
scriptOnDisk.deleteOnExit();
} catch (IOException e) {
throw new RScriptException("Failed to create a temporary file.", e);
}
// Perform variable substitution and write the results to the temporary file
try (FileOutputStream fos = new FileOutputStream(scriptOnDisk);
Writer out = new OutputStreamWriter(fos)) {
template.process(input.getArguments(), out);
} catch (IOException | TemplateException e) {
scriptOnDisk.delete();
throw new RScriptException("Failed to process the template.", e);
}
// Convert the input matrix to a CSV string which will be passed to the script via stdin.
// The table may be large, so we try and avoid writing it to disk
final StringBuilder inputTableAsCsv;
try {
inputTableAsCsv = toCsv(input.getTable());
} catch (IOException e) {
scriptOnDisk.delete();
throw new RScriptException("Failed to convert the input table to CSV.", e);
}
// Invoke Rscript against the script (located in a temporary file)
CommandLine cmdLine = new CommandLine(RSCRIPT_BINARY);
cmdLine.addArgument(scriptOnDisk.getAbsolutePath());
// Use commons-exec to execute the process
DefaultExecutor executor = new DefaultExecutor();
// Use the CharSequenceInputStream in order to avoid explicitly converting
// the StringBuilder a string and then an array of bytes.
InputStream stdin = new CharSequenceInputStream(inputTableAsCsv, StandardCharsets.UTF_8);
ByteArrayOutputStream stderr = new ByteArrayOutputStream();
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
executor.setStreamHandler(new PumpStreamHandler(stdout, stderr, stdin));
// Fail if we get a non-zero exit code
executor.setExitValue(0);
// Fail if the process takes too long
ExecuteWatchdog watchdog = new ExecuteWatchdog(SCRIPT_TIMEOUT_MS);
executor.setWatchdog(watchdog);
// Execute
try {
executor.execute(cmdLine);
} catch (IOException e) {
scriptOnDisk.delete();
throw new RScriptException("An error occured while executing Rscript, or the requested script.", inputTableAsCsv.toString(), stderr.toString(), stdout.toString(), e);
}
// Parse and return the results
try {
ImmutableTable<Long, String, Double> table = fromCsv(stdout.toString());
return new RScriptOutput(table);
} catch (Throwable t) {
throw new RScriptException("Failed to parse the script's output.", inputTableAsCsv.toString(), stderr.toString(), stdout.toString(), t);
} finally {
scriptOnDisk.delete();
}
}
Aggregations