@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); } }
@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\"}")); }
/** * 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(); }
/** * 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 ""; } }
@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); } } }
/** * 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; }
/** * @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); } }
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(); } }
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; } }
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(); }
/** * 执行模板渲染 * @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) { } } }
@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; }
@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; }
@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; }
/** * 解析模板 * * @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); } }
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(); }
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; } }
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; }
/** * 获取评论 * @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; }
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(); } }
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); }
/** * 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; }
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; } }
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()); }
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(); } }
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; }
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(); }
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); } }
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()); } }
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 }
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); } }
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); }
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); } }
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"); } }
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(); }
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); } }
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; }