/** 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); }
/** * Constructor * * @throws ParserConfigurationException * @throws SAXException * @throws IOExeption si no puede leer fichero properties */ public GeneradorHtml() { try { java.io.InputStream is = this.getClass().getResourceAsStream("/entregar.properties"); if (is != null) props.load(is); File templates = new File(props.getProperty("carpeta.templates")); if (!templates.exists()) logger.debug("la carptea de templates no existe.... imposible crear los htmls"); cfg.setDirectoryForTemplateLoading(templates); root.put("noframesmensaje", "Esta página utiliza frames pero su navegador no los soporta"); root.put("enlaceCabecera", "Enlace con Cabecera"); root.put("enlaceMenu", "Enlace con Menu"); root.put("enlaceContenido", "Enlace con Contenido"); root.put("enlace", "Enlace con pagina"); root.put("redes", "red.es"); root.put("comunidad", "Comunidad de Madrid"); root.put("contenido", "Contenido"); root.put("contenidoPrincipal", "Contenido Principal"); root.put("salir", "Cerrar Ventana"); root.put("siguiente", "Ver Siguiente"); root.put("anterior", "Ver Anterior"); root.put("infSiguiente", "Informe Siguiente"); root.put("infAnterior", "Informe Anterior"); NodeModel.useDefaultXPathSupport(); cfg.setObjectWrapper(new DefaultObjectWrapper()); } catch (Exception e) { logger.error("No se pudo cargar el fichero properties"); } }
public static void main(String[] args) throws IOException, TemplateException { Locale.setDefault(Locale.US); boolean simple = false; Configuration cfg = new Configuration(); // Specify the data source where the template files come from. // Here I set a file directory for it: cfg.setDirectoryForTemplateLoading(new File("src/test/resources/templates")); // Specify how templates will see the data-model. This is an advanced topic... // but just use this: cfg.setObjectWrapper(new DefaultObjectWrapper()); Template temp; String name; if (simple) { temp = cfg.getTemplate("simple.ftl"); name = "simple"; } else { temp = cfg.getTemplate("extended.ftl"); name = "orders"; } String path = ""; write(temp, 1, path + name + "-1.xml", simple); write(temp, 50, path + name + "-50.xml", simple); write(temp, 500, path + name + "-500.xml", simple); write(temp, 5000, path + name + "-5000.xml", simple); write(temp, 50000, path + name + "-50000.xml", simple); write(temp, 500000, path + name + "-500000.xml", simple); System.out.println("done"); }
/** * @param templateName 模板文件名称 * @param templateEncoding 模板文件的编码方式 * @param root 数据模型根对象 */ public static void analysisTemplate( String templateName, String templateEncoding, Map<?, ?> root) { try { /** 创建Configuration对象 */ Configuration config = new Configuration(); /** 指定模板路径 */ File file = new File("templates"); /** 设置要解析的模板所在的目录,并加载模板文件 */ config.setDirectoryForTemplateLoading(file); /** 设置包装器,并将对象包装为数据模型 */ config.setObjectWrapper(new DefaultObjectWrapper()); /** 获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致 */ Template template = config.getTemplate(templateName, templateEncoding); /** 合并数据模型与模板 */ Writer out = new OutputStreamWriter(System.out); template.process(root, out); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { e.printStackTrace(); } }
// templatePath模板文件存放路径 // templateName 模板文件名称 // filename 生成的文件名称 public static void analysisTemplate( String templatePath, String templateName, String fileName, Map<?, ?> root) { try { Configuration config = new Configuration(); // 设置要解析的模板所在的目录,并加载模板文件 config.setDirectoryForTemplateLoading(new File(templatePath)); // 设置包装器,并将对象包装为数据模型 config.setObjectWrapper(new DefaultObjectWrapper()); // 获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致 // 否则会出现乱码 Template template = config.getTemplate(templateName, "UTF-8"); // 合并数据模型与模板 FileOutputStream fos = new FileOutputStream(fileName); Writer out = new OutputStreamWriter(fos, "UTF-8"); template.process(root, out); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { e.printStackTrace(); } }
public TemplateEngine(File outdir, File templatedir, String templatename) throws IOException { Configuration cfg = new Configuration(); cfg.setDirectoryForTemplateLoading(templatedir); cfg.setObjectWrapper(new DefaultObjectWrapper()); temp = cfg.getTemplate(templatename); this.out = outdir; }
@Before public void setUp() throws IOException { cfg = new Configuration(); cfg.setDirectoryForTemplateLoading(new File(TubainaBuilder.DEFAULT_TEMPLATE_DIR, "kindle")); cfg.setObjectWrapper(new BeansWrapper()); htmlBibGenerator = new HtmlBibliographyGenerator(cfg); }
private void initConfig() { if (cfg != null) return; cfg = new Configuration(); cfg.setClassForTemplateLoading(DefaultHTMLEmitter.class, "/freemarker/"); cfg.setObjectWrapper(new DefaultObjectWrapper()); }
static { /* Create and adjust freemarker configuration */ cfg.setClassForTemplateLoading( PropertyClassGenerator.class, "/net/jangaroo/properties/templates"); cfg.setObjectWrapper(new DefaultObjectWrapper()); cfg.setOutputEncoding("UTF-8"); }
private static Configuration buildFreemarkerConfiguration() { if (freemarkerConfiguration == null) { freemarkerConfiguration = new Configuration(); freemarkerConfiguration.setClassForTemplateLoading(TallyXMLGenerator.class, ""); freemarkerConfiguration.setObjectWrapper(new DefaultObjectWrapper()); } return freemarkerConfiguration; }
private Configuration getFreeMarkerConfig() { if (mFreemarkerConfig == null) { mFreemarkerConfig = new Configuration(); mFreemarkerConfig.setClassForTemplateLoading(getClass(), ""); mFreemarkerConfig.setObjectWrapper(new DefaultObjectWrapper()); } return mFreemarkerConfig; }
/** * 获取servlet上下文件的Configuration * * @param pageFolder * @return */ public static Configuration getServletCfg(String pageFolder) { Configuration cfg = new Configuration(); cfg.setServletContextForTemplateLoading( ThreadContextHolder.getHttpRequest().getSession().getServletContext(), pageFolder); cfg.setObjectWrapper(new DefaultObjectWrapper()); return cfg; }
/** * Gets the current Freemarker configuration. If the configuration does not exist it will be * initialized. * * @return configuration The current freemarker configuration. * @throws IOException thrown When the template directory doen not exist. */ private Configuration getConfiguration() throws IOException { if (configuration == null) { configuration = new Configuration(); configuration.setDirectoryForTemplateLoading(new File(templateDirectory)); configuration.setObjectWrapper(new DefaultObjectWrapper()); } return configuration; }
public static void init() { cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER); cfg.setCacheStorage(new freemarker.cache.MruCacheStorage(20, 250)); cfg.setNumberFormat("#"); cfg.setEncoding(Locale.getDefault(), "UTF-8"); cfg.setObjectWrapper(new DefaultObjectWrapper()); cfg.clearTemplateCache(); }
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); }
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"); }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ClassNotFoundException, SQLException, TemplateException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); Configuration c = new Configuration(); c.setDefaultEncoding("ISO-8859-1"); // setta il decoding della pagina in ingresso c.setOutputEncoding("ISO-8859-1"); // in output c.setNumberFormat(""); // per i numeri in virgola mobile e non c.setObjectWrapper( ObjectWrapper.BEANS_WRAPPER); // fa si che se voi passate al template un oggetto // viene visto come un associazione chiave valore da usare nel template c.setServletContextForTemplateLoading( getServletContext(), "templates"); // vatti a caricare questo template in base al contesto c c.setTemplateExceptionHandler( TemplateExceptionHandler .IGNORE_HANDLER); // handler di errori (default:statti zitto) cambia se vuoi debuggare // carica il template(il template non si reinderizza senza modellodati!) Template t = c.getTemplate("add_invitato.ftl.html"); Map<String, Object> data = new HashMap<String, Object>(); if (request.getSession(false) == null) { response.sendRedirect("index"); } if (request.getSession(false) != null) { data.put("login", 1); HttpSession s = request.getSession(false); int idtipo = (Integer) s.getAttribute("idtipo"); String username = (String) s.getAttribute("usersession"); int idutente = (Integer) s.getAttribute("idutente"); data.put("username", username); DataLayer dl = new DataLayerImpl(); UtenteDataLayer udl = dl.getUtenteDataLayer(dl.getC()); Utente utente = udl.readUtente(idutente); if (idtipo == 1) { data.put("tipo", "1"); // setta pannello admin } if (idtipo == 2) { data.put("tipo", "2"); // setta pannello organizzatore } String tmp = request.getParameter("id"); int idevento = Integer.parseInt(tmp); InvitatoDataLayer idl = dl.getInvitatoDataLayer(dl.getC()); List<Invitato> lista = idl.getRubricaAndInvitati(idutente, idevento); data.put("invitati", lista); data.put("idevento", idevento); } try { t.process(data, response.getWriter()); } finally { out.close(); } }
/** * 创建历史成交数据 * * @param buildingTab * @param estateTab */ private void createChartXmlFile( TransanctionStatManager transanctionStatManager, String xmlFilePath, String xmlAvgPriceFile, String xmlCountFile, List tenYears) { try { // 生成所有交易年数据文件 String filesp = File.separator; String templatePath = Constants.REALPATH + "WEB-INF" + filesp + "pages" + filesp + "maker" + filesp + "chart" + filesp; String templateAvgPriceFileName = "chart_avgprice_xml.ftl"; String templateCountFileName = "chart_count_xml.ftl"; Configuration cfg = new Configuration(); cfg.setNumberFormat("0.######"); cfg.setDirectoryForTemplateLoading(new File(templatePath)); cfg.setObjectWrapper(new DefaultObjectWrapper()); Map root = new HashMap(); root.put("tenYears", tenYears); // 生成十年交易平均价格数据文件 Template templateAvgPrice = cfg.getTemplate(templateAvgPriceFileName, "UTF-8"); Writer avgpriceOut = new OutputStreamWriter(new FileOutputStream(xmlAvgPriceFile), "UTF-8"); try { templateAvgPrice.process(root, avgpriceOut); } catch (TemplateException e) { e.printStackTrace(); } avgpriceOut.flush(); avgpriceOut.close(); // 生成十年交易总数数据文件 Template templateCount = cfg.getTemplate(templateCountFileName, "UTF-8"); Writer countOut = new OutputStreamWriter(new FileOutputStream(xmlCountFile), "UTF-8"); try { templateCount.process(root, countOut); } catch (TemplateException e) { e.printStackTrace(); } countOut.flush(); countOut.close(); } catch (Exception e) { e.printStackTrace(); } }
/** * インスタンスを生成します。 * * @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 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(); } }
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); } }); }
@Test public void hello() throws IOException, TemplateException { Configuration cfg = new Configuration(); // 设置模板文件夹 cfg.setDirectoryForTemplateLoading(new ClassPathResource("templateDirectory/").getFile()); cfg.setObjectWrapper(new DefaultObjectWrapper()); Template temp = cfg.getTemplate("hello.ftl"); // ${Salutation} ${First_Name} ${Surname} Map<String, Object> map = new HashMap<String, Object>(); map.put("msg", "HelloWord"); console(temp, map); }
@Test public void testTemplate() throws Exception { Configuration cfg = new Configuration(); cfg.setObjectWrapper(new FeatureWrapper()); cfg.setClassForTemplateLoading(FeatureTemplate.class, ""); Template template = cfg.getTemplate("description.ftl"); assertNotNull(template); // create some data GeometryFactory gf = new GeometryFactory(); SimpleFeatureType featureType = DataUtilities.createType("testType", "string:String,int:Integer,double:Double,geom:Point"); SimpleFeature f = SimpleFeatureBuilder.build( featureType, new Object[] { "three", new Integer(3), new Double(3.3), gf.createPoint(new Coordinate(3, 3)) }, "fid.3"); ByteArrayOutputStream output = new ByteArrayOutputStream(); template.process(f, new OutputStreamWriter(output)); // template.process(f, new OutputStreamWriter(System.out)); // This generates the following: // <h4>testType</h4> // <ul class="textattributes"> // <li><strong><span class="atr-name">string</span>:</strong> <span // class="atr-value">three</span></li> // <li><strong><span class="atr-name">int</span>:</strong> <span // class="atr-value">3</span></li> // <li><strong><span class="atr-name">double</span>:</strong> <span // class="atr-value">3.3</span></li> // // </ul> // TODO docbuilder cannot parse this? May expect encapsulation, which table did provide // DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); // Document document = docBuilder.parse(new ByteArrayInputStream(output.toByteArray())); // assertNotNull(document); // assertEquals("table", document.getDocumentElement().getNodeName()); }
private void initialize() { try { Configuration cfg = new Configuration(new Version(2, 3, 23)); cfg.setCacheStorage(new NullCacheStorage()); cfg.setObjectWrapper(new DefaultObjectWrapperBuilder(new Version(2, 3, 23)).build()); Reader templateReader = new BufferedReader( new InputStreamReader(AltoXMLExporter.class.getResourceAsStream("jochre.ftl"))); this.template = new Template("freemarkerTemplate", templateReader, cfg); } catch (IOException e) { LOG.error("Failed writing to " + this.getClass().getSimpleName(), e); throw new RuntimeException(e); } }
public static Configuration cfg(String templatePath) { if (configuration == null) { Configuration cfg = new Configuration(); cfg.setEncoding(Locale.CHINA, "utf-8"); try { cfg.setDirectoryForTemplateLoading( new File(ServiceManager.getInstance().getWebContextPath() + templatePath)); } catch (IOException e) { logger.error(e); throw new RuntimeException("设置模板文件路径失败!"); } // 设置定义的编码 cfg.setObjectWrapper(new DefaultObjectWrapper()); return cfg; } else return configuration; }
@Override protected Configuration createConfiguration(Object data, Class clazz) { Configuration cfg = super.createConfiguration(data, clazz); cfg.setObjectWrapper( new ObjectToMapWrapper<DataStoreInfo>(DataStoreInfo.class) { @Override protected void wrapInternal(Map properties, SimpleHash model, DataStoreInfo object) { List<FeatureTypeInfo> featureTypes = catalog.getFeatureTypesByDataStore(object); properties.put( "featureTypes", new CollectionModel(featureTypes, new ObjectToMapWrapper(FeatureTypeInfo.class))); } }); return cfg; }
public void genServerConfFile() throws IOException, TemplateException { Configuration cfg = new Configuration(Configuration.VERSION_2_3_23); cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER); cfg.setClassForTemplateLoading(this.getClass(), "/"); Template template = cfg.getTemplate("template/galera_server.ftl"); // Build the data-model Map<String, Object> data = new HashMap<>(); data.put("ownHostInfo", hostInfo); data.put("otherHostInfos", otherHostInfo); // Console output String path = getClass().getClassLoader().getResource("").getFile(); FileWriter out = new FileWriter(path + "/template/server.cnf." + hostInfo.getHostName()); template.process(data, out); out.flush(); out.close(); }
/** Initialize Freemarker Configuration */ public void initializeFreemarkerConfiguration() { configuration = new Configuration(); // make maps work in Freemarker when map key is not a String BeansWrapper beansWrapper = BeansWrapper.getDefaultInstance(); beansWrapper.setSimpleMapWrapper(true); configuration.setObjectWrapper(beansWrapper); // make sure that numbers are not formatted as 1,000 but as 1000 instead configuration.setNumberFormat("computer"); // TODO: make configurable? configuration.setDateFormat(ISO8601_FORMAT); configuration.setAutoFlush(true); }
@Override protected void setUp() throws Exception { super.setUp(); try { Configuration config = new Configuration(); DefaultObjectWrapper wrapper = new DefaultObjectWrapper(); config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER); config.setObjectWrapper(wrapper); config.setTemplateExceptionHandler(TemplateExceptionHandler.DEBUG_HANDLER); TemplateModel templateModel = this.createModel(wrapper); ExecutorBeanContainer ebc = new ExecutorBeanContainer(config, templateModel); super.getRequestContext() .addExtraParam(SystemConstants.EXTRAPAR_EXECUTOR_BEAN_CONTAINER, ebc); } catch (Throwable t) { throw new Exception(t); } }