public void init(ServletConfig config) throws ServletException { super.init(config); try { String appPath = config.getServletContext().getRealPath(""); // 是否为开发mode debug = "true".equals(config.getInitParameter("development")); // 读取log4j.xml配置文件 DOMConfigurator.configure(appPath + "/WEB-INF/log4j.xml"); logger.info("Starting JForum. Debug mode is " + debug); // ConfigLoader.startSystemglobals(appPath); // 启动缓存引擎 ConfigLoader.startCacheEngine(); // Configure the template engine Configuration templateCfg = new Configuration(); templateCfg.setTemplateUpdateDelay(2); templateCfg.setSetting("number_format", "#"); templateCfg.setSharedVariable("startupTime", new Long(new Date().getTime())); // Create the default template loader String defaultPath = SystemGlobals.getApplicationPath() + "/templates"; FileTemplateLoader defaultLoader = new FileTemplateLoader(new File(defaultPath)); String extraTemplatePath = SystemGlobals.getValue(ConfigKeys.FREEMARKER_EXTRA_TEMPLATE_PATH); if (StringUtils.isNotBlank(extraTemplatePath)) { // An extra template path is configured, we need a MultiTemplateLoader FileTemplateLoader extraLoader = new FileTemplateLoader(new File(extraTemplatePath)); TemplateLoader[] loaders = new TemplateLoader[] {extraLoader, defaultLoader}; MultiTemplateLoader multiLoader = new MultiTemplateLoader(loaders); templateCfg.setTemplateLoader(multiLoader); } else { // An extra template path is not configured, we only need the default loader templateCfg.setTemplateLoader(defaultLoader); } // 载入模块 ModulesRepository.init(SystemGlobals.getValue(ConfigKeys.CONFIG_DIR)); this.loadConfigStuff(); if (!this.debug) { templateCfg.setTemplateUpdateDelay(3600); } JForumExecutionContext.setTemplateConfig(templateCfg); } catch (Exception e) { throw new ForumStartupException("Error while starting JForum", e); } }
private String substituteParams(final Event e) { final Configuration cfg = new Configuration(); final StringWriter writer = new StringWriter(); String processedTemplate = null; // StringTemplateLoader Freemarker used to read the ResponseTemplate of // Event object final StringTemplateLoader stringLoader = new StringTemplateLoader(); stringLoader.putTemplate("template", e.getResponseTemplate()); cfg.setTemplateLoader(stringLoader); Template tpl; // Substitutes the ResponseTemplate variables with the values defined in // the map(params) try { tpl = cfg.getTemplate("template"); tpl.process(e.getParams(), writer); processedTemplate = writer.toString(); } catch (final IOException ex) { throw new EGOVRuntimeException( "Exception Occurred in EventProcessor while substituting Parameters" + ex); } catch (final TemplateException ex) { throw new EGOVRuntimeException( "Exception Occurred in EventProcessor while processing Template" + ex); } return processedTemplate; }
/** Initialise FreeMarker Configuration */ protected void initConfig() { // construct template config Configuration config = new Configuration(); ObjectWrapper objectWrapper = new NonBlockingObjectWrapper(); config.setObjectWrapper(objectWrapper); config.setCacheStorage(new StrongCacheStorage()); config.setTemplateUpdateDelay(isDebugMode() == false ? updateDelay : 0); config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); config.setLocalizedLookup(false); config.setOutputEncoding("UTF-8"); if (defaultEncoding != null) { config.setDefaultEncoding(defaultEncoding); } config.setIncompatibleImprovements(new Version(2, 3, 20)); if (getTemplateLoader() != null) { config.setTemplateLoader(getTemplateLoader()); } config.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER); templateConfig = config; // construct string config stringConfig = new Configuration(); stringConfig.setObjectWrapper(objectWrapper); stringConfig.setCacheStorage(new MruCacheStorage(2, 0)); stringConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); stringConfig.setOutputEncoding("UTF-8"); if (defaultEncoding != null) { stringConfig.setDefaultEncoding(defaultEncoding); } stringConfig.setIncompatibleImprovements(new Version(2, 3, 20)); stringConfig.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER); }
public FreeMarkerTemplateEngineImpl() { super(DEFAULT_TEMPLATE_EXTENSION, DEFAULT_MAX_CACHE_SIZE); loader = new FreeMarkerTemplateLoader(); config = new Configuration(Configuration.VERSION_2_3_22); config.setObjectWrapper(new VertxWebObjectWrapper(config.getIncompatibleImprovements())); config.setTemplateLoader(loader); }
@Override public void testSetUp() { super.testSetUp(); // generated load users and group resources cfg = new Configuration(); cfg.setTemplateLoader( new ClassTemplateLoader(getClass().getClassLoader().getClass(), DIR_TMPL)); }
public TemplateLoaderImpl(BundleContext ctx) { menuBuilder = new MenuBuilder(ctx); config = new Configuration(); // config.setTemplateLoader(new ClassTemplateLoader(Activator.class, "/templates/")); config.setTemplateLoader(new BundleTemplateLoader(ctx, "/templates/")); config.setObjectWrapper(new DefaultObjectWrapper()); config.setEncoding(Locale.getDefault(), "UTF-8"); config.setURLEscapingCharset("UTF-8"); }
/** * インスタンスを生成します。 * * @param templateEncoding テンプレートファイルのエンコーディング * @param templatePrimaryDir テンプレートファイルを格納したプライマリディレクトリ、プライマリディレクトリを使用しない場合{@code null} */ public Generator(String templateEncoding) { if (templateEncoding == null) { throw new NullPointerException("templateFileEncoding"); } this.configuration = new Configuration(); configuration.setObjectWrapper(ObjectWrapper.DEFAULT_WRAPPER); configuration.setEncoding(Locale.getDefault(), templateEncoding); configuration.setTemplateLoader( new ClassTemplateLoader(this.getClass(), "/" + DEFAULT_TEMPLATE_DIR_NAME)); }
public static void main(String[] args) throws MalformedTemplateNameException, ParseException, IOException, TemplateException { String templPath = args[0]; String josnPath = args[1]; File templFile = new File(templPath); JsonValue jdm = getJsonInFile(josnPath); Configuration cfg = new Configuration(Configuration.VERSION_2_3_23); cfg.setTemplateLoader(new FileTemplateLoader(templFile.getParentFile())); Template tpl = cfg.getTemplate(templFile.getName()); tpl.process(jdm, new OutputStreamWriter(System.out)); }
public ProcessadorFreemarkerSimples() { super(); cfg = new Configuration(); String s = cfg.getVersionNumber(); // Specify the data source where the template files come from. cfg.setTemplateLoader(this); // Specify how templates will see the data-model. cfg.setObjectWrapper(new DefaultObjectWrapper()); cfg.setWhitespaceStripping(true); cfg.setTagSyntax(Configuration.SQUARE_BRACKET_TAG_SYNTAX); cfg.setLocalizedLookup(false); }
/** * Create an instance that loads templates from an OSGi <tt>bundle</tt>. * * @param bundle the OSGi bundle used to load all templates from */ public FreemarkerTemplateFactory(final Bundle bundle) { this.config = new Configuration(); config.setObjectWrapper(new DefaultObjectWrapper()); config.setTemplateUpdateDelay(Integer.MAX_VALUE); config.setLocalizedLookup(false); config.setTemplateLoader( new URLTemplateLoader() { @Override protected URL getURL(String url) { return bundle.getEntry(url); } }); }
FremarkParseUtils() { if (config == null) { config = new Configuration(); config.setTemplateLoader(new StringTemplateLoader()); try { config.setSetting("datetime_format", "yyyy-MM-dd HH:mm:ss"); config.setLocale(Locale.CHINA); } catch (Exception ex) { ex.printStackTrace(); } } }
/** 初始化freemarker */ private void initFreeMarker(ServletContextEvent sce) throws Exception { // freemarker上下文配置 Configuration freeMarkerConfig = new Configuration(Configuration.VERSION_2_3_23); freeMarkerConfig.setTemplateLoader(getTemplateLoader(sce)); freeMarkerConfig.setObjectWrapper( new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_23).build()); // freemaker setting freeMarkerConfig.setSetting("locale", "zh_CN"); freeMarkerConfig.setSetting("template_update_delay", "1"); freeMarkerConfig.setSetting("datetime_format", "yyyy-MM-dd HH:mm:ss"); freeMarkerConfig.setSetting("date_format", "HH:mm:ss"); freeMarkerConfig.setSetting("time_format", "yyyy-MM-dd"); freeMarkerConfig.setSetting("number_format", "#.##"); freeMarkerConfig.setSetting("default_encoding", "UTF-8"); freeMarkerConfig.setSetting("tag_syntax", "auto_detect"); freeMarkerConfig.setSetting("url_escaping_charset", "UTF-8"); sce.getServletContext().setAttribute(Constants.globalFreeMarkerConfig, freeMarkerConfig); }
@SuppressWarnings("deprecation") private static synchronized void init() throws Exception { Version version = new Version(2, 3, 23); Logger.selectLoggerLibrary(0); cfg = new Configuration(version); // cfg.setLogTemplateExceptions(true); cfg.setCacheStorage(new MruCacheStorage(0, Integer.MAX_VALUE)); cfg.setObjectWrapper(new DefaultObjectWrapper(version)); // cfg.setDirectoryForTemplateLoading(new // File(FreemarkerUtil.class.getClassLoader().getResource("template").getFile() )); // cfg.setClassForTemplateLoading(FreemarkerUtil.class, "template"); StringTemplateLoader st = new StringTemplateLoader(); // st.putTemplate("autoMall", // "<AutoMall><docid>${autoMall.docid!}</docid><Id>${autoMall.id!}</Id><Name><![CDATA[${autoMall.name!}]]></Name><NameAlias><![CDATA[${autoMall.nameAlias!}]]></NameAlias><ImgUrl><![CDATA[${autoMall.imgUrl!}]]></ImgUrl><CarStyleId>${autoMall.carStyleId!}</CarStyleId><CategoryId>${autoMall.categoryId!}</CategoryId><CategoryLevel>${autoMall.categoryLevel!}</CategoryLevel><BrandId>${autoMall.brandId!}</BrandId><SpecificationsId>${autoMall.specificationsId!}</SpecificationsId><FactoryNumber>${autoMall.factoryNumber!}</FactoryNumber><ShelvesTime>${autoMall.shelvesTime!}</ShelvesTime><RegionId>${autoMall.regionId!}</RegionId><IsHstock>${autoMall.isHstock!}</IsHstock><IsCerGoods>${autoMall.isCerGoods!}</IsCerGoods><IsStarProducts>${autoMall.isStarProducts!}</IsStarProducts><SalesVolume>${autoMall.salesVolume!}</SalesVolume><Evaluation>${autoMall.evaluation!}</Evaluation><Price>${autoMall.price!}</Price><GoodsModel><![CDATA[${autoMall.goodsModel!}]]></GoodsModel><UserDefinedBrandName><![CDATA[${autoMall.userDefinedBrandName!}]]></UserDefinedBrandName><FactoryName><![CDATA[${autoMall.factoryName!}]]></FactoryName><CarStyleName><![CDATA[${autoMall.carStyleName!}]]></CarStyleName><ServiceStationName><![CDATA[${autoMall.serviceStationName!}]]></ServiceStationName><StoreId>${autoMall.storeId!}</StoreId><StoreName><![CDATA[${autoMall.storeName!}]]></StoreName><AttrValue><![CDATA[${autoMall.attrValue!}]]></AttrValue><CarName><![CDATA[${autoMall.carName!}]]></CarName><BrandName><![CDATA[${autoMall.brandName!}]]></BrandName></AutoMall>"); String[] templates = new String[] {"carParts", "stores", "storesrecomm"}; for (String template : templates) { st.putTemplate(template, CommonUtil.readFileInJar("/template/" + template)); } cfg.setTemplateLoader(st); }
public void applyWebAppConfiguration(Configuration fmConfig, ServletContext servletContext) { String templatePathsText = servletContext.getInitParameter("com.netspective.sparx.template.freemarker.template-paths"); String templatePathsDelim = servletContext.getInitParameter( "com.netspective.sparx.template.freemarker.template-path-delim"); List templateLoaders = new ArrayList(); templateLoaders.add(stringTemplateLoader); templateLoaders.add(new WebappTemplateLoader(servletContext)); try { if (templatePathsText != null) { String[] templatePaths = TextUtils.getInstance() .split( templatePathsText, templatePathsDelim == null ? File.pathSeparator : templatePathsDelim, true); for (int i = 0; i < templatePaths.length; i++) templateLoaders.add( new FileTemplateLoader(new File(servletContext.getRealPath(templatePaths[i])))); } } catch (Exception e) { log.error("Unable to setup file templates loader.", e); throw new NestableRuntimeException(e); } // allow stuff to be loaded from CLASSPATH too (like Console, etc) templateLoaders.add(new ClassTemplateLoader(com.netspective.sparx.ProductRelease.class)); templateLoaders.add(new ClassTemplateLoader(com.netspective.axiom.ProductRelease.class)); templateLoaders.add(new ClassTemplateLoader(com.netspective.commons.ProductRelease.class)); fmConfig.setTemplateLoader( new MultiTemplateLoader( (TemplateLoader[]) templateLoaders.toArray(new TemplateLoader[templateLoaders.size()]))); configureSharedVariables(fmConfig); }
public static void sendMail(String mail, MailContent mailContent) throws Exception { Properties props = new Properties(); // try { // props.load(new FileInputStream(new File("settings.properties"))); // } catch (FileNotFoundException e1) { // e1.printStackTrace(); // } catch (IOException e1) { // e1.printStackTrace(); // } props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance( props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("*****@*****.**", "mycity@123"); } }); try { String a = mail; String b = mailContent.getTopp(); String c = mailContent.getBody1(); String d = mailContent.getBody2(); Message message = new MimeMessage(session); // MimeUtility.encodeText(subject, "utf-8", "B") message.setFrom(new InternetAddress("*****@*****.**")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mail)); message.setSubject(MimeUtility.encodeText(mailContent.getSubJect(), "utf-8", "B")); BodyPart body = new MimeBodyPart(); // freemarker stuff. Configuration cfg = new Configuration(); FileTemplateLoader ftl1 = new FileTemplateLoader( new File(ServletActionContext.getServletContext().getRealPath("/"))); cfg.setClassForTemplateLoading(cfg.getClass(), "/"); cfg.setTemplateLoader(ftl1); Template template = null; template = cfg.getTemplate("resources/mycity_cms/templates/mail/html-mail-template.html", "UTF-8"); Map<String, String> rootMap = new HashMap<String, String>(); rootMap.put("to", mailContent.getTopp()); rootMap.put("body1", mailContent.getBody1()); rootMap.put("body2", mailContent.getBody2()); Writer out = new StringWriter(); template.process(rootMap, out); // freemarker stuff ends. /* you can add html tags in your text to decorate it. */ // body.setContent(out.toString(), "text/html"); body.setContent(out.toString(), "text/html; charset=UTF-8"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(body); // cfg // body = new MimeBodyPart(); // // String filename = "hello.txt"; // DataSource source = new FileDataSource(filename); // body.setDataHandler(new DataHandler(source)); // body.setFileName(filename); // multipart.addBodyPart(body); // message.setContent(multipart, "text/html; charset=UTF-8;"); // Transport.send(message); } catch (MessagingException e) { LogUtility.logError(e, e.getMessage()); } System.out.println("Done...."); }
public static Configuration createConfiguration(Class<?> clazz, String path) { Configuration cfg = new Configuration(); cfg.setTemplateLoader(new ClassTemplateLoader(clazz, path)); cfg.setObjectWrapper(new DefaultObjectWrapper()); return cfg; }
static { Configuration freeMarkerConfiguration = new Configuration(); freeMarkerConfiguration.setTemplateLoader( new ClassTemplateLoader(TemplateEngineFactory.class, "/freemarker")); freeMarkerEngine.setConfiguration(freeMarkerConfiguration); }
private Template loadFreemarkerTemplate() throws IOException { Configuration cfg = new Configuration(); cfg.setTemplateLoader(new WebappTemplateLoader(ctx)); return cfg.getTemplate(TEMPLATE_PATH); }
@SuppressWarnings("deprecation") public String render(String templatePath, Map<String, Object> templateArgs) // , // boolean // usePublicFields) { logger.debug("trying to render " + templatePath); try { // keep configuration in session so we can reuse it if (conf == null) { logger.debug("create freemarker config"); // create configuration conf = new freemarker.template.Configuration(); conf.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); List<TemplateLoader> loaders = new ArrayList<TemplateLoader>(); // create template loader // load templates from MOLGENIS loaders.add(new ClassTemplateLoader(MolgenisOriginalStyle.class, "")); // load templates from plugins, can be anywere // (nb this method is deprecated but I can't see why) loaders.add(new ClassTemplateLoader()); for (Entry<String, Object> entry : templateArgs.entrySet()) { Object value = entry.getValue(); if (entry.getKey() != null && entry.getKey().equals("model") && value != null) { loaders.add(new ClassTemplateLoader(value.getClass())); // also add superclass because of generated code loaders.add(new ClassTemplateLoader(value.getClass().getSuperclass())); } } loaders.add(new FileTemplateLoader()); loaders.add(new FileTemplateLoader(new File("/"))); // ClassTemplateLoader loader1 = new ClassTemplateLoader( // Object.class, ""); // ClassTemplateLoader loader2 = new ClassTemplateLoader( // getClass().getSuperclass(), ""); MultiTemplateLoader mLoader = new MultiTemplateLoader(loaders.toArray(new TemplateLoader[loaders.size()])); conf.setTemplateLoader(mLoader); logger.debug("created freemarker config"); } // merge template conf.addAutoInclude("ScreenViewHelper.ftl"); WidgetFactory.configure(conf); Template template = conf.getTemplate(templatePath); StringWriter writer = new StringWriter(); template.process(templateArgs, writer); writer.close(); return writer.toString(); } catch (TemplateException e) { logger.error("rendering of template " + templatePath + " failed:"); e.printStackTrace(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); e.printStackTrace(pw); pw.flush(); sw.flush(); return sw.toString().replace("\n", "<br/>"); } catch (IOException e) { logger.error("rendering of template " + templatePath + " failed:"); e.printStackTrace(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); e.printStackTrace(pw); pw.flush(); sw.flush(); return sw.toString().replace("\n", "<br/>"); } }
@Override public void perform( final GraphRewrite event, final EvaluationContext context, final ReportModel payload) { String templatePath = payload.getTemplatePath(); String outputFilename = payload.getReportFilename(); ExecutionStatistics.get() .begin("FreeMarkerIterationOperation.render(" + templatePath + ", " + outputFilename + ")"); try { ReportService reportService = new ReportService(event.getGraphContext()); Path outputDir = Paths.get(reportService.getReportDirectory()); if (!Files.isDirectory(outputDir)) { Files.createDirectories(outputDir); } Path outputPath = outputDir.resolve(outputFilename); LOG.info( "Reporting: Writing template \"" + templatePath + "\" to output file \"" + outputPath.toAbsolutePath().toString() + "\""); Configuration freemarkerConfig = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); DefaultObjectWrapperBuilder objectWrapperBuilder = new DefaultObjectWrapperBuilder(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); objectWrapperBuilder.setUseAdaptersForContainers(true); freemarkerConfig.setObjectWrapper(objectWrapperBuilder.build()); freemarkerConfig.setAPIBuiltinEnabled(true); freemarkerConfig.setTemplateLoader(new FurnaceFreeMarkerTemplateLoader()); freemarkerConfig.setTemplateUpdateDelayMilliseconds(3600); Template template = freemarkerConfig.getTemplate(templatePath); Variables variables = Variables.instance(event); // just the variables Map<String, Object> vars = FreeMarkerUtil.findFreeMarkerContextVariables( variables, variableNames.toArray(new String[variableNames.size()])); if (useDefaultPayloadVariableName) { vars.put(DEFAULT_ITERATION_PAYLOAD_NAME, payload); } // also, extension functions (these are kept separate from vars in order to prevent them // from being stored in the associated data with the reportmodel) final Map<String, Object> freeMarkerExtensions; freeMarkerExtensions = furnace .getLockManager() .performLocked( LockMode.WRITE, new Callable<Map<String, Object>>() { @Override public Map<String, Object> call() throws Exception { return FreeMarkerUtil.findFreeMarkerExtensions(furnace, event); } }); Map<String, Object> objects = new HashMap<>(vars); objects.putAll(freeMarkerExtensions); try (FileWriter fw = new FileWriter(outputPath.toFile())) { template.process(objects, fw); } FreeMarkerUtil.addAssociatedReportData(event.getGraphContext(), payload, vars); } catch (IOException | TemplateException e) { LOG.log( Level.WARNING, "Template \"" + templatePath + "\" Failed to write report at \"" + outputFilename + "\" due to: " + e.getMessage(), e); } finally { ExecutionStatistics.get() .end("FreeMarkerIterationOperation.render(" + templatePath + ", " + outputFilename + ")"); } }