Java Code Examples for freemarker.template.Template.process()

The following are Jave code examples for showing how to use process() of the freemarker.template.Template class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: dremio-oss   File: IndexServlet.java   Source Code and License Vote up 8 votes
@Override
public void service(ServletRequest servletRequest, ServletResponse response) throws ServletException, IOException {
  ClientSettings settings = new ClientSettings(
      options.getOption(SupportService.SUPPORT_EMAIL_ADDR),
      options.getOption(SupportService.SUPPORT_EMAIL_SUBJECT),
      options.getOption(SupportService.OUTSIDE_COMMUNICATION_DISABLED),
      options.getOption(AccelerationOptions.ENABLE_SUBHOUR_POLICIES),
      options.getOption(UIOptions.ALLOW_LOWER_PROVISIONING_SETTINGS),
      options.getOption(UIOptions.TABLEAU_TDS_MIMETYPE));

  String environment = config.allowTestApis ? "DEVELOPMENT" : "PRODUCTION";
  final ServerData indexConfig = new ServerData(environment, serverHealthMonitor, config.getConfig(), settings, getVersionInfo(), supportService.getClusterId().getIdentity());

  Template tmp = templateCfg.getTemplate("/index.html");

  response.setContentType("text/html; charset=utf-8");
  OutputStreamWriter outputWriter = new OutputStreamWriter(response.getOutputStream());
  try {
    tmp.process(ImmutableMap.of("dremio", indexConfig), outputWriter);
    outputWriter.flush();
    outputWriter.close();
  } catch (TemplateException e) {
    throw new IOException("Error rendering index.html template", e);
  }
}
 
Example 2
Project: Android_Code_Arbiter   File: FreemarkerUsage.java   Source Code and License Vote up 6 votes
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 3
Project: solo-spring   File: AbstractPlugin.java   Source Code and License Vote up 6 votes
/**
 * Gets view content of a plugin. The content is processed with the
 * specified data model by template engine.
 *
 * @param dataModel
 *            the specified data model
 * @return plugin view content
 */
private String getViewContent(final Map<String, Object> dataModel) {
	if (null == configuration) {
		initTemplateEngineCfg();
	}

	try {
		final Template template = configuration.getTemplate("plugin.ftl");
		final StringWriter sw = new StringWriter();

		template.process(dataModel, sw);

		return sw.toString();
	} catch (final Exception e) {
		// This plugin has no view

		return "";
	}
}
 
Example 4
Project: solo-spring   File: IndexProcessor.java   Source Code and License Vote up 6 votes
@Override
public void render(final HttpServletRequest request, final HttpServletResponse response) {
	response.setContentType("text/html");
	response.setCharacterEncoding("UTF-8");

	try {
		final Template template = ConsoleRenderer.TEMPLATE_CFG.getTemplate("kill-browser.ftl");

		final PrintWriter writer = response.getWriter();

		final StringWriter stringWriter = new StringWriter();

		template.setOutputEncoding("UTF-8");
		template.process(getDataModel(), stringWriter);

		final String pageContent = stringWriter.toString();

		writer.write(pageContent);
		writer.flush();
		writer.close();
	} catch (final Exception e) {
		try {
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		} catch (final IOException ex) {
			logger.error("Can not sned error 500!", ex);
		}
	}
}
 
Example 5
Project: pyblog   File: GeneratorHtml.java   Source Code and License Vote up 6 votes
public void generatorHtml(String dir, String htmlName, String templateFile, String attrName, Object attrValue) {
  try {
    if (StringUtils.isEmpty(htmlName)) htmlName = "index.html";
    fileUtil.mkdirs(dir);
    File staticFile = fileUtil.createFile(dir + "/" + htmlName);

    FileOutputStream outStream = new FileOutputStream(staticFile);
    OutputStreamWriter writer = new OutputStreamWriter(outStream, "UTF-8");
    BufferedWriter sw = new BufferedWriter(writer);

    Map rootMap = new HashMap();
    if (!StringUtils.isEmpty(attrName)) rootMap.put(attrName, attrValue);

    Template template = configuration.getTemplate(siteConfig.getTheme() + "/" + templateFile);
    template.process(rootMap, sw);
    sw.flush();
    sw.close();
    outStream.close();
  } catch (IOException | TemplateException e) {
    e.printStackTrace();
  }
}
 
Example 6
Project: mybatis-generator-plugin   File: TemplateCommentGenerator.java   Source Code and License Vote up 6 votes
/**
 * 获取评论
 * @param map 模板参数
 * @param node  节点ID
 * @return
 */
private String[] getComments(Map<String, Object> map, EnumNode node) {
    // 1. 模板引擎解析
    try {
        StringWriter stringWriter = new StringWriter();
        Template template = templates.get(node);
        if (template != null){
            template.process(map, stringWriter);

            String comment = stringWriter.toString();
            stringWriter.close();

            // 需要先清理字符串
            return comment.replaceFirst("^[\\s\\t\\r\\n]*", "").replaceFirst("[\\s\\t\\r\\n]*$", "").split("\n");
        }

    } catch (Exception e) {
        logger.error("freemarker 解析失败!", e);
    }

    return null;
}
 
Example 7
Project: gen_code   File: FreeMarkerUtil.java   Source Code and License Vote up 5 votes
/**
 * 获取渲染之后的字符串
 * @param content 渲染的字符串
 * @param data 模板中渲染的参数
 * @return 返回结果
 */
public static String renderStr(String content,Map<String,Object> data){
    String result = null;
    try {
        Template t = new Template(null,new StringReader(content),null);
        StringWriter writer = new StringWriter();
        t.process(data,writer);
        result = writer.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
 
Example 8
Project: otus_java_2017_04   File: TemplateProcessor.java   Source Code and License Vote up 5 votes
String getPage(String filename, Map<String, Object> data) throws IOException {
    try (Writer stream = new StringWriter();) {
        Template template = configuration.getTemplate(filename);
        template.process(data, stream);
        return stream.toString();
    } catch (TemplateException e) {
        throw new IOException(e);
    }
}
 
Example 9
Project: incubator-netbeans   File: SpeedTest.java   Source Code and License Vote up 5 votes
public void testSpeedOfFreemarker() throws Exception {
    Configuration cfg = new Configuration();
    cfg.setDirectoryForTemplateLoading(getWorkDir());
    cfg.setObjectWrapper(new BeansWrapper());
    Template templ = cfg.getTemplate("template.txt");
    
    for(int i = 0; i < whereTo.length; i++) {
        Writer out = new BufferedWriter(new FileWriter(whereTo[i]));
        templ.process(parameters, out);
        out.close();
    }
}
 
Example 10
Project: otus_java_2017_04   File: TemplateProcessor.java   Source Code and License Vote up 5 votes
String getPage(String filename, Map<String, Object> data) throws IOException {
    try (Writer stream = new StringWriter();) {
        Template template = configuration.getTemplate(filename);
        template.process(data, stream);
        return stream.toString();
    } catch (TemplateException e) {
        throw new IOException(e);
    }
}
 
Example 11
Project: gradle-site-plugin   File: FreemarkerSiteGenerator.java   Source Code and License Vote up 5 votes
private void processIndexPageTemplate(ProjectDescriptor projectDescriptor, CustomData customData) throws IOException, URISyntaxException, TemplateException {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
    cfg.setClassLoaderForTemplateLoading(getClass().getClassLoader(), "template");
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setLogTemplateExceptions(false);
    Map<String, Object> root = new HashMap<String, Object>();
    root.put("project", projectDescriptor);
    root.put("customData", customData);
    Template template = cfg.getTemplate("index.ftl");
    template.process(root, new FileWriter(new File(outputDir, "index.html")));
}
 
Example 12
Project: selenium-testng-template   File: HtmlReporter.java   Source Code and License Vote up 5 votes
private String buildReport(ITestContext test) {
	try {
		InputStream is = HtmlReporter.class.getResourceAsStream(REPORT_TEMPLATE);
		Configuration cfg = new Configuration(Configuration.getVersion());
		Template template = new Template("Report", new InputStreamReader(is), cfg);
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("context", test);
		StringWriter writer = new StringWriter();
		template.process(parameters, writer);
		return writer.toString();
	} catch (Exception e) {
		log.error("Build Report error", e);
		return "Exception: " + e.getMessage();
	}
}
 
Example 13
Project: satisfy   File: TemplateUtils.java   Source Code and License Vote up 5 votes
public static File processTemplate(File template) throws IOException, TemplateException {
    Configuration config = new Configuration();
    config.setDirectoryForTemplateLoading(template.getParentFile());
    config.setObjectWrapper(new DefaultObjectWrapper());
    config.setDefaultEncoding("UTF-8");
    Template temp = config.getTemplate(template.getName());
    String child = template.getName() + RandomStringUtils.randomAlphanumeric(8);
    File fileOutput = new File(template.getParentFile(), child);
    Writer fileWriter = new FileWriter(fileOutput);
    Map<Object, Object> currentSession = Thucydides.getCurrentSession();
    temp.process(currentSession, fileWriter);
    return fileOutput;
}
 
Example 14
Project: otus_java_2017_04   File: TemplateProcessor.java   Source Code and License Vote up 5 votes
String getPage(String filename, Map<String, Object> data) throws IOException {
    try (Writer stream = new StringWriter();) {
        Template template = configuration.getTemplate(filename);
        template.process(data, stream);
        return stream.toString();
    } catch (TemplateException e) {
        throw new IOException(e);
    }
}
 
Example 15
Project: otus_java_2017_04   File: TemplateProcessor.java   Source Code and License Vote up 5 votes
String getPage(String filename, Map<String, Object> data) throws IOException {
    try (Writer stream = new StringWriter();) {
        Template template = configuration.getTemplate(filename);
        template.process(data, stream);
        return stream.toString();
    } catch (TemplateException e) {
        throw new IOException(e);
    }
}
 
Example 16
Project: webpage-update-subscribe   File: FreemarkerEmailTemplateService.java   Source Code and License Vote up 5 votes
public String getText(String templateId, Map<Object, Object> parameters) {
	String templateFile = templateId + SUFFIX;
	try {
		Template template = TEMPLATE_CACHE.get(templateFile);
		if(template == null){
			template = configuration.getTemplate(templateFile);
			TEMPLATE_CACHE.put(templateFile, template);
		}
		StringWriter stringWriter = new StringWriter();
		template.process(parameters, stringWriter);
		return stringWriter.toString();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 17
Project: tkcg   File: FreemarkerHelper.java   Source Code and License Vote up 5 votes
/**
 * Process to file.
 *
 * @param model model
 * @param templateName templateName
 * @param targetFile targetFile
 * @param encoding encoding
 * @throws IOException io exception
 */
public void processToFile(Map model, String templateName, File targetFile, String encoding) throws IOException {
    Template template = configuration.getTemplate(templateName);
    Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), encoding));
    try {
        template.process(model, out);
    } catch (TemplateException e) {
        throw new GeneratorException("处理文件模板出错:" + e.getMessage());
    }
    out.close();
}
 
Example 18
Project: otus_java_2017_06   File: TemplateProcessor.java   Source Code and License Vote up 5 votes
String getPage(String filename, Map<String, Object> data) throws IOException {
    try (Writer stream = new StringWriter();) {
        Template template = configuration.getTemplate(filename);
        template.process(data, stream);
        return stream.toString();
    } catch (TemplateException e) {
        throw new IOException(e);
    }
}
 
Example 19
Project: hippo   File: ImportableFileWriter.java   Source Code and License Vote up 3 votes
private void writeImportableFile(final HippoImportableItem importableItem,
                                        final String fileName,
                                        final Path targetDir) {

    try {

        Path targetFilePath = Paths.get(targetDir.toString(), fileName);

        final String itemTypeName = importableItem.getClass().getSimpleName().toLowerCase();

        final Template template = getFreemarkerConfiguration()
            .getTemplate(itemTypeName + ".json.ftl");

        final Writer writer = new StringWriter();

        template.process(new HashMap<String, Object>(){{
            put(itemTypeName, importableItem);
        }}, writer);

        final String importableFileContent = writer.toString();

        logger.debug("Writing file {}", fileName);

        Files.write(targetFilePath, importableFileContent.getBytes());

    } catch (final Exception e) {
        // If we fail with one file, make a note of the document that failed and carry on
        migrationReport.logError(e, "Failed to write out item:", "Item will not be imported", importableItem.toString());

        if (importableItem instanceof DataSet) {
            migrationReport.report(((DataSet) importableItem).getPCode(), DATASET_IMPORT_FILE_FAILURE);
        }
    }
}
 
Example 20
Project: lams   File: FreeMarkerTemplateUtils.java   Source Code and License Vote up 3 votes
/**
 * Process the specified FreeMarker template with the given model and write
 * the result to the given Writer.
 * <p>When using this method to prepare a text for a mail to be sent with Spring's
 * mail support, consider wrapping IO/TemplateException in MailPreparationException.
 * @param model the model object, typically a Map that contains model names
 * as keys and model objects as values
 * @return the result as String
 * @throws IOException if the template wasn't found or couldn't be read
 * @throws freemarker.template.TemplateException if rendering failed
 * @see org.springframework.mail.MailPreparationException
 */
public static String processTemplateIntoString(Template template, Object model)
		throws IOException, TemplateException {
	StringWriter result = new StringWriter();
	template.process(model, result);
	return result.toString();
}