public static void main(String[] args) { final Configuration configuration = new Configuration(); configuration.setClassForTemplateLoading(HelloSparkFreemarker.class, "/"); Spark.get( "/", new Route() { public Object handle(Request request, Response response) throws Exception { try { Template template = configuration.getTemplate("hello.ftl"); StringWriter writer = new StringWriter(); Map<String, Object> helloMap = new HashMap<String, Object>(); helloMap.put("name", "Giovanni"); template.process(helloMap, writer); return writer; } catch (Exception e) { e.printStackTrace(); return "Error 500"; } } }); }
/** Description: */ public static void makeController() throws Exception { Configuration cfg = getCfg(); Template template = cfg.getTemplate("controller.html"); // 生成文件设置 String path = getJavaFileRoot() + File.separator + PropertyUtil.getValue("code.src.controller.root") + File.separator + key; mkdirs(path); path += File.separator + upperKey + "Controller.java"; FileWriter sw = new FileWriter(new File(path)); WeakHashMap<String, Object> data = new WeakHashMap<String, Object>(); data.put("packageName", controllerPackagePath); // 包名 data.put("pagePrefix", urlPrefix.substring(1)); data.put("urlPrefix", urlPrefix); data.put("key", key); data.put("UpperKey", upperKey); data.put("ZhKey", zhKey); data.put("author", author); data.put("createDate", createDate); data.put("EntityClass", entityPackagePath + "." + upperKey + "Entity"); data.put("serviceInterFace", servicePackagePath + ".I" + upperKey + "Service"); data.put("primaryKey", primaryKey.getName()); data.put("UpperPrimaryKey", StringUtil.upperFirst(primaryKey.getName())); template.process(data, sw); }
public static void makeEntity() throws Exception { Configuration cfg = getCfg(); Template template = cfg.getTemplate("entity.html"); // 生成文件设置 String path = getJavaFileRoot() + File.separator + PropertyUtil.getValue("code.src.entity.root"); mkdirs(path); path += File.separator + upperKey + "Entity.java"; FileWriter sw = new FileWriter(new File(path)); WeakHashMap<String, Object> data = new WeakHashMap<String, Object>(); data.put("packageName", entityPackagePath); data.put("key", key); data.put("UpperKey", upperKey); data.put("ZhKey", zhKey); data.put("author", author); data.put("createDate", createDate); List<Field> list = MysqlUtil.getInstance().getTableField(); noCommonFieldList = removeCommonFields(list); data.put("fieldList", list); data.put("noCommonFieldList", noCommonFieldList); primaryKey = MysqlUtil.getInstance().getPrimaryKey(list); fieldList = list; String level = PropertyUtil.getValue("created.code.level"); if (!levels.contains(level)) { level = "all"; } if ("all".equals(level) || "entity".equals(level)) { template.process(data, sw); } }
@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); }
/** * Description: 生成service相关类 * * @throws Exception */ public static void makeService() throws Exception { Configuration cfg = getCfg(); // interface Template template = cfg.getTemplate("serviceInterface.html"); // 生成文件设置 String path = getJavaFileRoot() + File.separator + PropertyUtil.getValue("code.src.service.root") + File.separator + key; mkdirs(path); path += File.separator + "I" + upperKey + "Service.java"; FileWriter sw = new FileWriter(new File(path)); WeakHashMap<String, Object> data = new WeakHashMap<String, Object>(); data.put("packageName", servicePackagePath); // 包名 data.put("EntityClass", entityPackagePath + "." + upperKey + "Entity"); data.put("key", key); data.put("UpperKey", upperKey); data.put("ZhKey", zhKey); data.put("primaryKey", primaryKey.getName()); data.put("UpperPrimaryKey", StringUtil.upperFirst(primaryKey.getName())); data.put("PrimaryKeyType", StringUtil.upperFirst(primaryKey.getType())); data.put("author", author); data.put("createDate", createDate); template.process(data, sw); // impl Template implTemplate = cfg.getTemplate("service.html"); String serviceImplPackagePath = servicePackagePath + ".impl"; // 生成文件设置 String implPath = getJavaFileRoot() + File.separator + PropertyUtil.getValue("code.src.service.root") + File.separator + key + File.separator + "impl"; mkdirs(implPath); implPath += File.separator + upperKey + "ServiceImpl.java"; FileWriter implWriter = new FileWriter(new File(implPath)); WeakHashMap<String, Object> implData = new WeakHashMap<String, Object>(); implData.put("packageName", serviceImplPackagePath); // 包名 implData.put("key", key); implData.put("UpperKey", upperKey); implData.put("ZhKey", zhKey); implData.put("EntityClass", entityPackagePath + "." + upperKey + "Entity"); implData.put("daoInterFace", daoPackagePath + ".I" + upperKey + "Dao"); implData.put("serviceInterFace", servicePackagePath + ".I" + upperKey + "Service"); implData.put("primaryKey", primaryKey.getName()); implData.put("UpperPrimaryKey", StringUtil.upperFirst(primaryKey.getName())); implData.put("PrimaryKeyType", StringUtil.upperFirst(primaryKey.getType())); implData.put("author", author); implData.put("createDate", createDate); implTemplate.process(implData, implWriter); }
public static Configuration buildConfiguration(String directory) throws IOException { Configuration cfg = new Configuration(); Resource path = new DefaultResourceLoader().getResource(directory); cfg.setDirectoryForTemplateLoading(path.getFile()); cfg.setDefaultEncoding("utf-8"); return cfg; }
private void initConfig() { if (cfg != null) return; cfg = new Configuration(); cfg.setClassForTemplateLoading(DefaultHTMLEmitter.class, "/freemarker/"); cfg.setObjectWrapper(new DefaultObjectWrapper()); }
public static void main(String[] args) throws Exception { /* You should do this ONLY ONCE in the whole application life-cycle: */ /* Create and adjust the configuration singleton */ Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); cfg.setDirectoryForTemplateLoading(new File("/Users/ian.goldsmith/projects/freemarker")); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); /* * You usually do these for MULTIPLE TIMES in the application * life-cycle: */ /* Create a data-model */ Map message = new HashMap(); message.put( "contentAsXml", freemarker.ext.dom.NodeModel.parse( new File("/Users/ian.goldsmith/projects/freemarker/test.xml"))); Map root = new HashMap(); root.put("message", message); /* Get the template (uses cache internally) */ Template temp = cfg.getTemplate("testxml.ftl"); /* Merge data-model with template */ Writer out = new OutputStreamWriter(System.out); temp.process(root, out); // Note: Depending on what `out` is, you may need to call `out.close()`. // This is usually the case for file output, but not for servlet output. }
/** * 模版配置 * * @param resource * @return */ private static Configuration getConfig(String resource) { Configuration cfg = new Configuration(); cfg.setDefaultEncoding("UTF-8"); cfg.setClassForTemplateLoading(DbTableProcess.class, resource); return cfg; }
/** * 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"); } }
@Test public void testFreemarkerAccess() throws Exception { configuration = new Configuration(); configuration.setDirectoryForTemplateLoading(new File("src/test/resources/")); Map<String, Object> model = new HashMap<String, Object>(); UID homepageUID = new UID("foaf", "homepage"); UID workpageUID = new UID("foaf", "workpage"); UID documentUID = new UID("foaf", "mypage"); DummyResource resource = new DummyResource(); DummyProperty prop = new DummyProperty<UID>(homepageUID); prop.getLiteralsSet().add(new LIT("http://www.koti.com")); resource.getPropertiesMap().put(homepageUID, prop); prop.getReferencesSet().add(documentUID); prop = new DummyProperty<UID>(workpageUID); prop.getLiteralsSet().add(new LIT("http://www.mysema.com")); prop.getLiteralsSet().add(new LIT("http://www.mysema1.com")); resource.getPropertiesMap().put(workpageUID, prop); model.put("resource", resource); model.put("uid", homepageUID); Writer writer = new PrintWriter(System.out); configuration.getTemplate("freemarker_test.ftl").process(model, writer); // writer.close(); }
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 toMailAddr 收信人地址 * @param subject email主题 * @param templatePath 模板地址 * @param map 模板map */ public static void sendFtlMail( String toMailAddr, String subject, String templatePath, Map<String, Object> map) { Template template = null; Configuration freeMarkerConfig = null; HtmlEmail hemail = new HtmlEmail(); try { hemail.setHostName(getHost(from)); hemail.setSmtpPort(getSmtpPort(from)); hemail.setCharset(charSet); hemail.addTo(toMailAddr); hemail.setFrom(from, fromName); hemail.setAuthentication(username, password); hemail.setSubject(subject); freeMarkerConfig = new Configuration(); freeMarkerConfig.setDirectoryForTemplateLoading(new File(getFilePath())); // 获取模板 template = freeMarkerConfig.getTemplate(getFileName(templatePath), new Locale("Zh_cn"), "UTF-8"); // 模板内容转换为string String htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map); System.out.println(htmlText); hemail.setMsg(htmlText); hemail.send(); System.out.println("email send true!"); } catch (Exception e) { e.printStackTrace(); System.out.println("email send error!"); } }
/** @param args */ public static void main(String[] args) { // TODO Auto-generated method stub final Configuration configuration = new Configuration(); configuration.setClassForTemplateLoading(HelloWorldFreeMarkerStyle.class, "/"); Spark.get( new Route("/") { public Object handle(final Request request, final Response response) { StringWriter writer = new StringWriter(); try { Template helloTemplate = configuration.getTemplate("hello.ftl"); Map<String, Object> helloMap = new HashMap<String, Object>(); helloMap.put("name", "Puneeth"); // System.out.println(helloMap.get("name")); helloTemplate.process(helloMap, writer); // System.out.println(writer); } catch (Exception e) { // TODO: handle exception halt(500); e.printStackTrace(); } return writer; } }); }
public static void main(String[] args) { final Configuration config = new Configuration(); config.setClassForTemplateLoading(HelloWorldFreemarkerStyle.class, "/"); Spark.get( new Route("/") { @Override public Object handle(final Request request, final Response response) { StringWriter writer = new StringWriter(); try { Template hello = config.getTemplate("hello.ftl"); Map<String, Object> map = new HashMap<String, Object>(); map.put("name", "World"); hello.process(map, writer); } catch (Exception e) { halt(500); e.printStackTrace(); } return writer; } }); }
static { /* Create and adjust freemarker configuration */ cfg.setClassForTemplateLoading( PropertyClassGenerator.class, "/net/jangaroo/properties/templates"); cfg.setObjectWrapper(new DefaultObjectWrapper()); cfg.setOutputEncoding("UTF-8"); }
public static void main(String[] args) { Writer out = null; String gAME_VERSION = "1"; String tAG_VERSION = "195"; String channelName = "ZHANGYUE"; String cHANNEL_ID = "3058"; String mEIDA_CHANNEL = "2011552002"; Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); try { cfg.setDirectoryForTemplateLoading(new File("./templates")); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); Map<String, Object> root = new HashMap<String, Object>(); XMTLBBConfig xConfig = XTestMain.getConfigBean( channelName, cHANNEL_ID, gAME_VERSION, tAG_VERSION, mEIDA_CHANNEL); root.put("XMTLBB", xConfig); File target = new File("./target/" + cHANNEL_ID + "/config.properties"); target.getParentFile().mkdirs(); Template temp = cfg.getTemplate("config.ftl"); out = new OutputStreamWriter(new FileOutputStream(target), "utf-8"); temp.process(root, out); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } }
private void generateCode(Writer modelCodeWriter) throws IOException, TemplateException { Map<String, Object> modelProperties = Maps.newHashMap(); List<Map<String, Object>> eventList = Lists.newLinkedList(); modelProperties.put("modelName", modelName); modelProperties.put("events", eventList); modelProperties.put("variables", variableList); for (Event event : events) { EventBuilder eventBuilder = new EventBuilder(); Event.EventState eventState = event.getEventState(); Event.Function eventFunctionMatcher = new Event.Function(eventState.getFunctionBody()); eventFunctionMatcher.process(); eventBuilder.setName(eventState.getName()); eventBuilder.setParameters(eventFunctionMatcher.getParameters()); eventBuilder.setBody(eventFunctionMatcher.getBody()); for (Map.Entry<Event, List<Edge>> targetEntry : adjacencyList.row(event).entrySet()) { List<Edge> edges = targetEntry.getValue(); for (Edge edge : edges) { eventBuilder.addEdge(edge); } } eventList.add(eventBuilder.asMap()); } Templates templatesInstance = Templates.getTemplatesInstance(); Configuration templateConfiguration = templatesInstance.getConfiguration(); Template modelTemplate = templateConfiguration.getTemplate("Simulation.java.ftl"); modelTemplate.process(modelProperties, modelCodeWriter); }
/** * @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(); } }
private String buildEmailAlarmContent(ThresholdAlarmMeta meta) { Map<Object, Object> root = new HashMap<Object, Object>(); StringWriter sw = new StringWriter(5000); root.put("rule", buildRuleMeta(meta.getDuration())); root.put("count", meta.getRealCount()); root.put("domain", meta.getDomain()); root.put("date", meta.getDate()); root.put("url", buildProblemUrl(meta.getBaseShowUrl(), meta.getDomain(), meta.getDate())); try { String type = meta.getType(); if (type.equalsIgnoreCase(AlertInfo.EXCEPTION)) { Template t = m_configuration.getTemplate("exceptionAlarm.ftl"); t.process(root, sw); } else if (type.equalsIgnoreCase(AlertInfo.SERVICE)) { Template t = m_configuration.getTemplate("serviceAlarm.ftl"); t.process(root, sw); } } catch (Exception e) { Cat.logError(e); } return sw.toString(); }
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; }
public void generate() throws Exception { Configuration conf = new Configuration(); conf.setDefaultEncoding("UTF-8"); conf.setClassForTemplateLoading(this.getClass(), "../../../../../../"); Map root = new HashedMap(); Entity entity = (Entity) getModel(); root.put("entity", entity); File file = new File( System.getProperty("src.path") + StringUtils.replace(entity.getPackageDeclaration(), ".", File.separator)); if (!file.exists()) { file.mkdirs(); } getTemplate(conf) .process( root, new OutputStreamWriter( new FileOutputStream( file.getAbsolutePath() + File.separator + entity.getDeclarationName() + JAVA_EXTENSION), conf.getDefaultEncoding())); }
// 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(); } }
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; }
@BeforeMethod public void setUp() throws Exception { _uriInfo = new MockUriInfo(); _secMaster = new InMemorySecurityMaster(); _secLoader = new SecurityLoader() { @Override public Map<ExternalIdBundle, UniqueId> loadSecurity( Collection<ExternalIdBundle> identifiers) { throw new UnsupportedOperationException("load security not supported"); } @Override public SecurityMaster getSecurityMaster() { return _secMaster; } }; HistoricalTimeSeriesMaster htsMaster = new InMemoryHistoricalTimeSeriesMaster(); addSecurity(WebResourceTestUtils.getEquitySecurity()); addSecurity(WebResourceTestUtils.getBondFutureSecurity()); _webSecuritiesResource = new WebSecuritiesResource(_secMaster, _secLoader, htsMaster); MockServletContext sc = new MockServletContext("/web-engine", new FileSystemResourceLoader()); Configuration cfg = FreemarkerOutputter.createConfiguration(); cfg.setServletContextForTemplateLoading(sc, "WEB-INF/pages"); FreemarkerOutputter.init(sc, cfg); _webSecuritiesResource.setServletContext(sc); _webSecuritiesResource.setUriInfo(_uriInfo); }
/** * método que permite generar fichero de metadatos en carpeta separada comprueba si el fichero * manifest tiene un lomes integrado o un metadato externo. si el ODE no tiene metadatos.. no * genera nada */ private void obtenerLOMES(String lomFileName) throws Exception { FileOutputStream fo = null; FileInputStream fin = null; Writer out = null; File lomes = null; Template template; try { if (pathLomesExterno != null) { lomes = new File(dirDestino + File.separator + lomFileName); if (!lomes.exists()) lomes.createNewFile(); } if (pathLomesExterno != null && pathLomesExterno.equals("")) { // tiene lomes y no es un fichero externo adlcp:location template = cfg.getTemplate("lomes.ftl"); cfg.setDefaultEncoding("UTF-8"); fo = new FileOutputStream(lomes); out = new OutputStreamWriter(fo, "UTF-8"); Environment env = template.createProcessingEnvironment(root, out); env.setOutputEncoding("UTF-8"); env.process(); out.flush(); } else if (pathLomesExterno != null && !pathLomesExterno.equals( "")) { // fichero externo.. por lo que solamente lo copio al destino File origen = new File(pathOde + "/" + pathLomesExterno); fin = new FileInputStream(origen); fo = new FileOutputStream(lomes); int c; while ((c = fin.read()) >= 0) { fo.write(c); } fin.close(); fo.close(); origen = null; } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Error en GeneradorHTML:obtenerLOMES .. " + e.getMessage()); } throw e; } finally { lomes = null; if (fo != null) { try { fo.close(); } catch (IOException e) { } } if (fin != null) { try { fin.close(); } catch (IOException e) { } } } }
/** * 获取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; }
private Configuration getFreeMarkerConfig() { if (mFreemarkerConfig == null) { mFreemarkerConfig = new Configuration(); mFreemarkerConfig.setClassForTemplateLoading(getClass(), ""); mFreemarkerConfig.setObjectWrapper(new DefaultObjectWrapper()); } return mFreemarkerConfig; }
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); }
private static Configuration buildFreemarkerConfiguration() { if (freemarkerConfiguration == null) { freemarkerConfiguration = new Configuration(); freemarkerConfiguration.setClassForTemplateLoading(TallyXMLGenerator.class, ""); freemarkerConfiguration.setObjectWrapper(new DefaultObjectWrapper()); } return freemarkerConfiguration; }