Java Code Examples for freemarker.template.Template

The following are top voted examples for showing how to use freemarker.template.Template. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: slardar   File: TemplateParser.java   Source Code and License 8 votes vote down vote up
public static void main(String[] args) {
    Map<String,Object> tmp = new HashMap<>();
    tmp.put("user","邢天宇");
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
    StringTemplateLoader loader = new StringTemplateLoader();
    loader.putTemplate(NAME,"hello ${user}");
    cfg.setTemplateLoader(loader);
    cfg.setDefaultEncoding("UTF-8");
    try {
        Template template = cfg.getTemplate(NAME);
        StringWriter writer = new StringWriter();
        template.process(tmp,writer);
        System.out.println(writer.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
Example 2
Project: dremio-oss   File: IndexServlet.java   Source Code and License 8 votes vote down vote up
@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 3
Project: kubernetes-elastic-agents   File: StatusReportExecutorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldBuildStatusReportView() throws Exception {
    NodeOperationsImpl nodes = mock(NodeOperationsImpl.class);
    PodOperationsImpl pods = mock(PodOperationsImpl.class);

    when(nodes.list()).thenReturn(new NodeList());
    when(kubernetesClient.nodes()).thenReturn(nodes);

    when(pods.inNamespace(Constants.KUBERNETES_NAMESPACE_KEY)).thenReturn(pods);
    when(pods.withLabel(Constants.CREATED_BY_LABEL_KEY, Constants.PLUGIN_ID)).thenReturn(pods);
    when(pods.list()).thenReturn(new PodList());
    when(kubernetesClient.pods()).thenReturn(pods);

    final PluginStatusReportViewBuilder builder = mock(PluginStatusReportViewBuilder.class);
    final Template template = mock(Template.class);

    when(builder.getTemplate("status-report.template.ftlh")).thenReturn(template);
    when(builder.build(eq(template), any(KubernetesCluster.class))).thenReturn("status-report");

    final GoPluginApiResponse response = new StatusReportExecutor(pluginRequest, kubernetesClientFactory, builder).execute();

    assertThat(response.responseCode(), is(200));
    assertThat(response.responseBody(), is("{\"view\":\"status-report\"}"));
}
 
Example 4
Project: Android_Code_Arbiter   File: FreemarkerUsage.java   Source Code and License 6 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 5
Project: solo-spring   File: AbstractFreeMarkerRenderer.java   Source Code and License 6 votes vote down vote up
/**
	 * Processes the specified FreeMarker template with the specified request,
	 * data model.
	 *
	 * @param request
	 *            the specified request
	 * @param dataModel
	 *            the specified data model
	 * @param template
	 *            the specified FreeMarker template
	 * @return generated HTML
	 * @throws Exception
	 *             exception
	 */
	protected String genHTML(final HttpServletRequest request, final Map<String, Object> dataModel,
			final Template template) throws Exception {
		final StringWriter stringWriter = new StringWriter();

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

		final StringBuilder pageContentBuilder = new StringBuilder(stringWriter.toString());

		final long endimeMillis = System.currentTimeMillis();
		final String dateString = DateFormatUtils.format(endimeMillis, "yyyy/MM/dd HH:mm:ss");
//		final long startTimeMillis = (Long) request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS);
		final long startTimeMillis = System.currentTimeMillis();
		final String msg = String.format("<!-- Generated by B3log Latke(%1$d ms), %2$s -->",
				endimeMillis - startTimeMillis, dateString);

		pageContentBuilder.append(msg);

		return pageContentBuilder.toString();
	}
 
Example 6
Project: solo-spring   File: AbstractPlugin.java   Source Code and License 6 votes vote down vote up
/**
 * 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 7
Project: solo-spring   File: IndexProcessor.java   Source Code and License 6 votes vote down vote up
@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 8
Project: solo-spring   File: Templates.java   Source Code and License 6 votes vote down vote up
/**
 * Determines whether the specified expression exists in the specified
 * element (includes its children) of the specified template.
 * 
 * @param template
 *            the specified template
 * @param expression
 *            the specified expression
 * @param templateElement
 *            the specified element
 * @return {@code true} if it exists, returns {@code false} otherwise
 */
private static boolean hasExpression(final Template template, final String expression,
		final TemplateElement templateElement) {
	final String canonicalForm = templateElement.getCanonicalForm();

	if (canonicalForm.startsWith(expression)) {
		logger.trace("Template has expression[nodeName={}, expression={}]",
				new Object[] { templateElement.getNodeName(), expression });

		return true;
	}

	@SuppressWarnings("unchecked")
	final Enumeration<TemplateElement> children = templateElement.children();

	while (children.hasMoreElements()) {
		final TemplateElement nextElement = children.nextElement();

		if (hasExpression(template, expression, nextElement)) {
			return true;
		}
	}

	return false;
}
 
Example 9
Project: restclient   File: FkUtils.java   Source Code and License 6 votes vote down vote up
/**
 * @param templateString
 *            模板字符串
 * @param args
 *            参数
 * @return
 */
public static String process(String templateString, Map<String, Object> args) {
    try {
        if (templateString == null) {
            return null;
        }
        String key = "template_" + templateString.hashCode();
        if (stringTemplateLoader.findTemplateSource(key) == null) {
            stringTemplateLoader.putTemplate(key, templateString);
        }
        Template mytpl = configuration.getTemplate(key, chareSet);
        return process(mytpl, args);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 10
Project: pyblog   File: GeneratorHtml.java   Source Code and License 6 votes vote down vote up
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 11
Project: support-rulesengine   File: RuleCreator.java   Source Code and License 6 votes vote down vote up
public String createDroolRule(Rule rule) throws TemplateException, IOException {
  try {
    Template temp = cfg.getTemplate(templateName);
    Writer out = new StringWriter();
    temp.process(createMap(rule), out);
    return out.toString();
  } catch (IOException iE) {
    logger.error("Problem getting rule template file." + iE.getMessage());
    throw iE;
  } catch (TemplateException tE) {
    logger.error("Problem writing Drool rule." + tE.getMessage());
    throw tE;
  } catch (Exception e) {
    logger.error("Problem creating rule: " + e.getMessage());
    throw e;
  }
}
 
Example 12
Project: cluecumber-report-plugin   File: DetailPageRenderer.java   Source Code and License 6 votes vote down vote up
public String getRenderedContent(final DetailPageCollection detailPageCollection, final Template template)
        throws CluecumberPluginException {

    ReportDetails reportDetails = new ReportDetails();
    addChartJsonToReportDetails(detailPageCollection.getElement(), reportDetails);
    addCurrentDateToReportDetails(reportDetails);
    detailPageCollection.setReportDetails(reportDetails);

    Writer stringWriter = new StringWriter();
    try {
        template.process(detailPageCollection, stringWriter);
    } catch (TemplateException | IOException e) {
        throw new CluecumberPluginException(e.getMessage());
    }
    return stringWriter.toString();
}
 
Example 13
Project: gen_code   File: FreeMarkerUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 执行模板渲染
 * @param temp 模板文件或者字符串
 * @param data 数据
 * @param writer 输出方式
 */
public static void process(String temp, Map<String,Object> data, Writer writer){
    try {
        config.setDirectoryForTemplateLoading(new File(System .getProperty("user.dir")+File.separator+CoreConfig.getTemplatePath()));
        Template template = config.getTemplate(temp,CoreConfig.getEncoding());
        template.process(data, writer);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // 关闭write
        try {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        } catch (Exception ex) {
        }
    }
}
 
Example 14
Project: nixmash-blog   File: FmServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public String createRssPostContent(Post post) {
    String html = null;

    Map<String, Object> model = new Hashtable<>();

    model.put("post", post);
    model.put("baseurl", applicationSettings.getBaseUrl());

    try {
        Template template = fm.getTemplate("posts/rss_post.ftl");
        html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
    } catch (IOException | TemplateException e) {
        logger.error("Problem merging post template : " + e.getMessage());
    }
    return html;
}
 
Example 15
Project: nixmash-blog   File: FmServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public String createPostHtml(Post post, String templateName) {
    String html = null;
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM dd, yyyy");
    String postCreated = post.getPostDate().format(formatter);

    Map<String, Object> model = new Hashtable<>();

    model.put("post", post);
    model.put("postCreated", postCreated);
    model.put("shareSiteName",
            StringUtils.deleteWhitespace(applicationSettings.getSiteName()));
    model.put("shareUrl",
            String.format("%s/post/%s", applicationSettings.getBaseUrl(), post.getPostName()));

    String displayType = templateName == null ? post.getDisplayType().name().toLowerCase() : templateName;
    String ftl = String.format("posts/%s.ftl", displayType);

    try {
        Template template = fm.getTemplate(ftl);
        html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
    } catch (IOException | TemplateException e) {
        logger.error("Problem merging post template : " + e.getMessage());
    }
    return html;
}
 
Example 16
Project: nixmash-blog   File: FmServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public String createPostAtoZs() {
    String html = null;

    String backToTop = mailUI.getMessage("posts.az.page.backtotop");
    String azFileName = environment.getProperty("posts.az.file.name");
    String azFilePath = applicationSettings.getPostAtoZFilePath();

    Map<String, Object> model = new Hashtable<>();
    model.put("alphaLinks", postService.getAlphaLInks());
    model.put("alphaPosts", postService.getAlphaPosts());
    model.put("backToTop", backToTop);

    try {
        Template template = fm.getTemplate("posts/az.ftl");
        html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
        InputStream in = IOUtils.toInputStream(html, "UTF-8");
        FileUtils.copyInputStreamToFile(in, new File(azFilePath + azFileName));
    } catch (IOException | TemplateException e) {
        logger.error("Problem creating A-to-Z template or HTML file: " + e.getMessage());
    }
    return html;
}
 
Example 17
Project: jkami   File: FKParse.java   Source Code and License 6 votes vote down vote up
/**
 * 解析模板
 *
 * @param tplContent
 *            模板内容
 * @param paras
 *            参数
 * @return String 模板解析后内容
 */
public static String parseTemplateContent(String tplContent, Map<String, Object> paras) {
    try {
        StringWriter swriter = new StringWriter();
        String key = "sql_" + tplContent.hashCode();
        if (stringTemplateLoader.findTemplateSource(key) == null) {
            stringTemplateLoader.putTemplate(key, tplContent);
        }
        Template mytpl = _sqlConfig.getTemplate(key, ENCODE);
        mytpl.process(paras, swriter);
        return getSqlText(swriter.toString());
    } catch (Exception e) {
        logger.error("模板key:" + tplContent, e);
        throw new RuntimeException("解析SQL模板异常", e);
    }
}
 
Example 18
Project: dingtalk-incoming-webhoot-plugin   File: DingtalkNotificationPlugin.java   Source Code and License 6 votes vote down vote up
private String generateMessage(String trigger, Map executionData, Map config) {

        HashMap<String, Object> model = new HashMap<String, Object>();
        model.put("trigger", trigger);
        model.put("executionData", executionData);
        model.put("config", config);

        StringWriter sw = new StringWriter();
        try {
            Template template = FREEMARKER_CFG.getTemplate(DINGTALK_MESSAGE_TEMPLATE);
            template.process(model, sw);

        } catch (IOException ioEx) {
            throw new DingtalkNotificationPluginException("Error loading Dingtalk notification message template: [" + ioEx.getMessage() + "].", ioEx);
        } catch (TemplateException templateEx) {
            throw new DingtalkNotificationPluginException("Error merging Dingtalk notification message template: [" + templateEx.getMessage() + "].", templateEx);
        }

        return sw.toString();
    }
 
Example 19
Project: Equella   File: AbstractFreemarkerFactory.java   Source Code and License 6 votes vote down vote up
public FreemarkerSectionResult createResult(String name, Reader reader, Object model, PreRenderable preRenderer)
{
	try
	{
		Template template = new Template(name, reader, configuration);
		FreemarkerSectionResult result = new FreemarkerSectionResult(this, template);
		result.setModel(model);
		result.setPreRenderer(preRenderer);
		return result;
	}
	catch( IOException e )
	{
		SectionUtils.throwRuntime(e);
		return null;
	}
}
 
Example 20
Project: jresume   File: ResumeGenerator.java   Source Code and License 6 votes vote down vote up
private String generateResumeHTML(String json, String theme) throws Exception {
    if (!isValidJSON(json)) {
        throw new InvalidJSONException();
    }

    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
    cfg.setDirectoryForTemplateLoading(new File("themes"));
    cfg.setDefaultEncoding("UTF-8");
    Template temp = cfg.getTemplate(theme + ".html");
    //System.out.println(json);
    Resume resume = gson.fromJson(json, Resume.class);
    resume.getRidOfArraysWithEmptyElements();
    resume.setConfig(config);
    StringWriter htmlStringWriter = new StringWriter();
    temp.process(resume, htmlStringWriter);
    String html = htmlStringWriter.toString();
    return html;
}
 
Example 21
Project: mybatis-generator-plugin   File: TemplateCommentGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * 获取评论
 * @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 22
Project: aws-sdk-java-v2   File: MarshallerGeneratorTasks.java   Source Code and License 6 votes vote down vote up
private GeneratorTask createMarshallerTask(String javaShapeName, Template template,
                                           String marshallerClassName, String marshallerDirectory)
        throws IOException {
    Map<String, Object> marshallerDataModel = ImmutableMapParameter.<String, Object>builder()
            .put("fileHeader", model.getFileHeader())
            .put("shapeName", javaShapeName)
            .put("shapes", shapes)
            .put("metadata", metadata)
            .put("transformPackage", model.getMetadata().getFullTransformPackageName())
            .put("requestTransformPackage", model.getMetadata().getFullRequestTransformPackageName())
            .put("customConfig", model.getCustomizationConfig())
            .put("className", marshallerClassName)
            .put("protocolEnum", getProtocolEnumName())
            .build();

    return new FreemarkerGeneratorTask(marshallerDirectory,
                                       marshallerClassName,
                                       template,
                                       marshallerDataModel);
}
 
Example 23
Project: java_pdf_demo   File: JavaToPdfHtmlFreeMarker.java   Source Code and License 6 votes vote down vote up
/**
 * freemarker渲染html
 */
public static String freeMarkerRender(Map<String, Object> data, String htmlTmp) {
	Writer out = new StringWriter();
	try {
		// 获取模板,并设置编码方式
		Template template = freemarkerCfg.getTemplate(htmlTmp);
		template.setEncoding("UTF-8");
		// 合并数据模型与模板
		template.process(data, out); // 将合并后的数据和模板写入到流中,这里使用的字符流
		out.flush();
		return out.toString();
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		try {
			out.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	return null;
}
 
Example 24
Project: GitHub   File: DaoGenerator.java   Source Code and License 5 votes vote down vote up
private void generate(Template template, File outDirFile, String javaPackage, String javaClassName, Schema schema,
                      Entity entity, Map<String, Object> additionalObjectsForTemplate) throws Exception {
    Map<String, Object> root = new HashMap<>();
    root.put("schema", schema);
    root.put("entity", entity);
    if (additionalObjectsForTemplate != null) {
        root.putAll(additionalObjectsForTemplate);
    }
    try {
        File file = toJavaFilename(outDirFile, javaPackage, javaClassName);
        //noinspection ResultOfMethodCallIgnored
        file.getParentFile().mkdirs();

        if (entity != null && entity.getHasKeepSections()) {
            checkKeepSections(file, root);
        }

        Writer writer = new FileWriter(file);
        try {
            template.process(root, writer);
            writer.flush();
            System.out.println("Written " + file.getCanonicalPath());
        } finally {
            writer.close();
        }
    } catch (Exception ex) {
        System.err.println("Data map for template: " + root);
        System.err.println("Error while generating " + javaPackage + "." + javaClassName + " ("
                + outDirFile.getCanonicalPath() + ")");
        throw ex;
    }
}
 
Example 25
Project: kubernetes-elastic-agents   File: StatusReportExecutor.java   Source Code and License 5 votes vote down vote up
public GoPluginApiResponse execute() throws Exception {
    LOG.info("[status-report] Generating status report");
    KubernetesClient client = factory.kubernetes(pluginRequest.getPluginSettings());
    final KubernetesCluster kubernetesCluster = new KubernetesCluster(client);
    final Template template = statusReportViewBuilder.getTemplate("status-report.template.ftlh");
    final String statusReportView = statusReportViewBuilder.build(template, kubernetesCluster);

    JsonObject responseJSON = new JsonObject();
    responseJSON.addProperty("view", statusReportView);

    return DefaultGoPluginApiResponse.success(responseJSON.toString());
}
 
Example 26
Project: incubator-netbeans   File: SpeedTest.java   Source Code and License 5 votes vote down vote up
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 27
Project: satisfy   File: WebserviceSteps.java   Source Code and License 5 votes vote down vote up
private File prepareFreemarkerTemplate(String filePath) throws IOException, TemplateException {
    File template = getFileFromResourcesByFilePath(filePath);
    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 28
Project: tdl-auth   File: Mailer.java   Source Code and License 5 votes vote down vote up
public String createBody() throws IOException, TemplateException {
    Template template = templateConfiguration.getTemplate("mail.txt");
    StringWriter stringWriter = new StringWriter();
    Map<String, String> contentParams = new HashMap<>();
    contentParams.put("PAGE_URL", pageUrl);
    template.process(contentParams, stringWriter);
    return stringWriter.toString();
}
 
Example 29
Project: framework   File: FreeMarkers.java   Source Code and License 5 votes vote down vote up
public static String renderTemplate(Template template, Object model) {
	try {
		StringWriter result = new StringWriter();
		template.process(model, result);
		return result.toString();
	} catch (Exception e) {
		throw Exceptions.unchecked(e);
	}
}
 
Example 30
Project: travny   File: Codegen.java   Source Code and License 5 votes vote down vote up
private String processTemplate(String templateName, Map values) throws Exception {
    Template template = cfg.getTemplate(templateName + ".ftl");
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        try (OutputStreamWriter writer = new OutputStreamWriter(out)) {
            template.process(values, writer);
        }
        out.flush();
        return out.toString(StandardCharsets.UTF_8.name());
    }
}
 
Example 31
Project: allure-java   File: FreemarkerAttachmentRenderer.java   Source Code and License 5 votes vote down vote up
public DefaultAttachmentContent render(final AttachmentData data) {
    try (Writer writer = new StringWriter()) {
        final Template template = configuration.getTemplate(templateName);
        template.process(Collections.singletonMap("data", data), writer);
        return new DefaultAttachmentContent(writer.toString(), "text/html", ".html");
    } catch (Exception e) {
        throw new AttachmentRenderException("Could't render http attachment file", e);
    }
}
 
Example 32
Project: magic-beanstalk   File: FileGenerator.java   Source Code and License 5 votes vote down vote up
private static void generateFileFromTemplate(Configuration cfg,
    String templateFile,
    String outputFilePath,
    Map<String, Object> parameters) throws IOException, TemplateException {
  Template temp = cfg.getTemplate(templateFile);
  File file = new File(outputFilePath);
  if (file.getParent() != null) {
    file.getParentFile().mkdirs();
  }
  FileWriter writer = new FileWriter(file);
  temp.process(parameters, writer);
}
 
Example 33
Project: webpage-update-subscribe   File: FreemarkerEmailTemplateService.java   Source Code and License 5 votes vote down vote up
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 34
Project: tscfg-docgen   File: FreemarkerDocGenerator.java   Source Code and License 5 votes vote down vote up
private Template loadTemplate() throws IOException {
  if (customTemplateFile != null) {
    freeMarkerConfig.setDirectoryForTemplateLoading(customTemplateFile.getParentFile());
    return freeMarkerConfig.getTemplate(customTemplateFile.getName());
  } else {
    freeMarkerConfig.setClassForTemplateLoading(this.getClass(), "/");
    return freeMarkerConfig.getTemplate("templates/" + standardTemplateName + ".ftl");
  }
}
 
Example 35
Project: alfresco-repository   File: FeedTaskProcessor.java   Source Code and License 5 votes vote down vote up
protected String processFreemarker(Map<String, Template> templateCache, String fmTemplate, Configuration cfg, Map<String, Object> model) throws IOException, TemplateException, Exception
{
    // Save on lots of modification date checking by caching templates locally
    Template myTemplate = templateCache.get(fmTemplate);
    if (myTemplate == null)
    {
        myTemplate = cfg.getTemplate(fmTemplate);
        templateCache.put(fmTemplate, myTemplate);
    }
    
    StringWriter textWriter = new StringWriter();
    myTemplate.process(model, textWriter);
    
    return textWriter.toString();
}
 
Example 36
Project: otus_java_2017_06   File: TemplateProcessor.java   Source Code and License 5 votes vote down vote up
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 37
Project: otus_java_2017_06   File: TemplateProcessor.java   Source Code and License 5 votes vote down vote up
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 38
Project: otus_java_2017_06   File: TemplateProcessor.java   Source Code and License 5 votes vote down vote up
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 39
Project: cluecumber-report-plugin   File: TemplateConfiguration.java   Source Code and License 5 votes vote down vote up
Template getTemplate(final String templateName) throws CluecumberPluginException {
    Template template = null;
    try {
        template = cfg.getTemplate(templateName);
    } catch (Exception e) {
        throw new CluecumberPluginException("Template '" + templateName + "' was not found or not parsable: " + e.getMessage());
    }
    return template;
}
 
Example 40
Project: otus_java_2017_06   File: TemplateProcessor.java   Source Code and License 5 votes vote down vote up
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);
    }
}