- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在寻找一个免费标记功能,例如:
<#include "big_file.json" parse="true" encode="base64">
我知道这是不可能的。有没有办法扩展 freemarker?
最佳答案
解决方案是使用:freemarker directives
解决这个例子:
"grafana_dashboards": {
<@list_dir folder="./grafana_dashboards/" suffix="json"; dashboard_file, dashboard_name, dashboard_file_has_next>
${dashboard_name}": "<@encode enc="base64"><#include dashboard_file></@encode>"<#if (dashboard_file_has_next)>,</#if>
</@list_dir>
}
我添加了这两个变量:
cfg = new Configuration(Configuration.VERSION_2_3_29);
...
final Map<String, Object> vars = new HashMap<>();
vars.put("list_dir", new xxx.freemarker.directives.ListDirDirective());
vars.put("encode", new xxx.freemarker.directives.EncodeDirective());
final Template temp = cfg.getTemplate(file.getName());
try ( //
final ByteArrayOutputStream bao = new ByteArrayOutputStream(); //
final Writer out = new OutputStreamWriter(bao); //
) {
temp.process(vars, out);
return bao.toString();
}
以下是指令:
编码指令
package xxx.freemarker.directives;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Base64;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Function;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateScalarModel;
/**
* FreeMarker user-defined directive that progressively transforms the output of
* its nested content to given encoding.
*
*
* <p>
* <b>Directive info</b>
* </p>
*
* Parameters:
* <ul>
* <li><code>enc</code>: The name of the encoding to use. Possible options:
* "base64". Required.
* </ul>
* <p>
* Loop variables: None
* <p>
* Directive nested content: Yes
*/
public class EncodeDirective implements TemplateDirectiveModel {
private static final String PARAM_NAME_ENC = "enc";
private static final Map<String, Function<String, String>> encoder = new HashMap<>();
static {
encoder.put("base64", EncodeDirective::encodeBase64);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void execute(final Environment env, final Map rawParams, final TemplateModel[] loopVars, final TemplateDirectiveBody body)
throws TemplateException, IOException {
final Params params = parseAndValidateParams(rawParams, loopVars);
// If there is non-empty nested content:
if (body != null) {
// Executes the nested body. Same as <#nested> in FTL, except
// that we use our own writer instead of the current output writer.
final EncodeFilterWriter writer = new EncodeFilterWriter(env.getOut(), params.getEncoderFunction());
body.render(writer);
writer.flush();
} else {
throw new RuntimeException("missing body");
}
}
/**
* A {@link Writer} that transforms the character stream to upper case and
* forwards it to another {@link Writer}.
*/
private static class EncodeFilterWriter extends Writer {
private StringBuffer buffer = new StringBuffer();
private final Writer out;
private final Function<String, String> encoder;
EncodeFilterWriter(final Writer out, final Function<String, String> encoder) {
this.out = out;
this.encoder = encoder;
}
public void write(final char[] cbuf, final int off, final int len) throws IOException {
buffer.append(cbuf, off, len);
}
public void flush() throws IOException {
out.write(encoder.apply(buffer.toString()));
out.flush();
}
public void close() throws IOException {
out.close();
}
}
private Params parseAndValidateParams(final Map<String, TemplateModel> params, final TemplateModel[] loopVars)
throws TemplateModelException {
boolean encParamSet = false;
final Params p = new Params();
final Iterator<Entry<String, TemplateModel>> paramIter = params.entrySet().iterator();
while (paramIter.hasNext()) {
final Entry<String, TemplateModel> ent = paramIter.next();
final String paramName = ent.getKey();
final TemplateModel paramValue = ent.getValue();
if (paramName.equals(PARAM_NAME_ENC)) {
if (!(paramValue instanceof TemplateScalarModel)) {
throw new TemplateModelException("The \"" + PARAM_NAME_ENC + "\" parameter must be a string.");
}
p.setEnc(((TemplateScalarModel) paramValue).getAsString());
encParamSet = true;
} else {
throw new TemplateModelException("Unsupported parameter: " + paramName);
}
}
if (!encParamSet) {
throw new TemplateModelException("The required \"" + PARAM_NAME_ENC + "\" paramter is missing.");
}
if (loopVars.length != 0) {
throw new TemplateModelException("This directive doesn't allow loop variables.");
}
return p;
}
@Data
private class Params {
private String enc;
public void setEnv(final String enc) {
this.enc = enc;
}
public String getEnv() {
return this.enc;
}
public Function<String, String> getEncoderFunction() throws TemplateModelException {
final Function<String, String> encoderFunc = encoder.get(enc.toLowerCase());
if (encoderFunc == null) {
throw new TemplateModelException("The required \"" + PARAM_NAME_ENC + "\" paramter, must be one of: " + encoder.keySet());
}
return encoderFunc;
}
}
private static String encodeBase64(final String in) {
try {
return Base64.getEncoder().encodeToString( //
in.getBytes("UTF-8"));
} catch (final UnsupportedEncodingException e) {
throw new IllegalArgumentException("The required \"" + PARAM_NAME_ENC + "\" paramter, encode error:: " + e.getMessage(), e);
}
}
}
ListDirDirective
package xxx.freemarker.directives;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import freemarker.cache.TemplateLoader;
import freemarker.core.Environment;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateBooleanModel;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateScalarModel;
/**
* FreeMarker user-defined directive for repeating a section of a template, that
* scan a folder on file system and loop through matching files.
*
*
* <p>
* <b>Directive info</b>
* </p>
*
* <p>
* Parameters:
* <ul>
* <li><code>folder</code>: The relative path of the folder on file system.
* Required.
* <li><code>suffix</code>: File ending too scan for. Required.
* </ul>
*
* Loop variables:
* <ul>
* <li><code>file_path</code>: String: The relative file path, used by
* "<#include" or "<#import". Required.</li>
* <li><code>file_name</code>: String: The file name without suffix.
* Optional.</li>
* <li><code>has_next</code>: Boolean: Indicator if it is last file or not.
* Optional.</li>
* </ul>
* <p>
* Nested content: Yes
*/
public class ListDirDirective implements TemplateDirectiveModel {
private static final String PARAM_NAME_FOLDER = "folder";
private static final String PARAM_NAME_SUFFIX = "suffix";
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void execute(final Environment env, final Map rawParams, final TemplateModel[] loopVars,
final TemplateDirectiveBody body) throws TemplateException, IOException {
final Path basePath = getCurrentTemplate(env).getParentFile().toPath();
final Params params = parseAndValidateParams(rawParams, loopVars);
final List<String> files = findFiles("**/*." + params.getSuffix(), basePath, params.getFolder());
if (files.isEmpty()) {
throw new IllegalArgumentException(
"No files found with suffix: " + params.getSuffix() + " using base path: " + params.getFolder());
}
if (body != null) {
final Iterator<String> filesIt = files.iterator();
while (filesIt.hasNext()) {
final String filePath = filesIt.next();
loopVars[0] = new SimpleScalar(filePath);
// Set file name without extension/suffix
if (loopVars.length > 1) {
loopVars[1] = new SimpleScalar(getFilennameWithoutSuffix(filePath, params.getSuffix()));
}
// Set has_next variable if set
if (loopVars.length > 2) {
loopVars[2] = filesIt.hasNext() ? TemplateBooleanModel.TRUE : TemplateBooleanModel.FALSE;
}
// Executes the nested body (same as <#nested> in FTL). In this
// case we don't provide a special writer as the parameter:
body.render(env.getOut());
}
}
}
private File getCurrentTemplate(final Environment env) throws IOException {
final TemplateLoader templateLoader = env.getConfiguration().getTemplateLoader();
final Object tmp = templateLoader.findTemplateSource(env.getCurrentTemplate().getSourceName());
if (!(tmp instanceof File)) {
throw new IllegalArgumentException("The ListDirDirective is only compatible with FileTemplateLoader");
}
return (File) tmp;
}
private static String getFilennameWithoutSuffix(final String filePath, final String suffix) {
final File file = new File(filePath);
return file.getName() //
.replace("\\.?" + Pattern.quote(suffix) + "$", "");
}
private static List<String> findFiles(final String pattern, final Path basePath, final String pathName)
throws IOException {
final Path path = basePath.resolve(pathName).toAbsolutePath();
final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
try (final Stream<Path> paths = Files.find(path, 10,
(currentPath, fileAttributes) -> pathMatcher.matches(currentPath))) {
return paths //
.map(basePath::relativize) //
.map(Path::toString) //
.collect(Collectors.toList());
}
}
private Params parseAndValidateParams(final Map<String, TemplateModel> params, final TemplateModel[] loopVars)
throws TemplateModelException {
boolean folderParamSet = false;
boolean suffixParamSet = false;
final Params p = new Params();
final Iterator<Entry<String, TemplateModel>> paramIter = params.entrySet().iterator();
while (paramIter.hasNext()) {
final Entry<String, TemplateModel> ent = paramIter.next();
final String paramName = ent.getKey();
final TemplateModel paramValue = ent.getValue();
if (paramName.equals(PARAM_NAME_FOLDER)) {
if (!(paramValue instanceof TemplateScalarModel)) {
throw new TemplateModelException(
"The \"" + PARAM_NAME_FOLDER + "\" parameter must be a string.");
}
p.setFolder(((TemplateScalarModel) paramValue).getAsString());
folderParamSet = true;
} else if (paramName.equals(PARAM_NAME_SUFFIX)) {
if (!(paramValue instanceof TemplateScalarModel)) {
throw new TemplateModelException(
"The \"" + PARAM_NAME_SUFFIX + "\" parameter must be a string.");
}
final String suffix = ((TemplateScalarModel) paramValue).getAsString();
if (!suffix.matches("[a-zA-Z0-9]{1,10}")) {
throw new TemplateModelException("The \"" + PARAM_NAME_SUFFIX + "\" parameter "
+ "must only contain letter and number and needs to be between 1-10 chars.");
}
p.setSuffix(suffix);
suffixParamSet = true;
} else {
throw new TemplateModelException("Unsupported parameter: " + paramName);
}
}
if (!folderParamSet) {
throw new TemplateModelException("The required \"" + PARAM_NAME_FOLDER + "\" paramter is missing.");
}
if (!suffixParamSet) {
throw new TemplateModelException("The required \"" + PARAM_NAME_SUFFIX + "\" paramter is missing.");
}
if (loopVars.length < 1) {
throw new TemplateModelException("At least 1 loop vars is required: file_name, [name], [has_next]");
}
if (loopVars.length > 3) {
throw new TemplateModelException("Max 3 loop vars are allowed: file_name, [name], [has_next]");
}
return p;
}
@Data
private class Params {
private String folder;
private String suffix;
public void setFolder(final String folder) {
this.folder = folder;
}
public String getFolder() {
return this.folder;
}
public void setSuffix(final String suffix) {
this.suffix = suffix;
}
public String getSuffix() {
return this.suffix;
}
}
}
关于java - freemarker包括+base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58826363/
我正在编写一个具有以下签名的 Java 方法。 void Logger(Method method, Object[] args); 如果一个方法(例如 ABC() )调用此方法 Logger,它应该
我是 Java 新手。 我的问题是我的 Java 程序找不到我试图用作的图像文件一个 JButton。 (目前这段代码什么也没做,因为我只是得到了想要的外观第一的)。这是我的主课 代码: packag
好的,今天我在接受采访,我已经编写 Java 代码多年了。采访中说“Java 垃圾收集是一个棘手的问题,我有几个 friend 一直在努力弄清楚。你在这方面做得怎么样?”。她是想骗我吗?还是我的一生都
我的 friend 给了我一个谜语让我解开。它是这样的: There are 100 people. Each one of them, in his turn, does the following
如果我将使用 Java 5 代码的应用程序编译成字节码,生成的 .class 文件是否能够在 Java 1.4 下运行? 如果后者可以工作并且我正在尝试在我的 Java 1.4 应用程序中使用 Jav
有关于why Java doesn't support unsigned types的问题以及一些关于处理无符号类型的问题。我做了一些搜索,似乎 Scala 也不支持无符号数据类型。限制是Java和S
我只是想知道在一个 java 版本中生成的字节码是否可以在其他 java 版本上运行 最佳答案 通常,字节码无需修改即可在 较新 版本的 Java 上运行。它不会在旧版本上运行,除非您使用特殊参数 (
我有一个关于在命令提示符下执行 java 程序的基本问题。 在某些机器上我们需要指定 -cp 。 (类路径)同时执行java程序 (test为java文件名与.class文件存在于同一目录下) jav
我已经阅读 StackOverflow 有一段时间了,现在我才鼓起勇气提出问题。我今年 20 岁,目前在我的家乡(罗马尼亚克卢日-纳波卡)就读 IT 大学。足以介绍:D。 基本上,我有一家提供簿记应用
我有 public JSONObject parseXML(String xml) { JSONObject jsonObject = XML.toJSONObject(xml); r
我已经在 Java 中实现了带有动态类型的简单解释语言。不幸的是我遇到了以下问题。测试时如下代码: def main() { def ks = Map[[1, 2]].keySet()
一直提示输入 1 到 10 的数字 - 结果应将 st、rd、th 和 nd 添加到数字中。编写一个程序,提示用户输入 1 到 10 之间的任意整数,然后以序数形式显示该整数并附加后缀。 public
我有这个 DownloadFile.java 并按预期下载该文件: import java.io.*; import java.net.URL; public class DownloadFile {
我想在 GUI 上添加延迟。我放置了 2 个 for 循环,然后重新绘制了一个标签,但这 2 个 for 循环一个接一个地执行,并且标签被重新绘制到最后一个。 我能做什么? for(int i=0;
我正在对对象 Student 的列表项进行一些测试,但是我更喜欢在 java 类对象中创建硬编码列表,然后从那里提取数据,而不是连接到数据库并在结果集中选择记录。然而,自从我这样做以来已经很长时间了,
我知道对象创建分为三个部分: 声明 实例化 初始化 classA{} classB extends classA{} classA obj = new classB(1,1); 实例化 它必须使用
我有兴趣使用 GPRS 构建车辆跟踪系统。但是,我有一些问题要问以前做过此操作的人: GPRS 是最好的技术吗?人们意识到任何问题吗? 我计划使用 Java/Java EE - 有更好的技术吗? 如果
我可以通过递归方法反转数组,例如:数组={1,2,3,4,5} 数组结果={5,4,3,2,1}但我的结果是相同的数组,我不知道为什么,请帮助我。 public class Recursion { p
有这样的标准方式吗? 包括 Java源代码-测试代码- Ant 或 Maven联合单元持续集成(可能是巡航控制)ClearCase 版本控制工具部署到应用服务器 最后我希望有一个自动构建和集成环境。
我什至不知道这是否可能,我非常怀疑它是否可能,但如果可以,您能告诉我怎么做吗?我只是想知道如何从打印机打印一些文本。 有什么想法吗? 最佳答案 这里有更简单的事情。 import javax.swin
我是一名优秀的程序员,十分优秀!