org.beetl.core.GroupTemplate Java Examples

The following examples show how to use org.beetl.core.GroupTemplate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AlbianBeetlTemplateService.java    From Albianj2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void loading() throws AlbianParserException {
    try {
        FileResourceLoader resourceLoader = new FileResourceLoader(c.getRootPath(), c.getCharset());
        Configuration cfg = Configuration.defaultConfiguration();
        cfg.setHtmlTagSupport(true);
        gt = new GroupTemplate(resourceLoader, cfg);
        StringTemplateResourceLoader rl = new StringTemplateResourceLoader();
        sgt = new GroupTemplate(rl, cfg);
        Map<String, CustomTagConfigurtion> ctcs = c.getCustomTags();
        for (Map.Entry<String, CustomTagConfigurtion> entry : ctcs.entrySet()) {
            CustomTagConfigurtion ctc = entry.getValue();
            Class<? extends Tag> cla = (Class<? extends Tag>) AlbianClassLoader.getInstance().loadClass(ctc.getFullClassname());
            if (null != cla) {
                gt.registerTag(ctc.getName(), cla);
                sgt.registerTag(ctc.getName(), cla);
            }
        }

    } catch (Exception e) {
        throw new AlbianParserException(e);
    }

}
 
Example #2
Source File: ClasspathResourceLoader.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void init(GroupTemplate gt)
{
	Map<String, String> resourceMap = gt.getConf().getResourceMap();
	//如果配置文件也配置了root
	if (resourceMap.get("root") != null)
	{
		String temp = resourceMap.get("root");
		temp = checkRoot(temp);
		this.root = this.getChildPath(root, temp);
	}

	if (this.charset == null)
	{
		this.charset = resourceMap.get("charset");

	}

	this.functionSuffix = resourceMap.get("functionSuffix");

	this.autoCheck = Boolean.parseBoolean(resourceMap.get("autoCheck"));
	this.functionRoot = resourceMap.get("functionRoot");


}
 
Example #3
Source File: FastRuntimeEngine.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Program createProgram(Resource rs, Reader reader, Map<Integer, String> textMap, String cr, GroupTemplate gt)
{

	Program orginalProgram = super.createProgram(rs, reader, textMap, cr, gt);

	//copy 一个出来分析
	ProgramMetaData metaData = orginalProgram.metaData.copy();
	Program copyProgram = new Program();
	copyProgram.metaData = metaData;
	copyProgram.res = orginalProgram.res;
	copyProgram.gt = orginalProgram.gt;
	copyProgram.rs = orginalProgram.rs;
	Probe nextFilter = new BasicProgramOptProbe();
	nextFilter.setProgram(copyProgram);

	TypeBindingProbe firstFilter = new TypeBindingProbe(copyProgram, nextFilter);
	//在能优化前,按照原有的program执行,但每次都会执行fitler以看看是否能优化
	FilterProgram filterProgram = new FilterProgram(orginalProgram, copyProgram, firstFilter);
	return filterProgram;
}
 
Example #4
Source File: BeetlUtil.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void autoFileFunctionRegister(GroupTemplate gt,File funtionRoot, String ns, String path,String functionSuffix){
	File[] files = funtionRoot.listFiles();
	for (File f : files)
	{
		if (f.isDirectory())
		{
			autoFileFunctionRegister(gt,f, f.getName().concat("."), path.concat(f.getName()).concat("/"),functionSuffix);
		}
		else if (f.getName().endsWith(functionSuffix))
		{
			String resourceId = path + f.getName();
			String fileName = f.getName();
			fileName = fileName.substring(0, (fileName.length() - functionSuffix.length() - 1));
			String functionName = ns.concat(fileName);
			FileFunctionWrapper fun = new FileFunctionWrapper(resourceId);
			gt.registerFunction(functionName, fun);
		}
	}
}
 
Example #5
Source File: AttributeCodeGen.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static AttributeAccess createAAClass(Class c, String name, String methodName, Class returnType,
		Class parameterType,GroupTemplate gt)
{
	try
	{
		BCW bcw = BCWFactory.defaultFactory.getAttribyteBCW(c, name, methodName, returnType, parameterType);
		byte[] bs = bcw.getClassByte();
		String clsName = c.getName() + "_" + name;
		return instance(bs, clsName,gt);

	}
	catch (Exception ex)
	{
		throw new RuntimeException(ex);
	}

}
 
Example #6
Source File: JavaCodeGen.java    From springboot-plus with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void make(Target target, Entity entity) {
	GroupTemplate gt = target.getGroupTemplate();
	Template template = gt.getTemplate("/java/query.java");
	List<Attribute> list = new ArrayList<Attribute>();
	for(Attribute attr:entity.getList()) {
		if(attr.isShowInQuery()) {
			list.add(attr);
		}
	}
	
	if(list.isEmpty()) {
		list.add(entity.getIdAttribute());
	}
	
	template.binding("entity", entity);
	template.binding("target", target);
	template.binding("package", gen.basePackage+".web.query");
	template.binding("basePackage", gen.basePackage);
	template.binding("attrs", list);
	String content = template.render();
	target.flush(this, content);
}
 
Example #7
Source File: AttributeCodeGen.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static AttributeAccess instance(byte[] bs, String clsName,GroupTemplate gt)
	{
//		javap -c xxxx 
//		try{
//			FileOutputStream fos = new FileOutputStream(new File("d:/"+clsName+".class"));
//			fos.write(bs);
//			fos.close();
//		}catch(Exception ex){
//			ex.printStackTrace();
//		}
		
		Class fieldAccessorClass =  gt.getByteLoader().defineClass(clsName, bs);
		AttributeAccess ac;
		try
		{
			ac = (AttributeAccess) fieldAccessorClass.newInstance();
			return ac;
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}

	}
 
Example #8
Source File: BeetlTemplateUtil.java    From ApplicationPower with Apache License 2.0 6 votes vote down vote up
/**
 * @param path
 * @param params
 * @return
 */
public static Map<String, String> getTemplatesRendered(String path, Map<String, Object> params) {
    Map<String, String> templateMap = new HashMap<>();
    File[] files = FileUtil.getResourceFolderFiles(path);
    GroupTemplate gt = getGroupTemplate(path);
    for (File f : files) {
        if (f.isFile()) {
            String fileName = f.getName();
            Template tp = gt.getTemplate(fileName);
            if (null != params) {
                tp.binding(params);
            }
            templateMap.put(fileName, tp.render());
        }
    }
    return templateMap;
}
 
Example #9
Source File: BeetlFrameworkConfig.java    From feiqu-opensource with Apache License 2.0 6 votes vote down vote up
@Bean
public BeetlTemplateCustomize beetlTemplateCustomize(@Qualifier("beetl_functions") Functions fn) {
    return new BeetlTemplateCustomize() {

        @Override
        public void customize(GroupTemplate groupTemplate) {
            groupTemplate.registerFunctionPackage("c", fn);
            Map vars = new HashMap<String, Object>() {{
                put("VERSION", Global.getConfig("feiqu.cssVersion"));
                put("LAYUI_VERSION", Global.getConfig("feiqu.layuiVersion"));
                put("DOMAIN_URL", Global.getConfig("feiqu.domainUrl"));
            }};
            groupTemplate.setSharedVars(vars);

        }

    };
}
 
Example #10
Source File: ServletGroupTemplate.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private ServletGroupTemplate()
{

	try
	{
		Configuration cfg = Configuration.defaultConfiguration();
		WebAppResourceLoader resourceLoader = new WebAppResourceLoader();
		groupTemplate = new GroupTemplate(resourceLoader, cfg);
	}
	catch (Exception ex)
	{
		ex.printStackTrace();
		throw new RuntimeException("加载GroupTemplate失败", ex);

	}

}
 
Example #11
Source File: BeetlTest.java    From seed with Apache License 2.0 6 votes vote down vote up
@Test
public void buildFromFile() throws IOException {
    /*
    <!DOCTYPE HTML>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>beetl demo</title>
    </head>
    <body>
        长篇架空武侠小说:${book},真的忍心烂尾么??
    </body>
    </html>
    */
    //使用模板文件位置实例化模板对象
    GroupTemplate groupTemplate = new GroupTemplate(new FileResourceLoader("C:/Users/Jadyer/Desktop/"), Configuration.defaultConfiguration());
    //设置模板所需的共享变量
    Map<String, Object> sharedVars = new HashMap<>();
    sharedVars.put("book", "英雄志");
    groupTemplate.setSharedVars(sharedVars);
    //模板解析成真实的HTML到文件(注意:模板文件source.html必须存在,dest.html不存在时beetl会自动创建并填充内容,dest.html存在时beetl会覆盖该文件)
    groupTemplate.getTemplate("source.html").renderTo(FileUtils.openOutputStream(new File("C:/Users/Jadyer/Desktop/dest.html")));
    //生成PDF文件
    //WkhtmltopdfUtil.convert(null, "C:/Users/Jadyer/Desktop/dest.html", "C:/Users/Jadyer/Desktop/dest.pdf");
}
 
Example #12
Source File: BeetlActionResult.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public BeetlActionResult()
{

	try
	{

		Configuration cfg = Configuration.defaultConfiguration();
		WebAppResourceLoader resourceLoader = new WebAppResourceLoader();
		groupTemplate = new GroupTemplate(resourceLoader, cfg);

	}
	catch (IOException e)
	{
		throw new RuntimeException("加载GroupTemplate失败", e);
	}

}
 
Example #13
Source File: BeetlTest.java    From seed with Apache License 2.0 6 votes vote down vote up
@Test
public void buildFromString() throws IOException {
    GroupTemplate groupTemplate = new GroupTemplate(new StringTemplateResourceLoader(), Configuration.defaultConfiguration());
    //设置模板字符串
    Template template = groupTemplate.getTemplate("<!DOCTYPE HTML>\n" +
            "<html>\n" +
            "<head>\n" +
            "    <meta charset=\"UTF-8\">\n" +
            "    <title>beetl demo</title>\n" +
            "</head>\n" +
            "<body>\n" +
            "    长篇架空武侠小说:${book},真的忍心烂尾么??\n" +
            "</body>\n" +
            "</html>");
    //设置模板所需的共享变量
    Map<String, Object> sharedVars = new HashMap<>();
    sharedVars.put("book", "英雄志");
    template.binding(sharedVars);
    //template.binding("book", "野狗志");
    //解析模板字符串
    String data = template.render();
    System.out.println(data);
}
 
Example #14
Source File: GroupTemplateTest.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] args) throws Exception {

		String home = System.getProperty("user.dir") + File.separator
				+ "template" + File.separator;
		Configuration cf = Configuration.defaultConfiguration();
		cf.setStatementStart("<!--:");
		cf.setStatementEnd("-->");
		FileResourceLoader rs = new FileResourceLoader(home, cf.getCharset());
		GroupTemplate gt = new GroupTemplate(rs, cf);

		List<StockModel> list = StockModel.dummyItems();

		Template t = gt.getTemplate("/helloworld.html");
		t.binding("items", list);
		StringWriter sw = new StringWriter();
		t.renderTo(sw);
		System.out.println(sw.toString());

		// 第二次
		t = gt.getTemplate("/helloworld.html");
		t.binding("items", list);
		sw = new StringWriter();
		t.renderTo(sw);
		System.out.println(sw.toString());

	}
 
Example #15
Source File: SharedVars.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	
ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader();		
Configuration cfg = Configuration.defaultConfiguration();
GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
Map<String,Object> shared = new HashMap<String,Object>();
shared.put("name", "beetl");
gt.setSharedVars(shared);
Template t = gt.getTemplate("/org/beetl/sample/s0208/t1.txt");	
String str = t.render();
System.out.println(str);
t = gt.getTemplate("/org/beetl/sample/s0208/t2.txt");	
str = t.render();
System.out.println(str);


}
 
Example #16
Source File: BeetlTemplateUtil.java    From smart-doc with Apache License 2.0 6 votes vote down vote up
/**
 * Batch bind binding value to Beetl templates and return all file rendered,
 * Map key is file name,value is file content
 *
 * @param path   path
 * @param params params
 * @return map
 */
public static Map<String, String> getTemplatesRendered(String path, Map<String, Object> params) {
    Map<String, String> templateMap = new HashMap<>();
    File[] files = FileUtil.getResourceFolderFiles(path);
    GroupTemplate gt = getGroupTemplate(path);
    for (File f : files) {
        if (f.isFile()) {
            String fileName = f.getName();
            Template tp = gt.getTemplate(fileName);
            if (null != params) {
                tp.binding(params);
            }
            templateMap.put(fileName, tp.render());
        }
    }
    return templateMap;
}
 
Example #17
Source File: SingleDLTest.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public GroupTemplate getGt()
{
	ClasspathResourceLoader rs = new ClasspathResourceLoader("/template");
	Configuration cfg;
	try
	{
		cfg = Configuration.defaultConfiguration();
	}
	catch (IOException e)
	{
		throw new RuntimeException(e);
	}
	cfg.setStatementEnd(null);
	cfg.setStatementStart("@");
	GroupTemplate gt = new GroupTemplate(rs, cfg);
	return gt;
}
 
Example #18
Source File: ErrorGrammarProgram.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public ErrorGrammarProgram(Resource res, GroupTemplate gt, String cr)
{
	super();
	this.res = res;
	this.rs = res;
	this.gt = gt;
	this.metaData = new ProgramMetaData() {
		public void initContext(Context ctx)
		{
			//do nothing;
		}

		protected void putGlobaToArray(Context ctx)
		{
			//do nothing;
		}

		public AjaxStatement getAjax(String anchor)
		{
			//创建一个临时的ajax片段语句
			return new AjaxStatement(null, GrammarToken.createToken(anchor, 0),true) {
				public void execute(Context ctx)
				{
					ErrorGrammarProgram.this.execute(ctx);

				}
			};
		}
	};
	this.metaData.lineSeparator = cr;
}
 
Example #19
Source File: BaseSimulate.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public BaseSimulate(GroupTemplate gt,JsonUtil jsonUtil,String base){
	this.gt = gt;		
	this.base = base;
	this.jsonUtil = jsonUtil;
	if(jsonUtil!=null){
		gt.registerFunctionPackage("jsonUtil", jsonUtil);
		gt.registerFunction("jsonBody", new ReuqestBodyFunction(jsonUtil) );
	}
	
}
 
Example #20
Source File: CompositeResourceLoaderTest.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSimple() throws Exception
{

	Configuration conf = Configuration.defaultConfiguration();
	CompositeResourceLoader loader = new CompositeResourceLoader();
	String home = System.getProperty("user.dir");
	String path1 = home + "/src/test/resources/template/resourceloader/var1";
	String path2 = home + "/src/test/resources/template/resourceloader/var2";
	FileResourceLoader fileLoader1 = new FileResourceLoader(path1);
	FileResourceLoader fileLoader2 = new FileResourceLoader(path2);
	Map data = getData();
	// 根据id加载
	MapResourceLoader mapLoader = new MapResourceLoader(data);

	loader.addResourceLoader(new StartsWithMatcher("http:").withoutPrefix(), fileLoader2);
	loader.addResourceLoader(new StartsWithMatcher("db:").withoutPrefix(), mapLoader);
	loader.addResourceLoader(new AllowAllMatcher(), fileLoader1);

	GroupTemplate gt = new GroupTemplate(loader, conf);

	Template t = gt.getTemplate("/xxx.html");
	t.binding("a", "hello");
	String result = t.render();
	;
	AssertJUnit.assertEquals("hellohello--file2:hello--db=hello", result);

}
 
Example #21
Source File: NativeTest.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSecurity() throws Exception
{

	StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader();
	Configuration cfg = Configuration.defaultConfiguration();
	GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
	Template t = gt.getTemplate("hello,${@java.lang.System.currentTimeMillis()}");

	String str = t.render();
	AssertJUnit.assertEquals("hello,", str);

}
 
Example #22
Source File: SingleDLTest.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSimple() throws Exception
{

	GroupTemplate newGt = getGt();
	Template t = newGt.getTemplate("/text/single_template.html");
	String str = t.render();
	AssertJUnit.assertEquals(this.getFileContent("/text/single_expected.html"), str);

}
 
Example #23
Source File: PairDLTest.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSimple() throws Exception
{

	GroupTemplate newGt = getGt();
	Template t = newGt.getTemplate("/text/simple_pair_template.html");
	String str = t.render();
	AssertJUnit.assertEquals(this.getFileContent("/text/simple_pair_expected.html"), str);

}
 
Example #24
Source File: BeetlViewMaker.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void init() throws IOException {
    log.debug("beetl init ....");
    Configuration cfg = Configuration.defaultConfiguration();
    Properties prop = new Properties();
    InputStream ins = Configuration.class.getResourceAsStream("/beetl.properties");
    if (ins != null) {
        log.debug("found beetl.properties, loading ...");
        try {
            prop.load(ins);
        }
        finally {
            Streams.safeClose(ins);
        }
    }
    if (!prop.containsKey(Configuration.RESOURCE_LOADER)) {
        // 默认选用WebAppResourceLoader,除非用户自定义了RESOURCE_LOADER
        log.debug("no custom RESOURCE_LOADER found , select WebAppResourceLoader");
        cfg.setResourceLoader(WebAppResourceLoader.class.getName());
    }
    if (!prop.containsKey(Configuration.DIRECT_BYTE_OUTPUT)) {
        // 默认启用DIRECT_BYTE_OUTPUT,除非用户自定义, 一般不会.
        log.debug("no custom DIRECT_BYTE_OUTPUT found , set to true");
        // 当DIRECT_BYTE_OUTPUT为真时, beetl渲染会通过getOutputStream获取输出流
        // 而BeetlView会使用LazyResponseWrapper代理getOutputStream方法
        // 从而实现在模板输出之前,避免真正调用getOutputStream
        // 这样@Fail视图就能正常工作了
        cfg.setDirectByteOutput(true);
    }
    if (!prop.containsKey(Configuration.ERROR_HANDLER)) {
        // 没有自定义ERROR_HANDLER,用定制的
        cfg.setErrorHandlerClass(LogErrorHandler.class.getName());
    }
    groupTemplate = new GroupTemplate(cfg);
    render = new WebRender(groupTemplate);
    log.debug("beetl init complete");
}
 
Example #25
Source File: AttributeCodeGen.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static AttributeAccess createAAClass(Class c, String name, String methodName, Class returnType,GroupTemplate gt)
{
	try
	{
		BCW bcw = BCWFactory.defaultFactory.getAttribyteBCW(c, name, methodName, returnType);
		byte[] bs = bcw.getClassByte();
		String clsName = c.getName() + "_" + name;
		return instance(bs, clsName,gt);
	}
	catch (Exception ex)
	{
		throw new RuntimeException(ex);
	}

}
 
Example #26
Source File: CompositeResourceLoader.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void init(GroupTemplate gt)
{
	//逐个初始化
	for (ResourceLoader rl : this.matcherResourceLoaderMap.values())
	{
		rl.init(gt);
	}
	Map<String, String> resourceMap = gt.getConf().getResourceMap();
	this.autoCheck = Boolean.parseBoolean(resourceMap.get("autoCheck"));
}
 
Example #27
Source File: MetaCopyTest.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

		String home = System.getProperty("user.dir") + File.separator
				+ "template" + File.separator;
		Configuration cf = Configuration.defaultConfiguration();
		FileResourceLoader rs = new FileResourceLoader(home, cf.getCharset());
		GroupTemplate gt = new GroupTemplate(rs, cf);
		Template t = gt.getTemplate("/helloworld.html");
		Program p = gt.getProgram("/helloworld.html");
		ProgramMetaData old = p.metaData;
		ProgramMetaData copy = old.copy();
		System.out.println("ok");
	}
 
Example #28
Source File: ErrorTest.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	
	ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader();		
	Configuration cfg = Configuration.defaultConfiguration();
	GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
	Template t = gt.getTemplate("/org/beetl/sample/s0125/error1.txt");	
	String str = t.render();
	
	t = gt.getTemplate("/org/beetl/sample/s0125/error2.txt");	
	str = t.render();
	System.out.println(str);

}
 
Example #29
Source File: ClasspathRL.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	
	ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader();		
	URL url = resourceLoader.getClass().getResource("/org/beetl/sample/s01/hello.txt");
	Configuration cfg = Configuration.defaultConfiguration();
	GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
	Template t = gt.getTemplate("/org/beetl/sample/s01/hello.txt");	
	String str = t.render();
	System.out.println(str);

}
 
Example #30
Source File: SQLBeetlRender.java    From weed3 with Apache License 2.0 5 votes vote down vote up
private void initForRuntime() {
    try {
        ClasspathResourceLoader loader = new ClasspathResourceLoader(this.getClass().getClassLoader(), _baseUri);
        gt = new GroupTemplate(loader, cfg);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}