Java Code Examples for freemarker.template.Configuration#getTemplate()

The following examples show how to use freemarker.template.Configuration#getTemplate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HeaderSampler.java    From log-synth with Apache License 2.0 6 votes vote down vote up
private void setupTemplate() throws IOException {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_21);
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setTemplateLoader(new ClassTemplateLoader(getClass(), "/web-headers"));
    String templateName = "header";
    switch (headerType) {
        case MAL3:
            templateName = "mal3";
            break;
        case ABABIL:
            templateName = "ababil";
            break;
        default:
            break;
    }
    template = cfg.getTemplate(templateName);
}
 
Example 2
Source File: FreemarkerRenderer.java    From act with GNU General Public License v3.0 6 votes vote down vote up
private void init(String dbHost, Integer dbPort, String dbName, String dnaCollection, String pathwayCollection) throws IOException {
  cfg = new Configuration(Configuration.VERSION_2_3_23);

  cfg.setClassLoaderForTemplateLoading(
      this.getClass().getClassLoader(), "/act/installer/reachablesexplorer/templates");
  cfg.setDefaultEncoding("UTF-8");

  cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
  cfg.setLogTemplateExceptions(true);

  reachableTemplate = cfg.getTemplate(reachableTemplateName);
  pathwayTemplate = cfg.getTemplate(pathwayTemplateName);

  // TODO: move this elsewhere.
  MongoClient client = new MongoClient(new ServerAddress(dbHost, dbPort));
  DB db = client.getDB(dbName);

  dnaDesignCollection = JacksonDBCollection.wrap(db.getCollection(dnaCollection), DNADesign.class, String.class);
  Cascade.setCollectionName(pathwayCollection);
}
 
Example 3
Source File: JiraContentFormatter.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private String buildDescription(String jiraTemplate, Map<String, Object> templateValues) {
  String description;

  // Render the values in templateValues map to the jira ftl template file
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  try (Writer out = new OutputStreamWriter(baos, CHARSET)) {
    Configuration freemarkerConfig = new Configuration(Configuration.VERSION_2_3_21);
    freemarkerConfig.setClassForTemplateLoading(getClass(), "/org/apache/pinot/thirdeye/detector");
    freemarkerConfig.setDefaultEncoding(CHARSET);
    freemarkerConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    Template template = freemarkerConfig.getTemplate(jiraTemplate);
    template.process(templateValues, out);

    description = new String(baos.toByteArray(), CHARSET);
  } catch (Exception e) {
    description = "Found an exception while constructing the description content. Pls report & reach out"
        + " to the Thirdeye team. Exception = " + e.getMessage();
  }

  return description;
}
 
Example 4
Source File: MailUtil.java    From SpringBootUnity with MIT License 6 votes vote down vote up
/**
 * 返回激活链接
 *
 * @param email email
 * @return 有3个参数 email password
 */
public static String getContent(String email, String password, Configuration configuration) {
    Long now = TimeUtil.getNowOfMills();
    Map<String, Object> data = new HashMap<>(10);
    StringBuilder sb = new StringBuilder("http://localhost:8080/user/validate?email=");
    sb.append(email);
    sb.append("&password=");
    sb.append(password);
    sb.append("&time=");
    sb.append(now);
    data.put("email", email);
    data.put("url", sb.toString());
    data.put("now", TimeUtil.getFormatDate(now, TimeUtil.DEFAULT_FORMAT));
    Template template;
    String readyParsedTemplate = null;
    try {
        template = configuration.getTemplate("email.ftl");
        readyParsedTemplate = FreeMarkerTemplateUtils.processTemplateIntoString(template, data);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return readyParsedTemplate;
}
 
Example 5
Source File: DTOGenerator.java    From fast-family-master with Apache License 2.0 6 votes vote down vote up
private static void genDTO(Map<String, Object> paramMap,
                           String reousrcePath,
                           GeneratorConfig generatorConfig) {


    Version version = new Version("2.3.27");
    Configuration configuration = new Configuration(version);
    try {
        URL url = ControllerGenerator.class.getClassLoader().getResource(reousrcePath);
        configuration.setDirectoryForTemplateLoading(new File(url.getPath()));
        configuration.setObjectWrapper(new DefaultObjectWrapper(version));
        String filePath = generatorConfig.getSrcBasePath() + "dto//";
        String savePath = filePath + paramMap.get("className") + "DTO.java";
        File dirPath = new File(filePath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        try (FileWriter fileWriter = new FileWriter(new File(savePath))) {
            Template template = configuration.getTemplate("dto.ftl");
            template.process(paramMap, fileWriter);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 6
Source File: Template.java    From embeddedlinux-jvmdebugger-intellij with Apache License 2.0 5 votes vote down vote up
/**
 * Processes a freemarker template based on some parameters
 */
public void toFile() {
    Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(classContext, "/");
    try {
        freemarker.template.Template template = configuration.getTemplate(name);
        Writer file = new FileWriter(new File(outputFile));
        template.process(data, file);
        file.flush();
        file.close();

    } catch (Exception e) {

    }
}
 
Example 7
Source File: LogSearchDocumentationGenerator.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
private static void writeMarkdown(Configuration freemarkerConfiguration, String templateName,
                                  Map<String, Object> models, File outputFile) throws Exception {
  final StringWriter stringWriter = new StringWriter();
  final Template template = freemarkerConfiguration.getTemplate(templateName);
  template.process(models, stringWriter);
  FileUtils.writeStringToFile(outputFile, stringWriter.toString(), Charset.defaultCharset(), false);
}
 
Example 8
Source File: MailService.java    From abixen-platform with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Async
public void sendMail(String to, Map<String, String> parameters, String template, String subject) {
    log.debug("sendMail() - to: " + to);
    MimeMessage message = mailSender.createMimeMessage();
    try {
        String stringDir = MailService.class.getResource("/templates/freemarker").getPath();
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        cfg.setDefaultEncoding("UTF-8");

        File dir = new File(stringDir);
        cfg.setDirectoryForTemplateLoading(dir);
        cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_22));

        StringBuffer content = new StringBuffer();
        Template temp = cfg.getTemplate(template + ".ftl");
        content.append(FreeMarkerTemplateUtils.processTemplateIntoString(temp, parameters));

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content.toString(), "text/html;charset=\"UTF-8\"");

        MimeMultipart multipart = new MimeMultipart("related");
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);
        message.setFrom(new InternetAddress(platformMailConfigurationProperties.getUser().getUsername(), platformMailConfigurationProperties.getUser().getName()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        mailSender.send(message);

        log.info("Message has been sent to: " + to);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 9
Source File: WelcomePage.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
/**
 * 获取模板 & 合并模板和数据模型.
 *
 * @param cfg
 * @param root
 * @throws IOException
 * @throws TemplateException
 */
private void showUp(Configuration cfg, Map<String, Object> root, String ftlPath, String outPath)
        throws IOException, TemplateException {
    Template temp = cfg.getTemplate(ftlPath);
    Writer out = new OutputStreamWriter(System.out);
    temp.process(root, out);

    try (FileWriter fileWriter = new FileWriter(new File(outPath))) {
        temp.process(root, fileWriter);
    }
}
 
Example 10
Source File: FreeMarkerHelper.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
/**
 * @param name name of template to retrieve
 * @return template with specified name
 */
public Template getTemplate(Configuration conf, String name) {
    Template result = null;
    try {
        result = conf.getTemplate(name, "UTF-8");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return result;
}
 
Example 11
Source File: FreemarkerUtil.java    From SSMGenerator with MIT License 5 votes vote down vote up
public static void execute(String ftlNameWithPath, Map<String, Object> data, Writer out) throws IOException, TemplateException {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
    int i = ftlNameWithPath.lastIndexOf("/") == -1 ? ftlNameWithPath.lastIndexOf("\\") : ftlNameWithPath.lastIndexOf("/");
    cfg.setDirectoryForTemplateLoading(new File(ftlNameWithPath.substring(0, i + 1)));
    cfg.setDefaultEncoding("UTF-8");
    Template t1 = cfg.getTemplate(ftlNameWithPath.substring(i + 1));
    t1.process(data, out);
    out.flush();
}
 
Example 12
Source File: MapperGenerator.java    From fast-family-master with Apache License 2.0 5 votes vote down vote up
private static void genMapper(String className,
                              String classComment,
                              String resourcePath,
                              GeneratorConfig generatorConfig) {
    Map<String, Object> paramMap = new HashMap<>();
    paramMap.put("className", className);
    paramMap.put("classComment", classComment);
    paramMap.put("sysTime", new Date());
    paramMap.put("packageName", generatorConfig.getPackageName());
    ;

    Version version = new Version("2.3.27");
    Configuration configuration = new Configuration(version);
    try {
        URL url = MapperGenerator.class.getClassLoader().getResource(resourcePath);
        configuration.setDirectoryForTemplateLoading(new File(url.getPath()));
        configuration.setObjectWrapper(new DefaultObjectWrapper(version));
        String filePath = generatorConfig.getSrcBasePath() + "mapper//";
        String savePath = filePath + className + "Mapper.java";
        File dirPath = new File(filePath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        try (FileWriter out = new FileWriter(new File(savePath))) {
            Template template = configuration.getTemplate("mapper.ftl");
            template.process(paramMap, out);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 13
Source File: KurentoJsBase.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
  try {
    final String outputFolder =
        new ClassPathResource("static").getFile().getAbsolutePath() + File.separator;

    Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
    cfg.setClassForTemplateLoading(KurentoJsBase.class, "/templates/");
    Template template = cfg.getTemplate("kurento-client.html.ftl");

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

    for (String lib : kurentoLibs) {
      Writer writer = new FileWriter(new File(outputFolder + lib + ".html"));
      data.put("kurentoLib", lib);

      if (lib.contains("utils")) {
        data.put("kurentoObject", "kurentoUtils");
      } else {
        data.put("kurentoObject", "kurentoClient");
      }

      template.process(data, writer);
      writer.flush();
      writer.close();
    }
  } catch (Exception e) {
    Assert.fail("Exception creating templates: " + e.getMessage());
  }

}
 
Example 14
Source File: CreateFileUtil.java    From Spring-generator with MIT License 5 votes vote down vote up
/**
 * 执行创建文件
 * 
 * @param content
 *          模板所需要的上下文
 * @param templeteName
 *          模板的名字 示例:Entity.ftl
 * @param projectPath
 *          生成的项目路径 示例:D://create
 * @param packageName
 *          包名 示例:com.szmirren
 * @param fileName
 *          文件名 示例:Entity.java
 * @param codeFormat
 *          输出的字符编码格式 示例:UTF-8
 * @throws Exception
 */
public static void createFile(GeneratorContent content, String templeteName, String projectPath, String packageName, String fileName,
		String codeFormat, boolean isOverride) throws Exception {
	String outputPath = projectPath + "/" + packageName.replace(".", "/") + "/";
	if (!isOverride) {
		if (Files.exists(Paths.get(outputPath + fileName))) {
			LOG.debug("设置了文件存在不覆盖,文件已经存在,忽略本文件的创建");
			return;
		}
	}
	Configuration config = new Configuration(Configuration.VERSION_2_3_23);
	// 打包成jar包使用的路径
	String tempPath = Paths.get(Constant.TEMPLATE_DIR_NAME).toFile().getName();
	// 在项目运行的模板路径
	// String tempPath =
	// Thread.currentThread().getContextClassLoader().getResource(Constant.TEMPLATE_DIR_NAME).getFile();
	config.setDirectoryForTemplateLoading(new File(tempPath));
	config.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));
	config.setDefaultEncoding("utf-8");
	Template template = config.getTemplate(templeteName);
	Map<String, Object> item = new HashMap<>();
	item.put("content", content);
	if (!Files.exists(Paths.get(outputPath))) {
		Files.createDirectories(Paths.get(outputPath));
	}
	try (Writer writer = new OutputStreamWriter(new FileOutputStream(outputPath + fileName), codeFormat)) {
		template.process(item, writer);
	}
}
 
Example 15
Source File: FreemarkerTransformer.java    From tutorials with MIT License 5 votes vote down vote up
public String html() throws IOException, TemplateException {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_29);
    cfg.setDirectoryForTemplateLoading(new File(templateDirectory));
    cfg.setDefaultEncoding(StandardCharsets.UTF_8.toString());
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setLogTemplateExceptions(false);
    cfg.setWrapUncheckedExceptions(true);
    cfg.setFallbackOnNullLoopVariable(false);
    Template temp = cfg.getTemplate(templateFile);
    try (Writer output = new StringWriter()) {
        temp.process(staxTransformer.getMap(), output);
        return output.toString();
    }
}
 
Example 16
Source File: TemplateService.java    From frostmourne with MIT License 5 votes vote down vote up
private String process(Configuration config, String key, Map<String, Object> env) {
    try {
        Template template = config.getTemplate(key, "utf-8");
        StringWriter writer = new StringWriter();
        template.process(env, writer);
        return writer.toString();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 17
Source File: ConfigurationExporterTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
static String renderDocumentation(ConfigurationRegistry configurationRegistry) throws IOException, TemplateException {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_27);
    cfg.setClassLoaderForTemplateLoading(ConfigurationExporterTest.class.getClassLoader(), "/");
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setLogTemplateExceptions(false);

    Template temp = cfg.getTemplate("configuration.asciidoc.ftl");
    StringWriter tempRenderedFile = new StringWriter();
    tempRenderedFile.write("////\n" +
        "This file is auto generated\n" +
        "\n" +
        "Please only make changes in configuration.asciidoc.ftl\n" +
        "////\n");
    final List<ConfigurationOption<?>> nonInternalOptions = configurationRegistry.getConfigurationOptionsByCategory()
        .values()
        .stream()
        .flatMap(List::stream)
        .filter(option -> !option.getTags().contains("internal"))
        .collect(Collectors.toList());
    final Map<String, List<ConfigurationOption<?>>> optionsByCategory = nonInternalOptions.stream()
        .collect(Collectors.groupingBy(ConfigurationOption::getConfigurationCategory, TreeMap::new, Collectors.toList()));
    temp.process(Map.of(
        "config", optionsByCategory,
        "keys", nonInternalOptions.stream().map(ConfigurationOption::getKey).sorted().collect(Collectors.toList())
    ), tempRenderedFile);

    // re-process the rendered template to resolve the ${allInstrumentationGroupNames} placeholder
    StringWriter out = new StringWriter();
    new Template("", tempRenderedFile.toString(), cfg)
        .process(Map.of("allInstrumentationGroupNames", getAllInstrumentationGroupNames()), out);

    return out.toString();
}
 
Example 18
Source File: FreeMarkerConfigurerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void freeMarkerConfigurationFactoryBeanWithNonFileResourceLoaderPath() throws Exception {
	FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean();
	fcfb.setTemplateLoaderPath("file:/mydir");
	Properties settings = new Properties();
	settings.setProperty("localized_lookup", "false");
	fcfb.setFreemarkerSettings(settings);
	fcfb.setResourceLoader(new ResourceLoader() {
		@Override
		public Resource getResource(String location) {
			if (!("file:/mydir".equals(location) || "file:/mydir/test".equals(location))) {
				throw new IllegalArgumentException(location);
			}
			return new ByteArrayResource("test".getBytes(), "test");
		}
		@Override
		public ClassLoader getClassLoader() {
			return getClass().getClassLoader();
		}
	});
	fcfb.afterPropertiesSet();
	assertThat(fcfb.getObject(), instanceOf(Configuration.class));
	Configuration fc = fcfb.getObject();
	Template ft = fc.getTemplate("test");
	assertEquals("test", FreeMarkerTemplateUtils.processTemplateIntoString(ft, new HashMap()));
}
 
Example 19
Source File: FreemarkerUsage.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void allSignatures(String inputFile) throws IOException, TemplateException {
    Configuration cfg = new Configuration();
    Template template = cfg.getTemplate(inputFile);
    Map<String, Object> data = new HashMap<String, Object>();

    template.process(data, new OutputStreamWriter(System.out)); //TP
    template.process(data, new OutputStreamWriter(System.out), null); //TP
    template.process(data, new OutputStreamWriter(System.out), null, null); //TP
}
 
Example 20
Source File: FreemarkerUtils.java    From t-io with Apache License 2.0 2 votes vote down vote up
/**
 * @param writer
 * @param template
 * @param configuration
 * @param model
 * @throws TemplateNotFoundException
 * @throws MalformedTemplateNameException
 * @throws ParseException
 * @throws IOException
 * @throws TemplateException
 */
public static void generateStringByPath(Writer writer, String template, Configuration configuration, Object model)
        throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException {
	Template tpl = configuration.getTemplate(template, null, null, null, true, true);
	tpl.process(model, writer);
}