CardGenerator.java 2.12 KB
import freemarker.template.TemplateExceptionHandler;

import java.io.*;
import java.util.*;

/**
 * @Description: TODO
 * @author: charles
 * @date: 2022年05月27日 10:13
 */
public class CardGenerator {

    private static final String PROJECT_PATH = System.getProperty("user.dir");//项目在硬盘上的基础路径

    private static final String TEMPLATE_FILE_PATH =PROJECT_PATH+ "/src/main/resources";//模板位置

    private static final List<String> APP_TYPE = Arrays.asList("理想玩伴","皮皮");



    public static void main(String[] args) {
        List<Map<String, Object>> select_statics = new ArrayList<>();

        Map<String, Object> select_actions = new HashMap<>();
        select_actions.put("actionContent", "所属App");

        select_actions.put("selectOptions", APP_TYPE);
        select_statics.add(select_actions);

        genMsgCard("red", "一段文本", select_statics);
    }

    public static void genMsgCard(String color, String content, List<Map<String, Object>> select_statics) {
        try {
            freemarker.template.Configuration cfg = getConfiguration();

            Map<String, Object> data = new HashMap<>();
            data.put("color", color);
            data.put("content", content);
            data.put("select_statics", select_statics);

            StringWriter stringWriter = new StringWriter();
            cfg.getTemplate("templates/msg-card.ftl").process(data,
                    stringWriter);
            System.out.println(stringWriter.toString());
            stringWriter.flush();
            System.out.println("生成成功");
        } catch (Exception e) {
            throw new RuntimeException("生成失败", e);
        }
    }

    private static freemarker.template.Configuration getConfiguration() throws IOException {
        freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23);
        cfg.setDirectoryForTemplateLoading(new File(TEMPLATE_FILE_PATH));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        return cfg;
    }
}