freemarker.template.TemplateDirectiveBody Java Examples

The following examples show how to use freemarker.template.TemplateDirectiveBody. 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: GuestTag.java    From SpringBoot-Base-System with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void render(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateDirectiveBody body) throws IOException, TemplateException {
    if (getSubject() == null || getSubject().getPrincipal() == null) {
        if (log.isDebugEnabled()) {
            log.debug("Subject does not exist or does not have a known identity (aka 'principal').  " +
                    "Tag body will be evaluated.");
        }

        renderBody(env, body);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Subject exists or has a known identity (aka 'principal').  " +
                    "Tag body will not be evaluated.");
        }
    }
}
 
Example #2
Source File: StrDirective.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
	String insertPrefix = getInsertPrefix(params);
	List<String> trimPrefixs = getTrimPrefixs(params);
	List<String> trimSuffixs = getTrimSuffixs(params);
	
	StringWriter writer = new StringWriter();
	body.render(writer);
	
	StringBuilder buffer = new StringBuilder(writer.toString().trim());
	if (StringUtils.isBlank(buffer)) {
		return ;
	}

	final String sql = buffer.toString().toLowerCase();
	
	trimPrefixs(buffer, sql, trimPrefixs);
	trimSuffixs(buffer, sql, trimSuffixs);
	
	buffer.insert(0, " ");
	buffer.insert(0, insertPrefix);
	env.getOut().append(buffer);
}
 
Example #3
Source File: DateTagDirective.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
		throws TemplateException, IOException {
	String dateValue = params.get("value").toString();
	String format = params.get("format").toString();
	String dateString="";
	if(dateValue==null) {
		if(format==null) {
			dateString=DateUtils.getCurrentDateAsString(DateUtils.FORMAT_DATE_YYYY_MM_DD);
		}else {
			dateString=DateUtils.getCurrentDateAsString(format);
		}
	}else {
		if(format==null) {
			dateString=DateUtils.format(DateUtils.tryParse(dateValue),DateUtils.FORMAT_DATE_YYYY_MM_DD);
		}else {
			dateString=DateUtils.format(DateUtils.tryParse(dateValue),format);
		}
	}
	
	env.getOut().append(dateString);
	
}
 
Example #4
Source File: AbstractDirective.java    From onetwo with Apache License 2.0 6 votes vote down vote up
protected String getBodyContent(TemplateDirectiveBody body){
		StringWriter sw = null;
		String bodyContent = "";
		try {
//			body.render(env.getOut());
			if(body!=null){
				sw = new StringWriter();
				body.render(sw);
				bodyContent = sw.toString();
			}
		} catch (Exception e) {
			LangUtils.throwBaseException("render error : " + e.getMessage(), e);
//			e.printStackTrace();
		} finally{
			LangUtils.closeIO(sw);
		}
		return bodyContent;
	}
 
Example #5
Source File: DialogTagDirective.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
		throws TemplateException, IOException {
	
	url=params.get("url").toString();
	title=params.get("title").toString();
	text=params.get("text").toString();
	if(params.get("width")!=null) {
		width=Integer.parseInt(params.get("width").toString());
	}
	if(params.get("height")!=null) {
		height=Integer.parseInt(params.get("height").toString());
	}
	
	env.getOut().append("<input  class=\"window button\" type=\"button\"  value=\""+text+"\"  title=\""+title+"\" ");
	env.getOut().append("wurl=\""+request.getContextPath()+url+"\" wwidth=\""+width+"\"  wheight=\""+height+"\" />" );
	
}
 
Example #6
Source File: PathVarTagDirective.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
		throws TemplateException, IOException {
	
	index=Integer.parseInt(params.get("index").toString());
	String[] pathVariables=request.getAttribute(org.springframework.web.util.WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE).toString().split("/");
	
	if(pathVariables==null){
		pathVariables=request.getRequestURI().split("/");
	}
	
	if(index==0){
		pathVariable=pathVariables[pathVariables.length-1];
	}else{
		pathVariable=pathVariables[index+1];
	}
		env.getOut().append(request.getParameter(pathVariable));
}
 
Example #7
Source File: BasePathTagDirective.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
		throws TemplateException, IOException {
	if(basePath==null) {
		basePath = request.getScheme()+"://"+request.getServerName();
		int port=request.getServerPort();
		if(port==443 && request.getScheme().equalsIgnoreCase("https")){
			
		}else if(port==80 && request.getScheme().equalsIgnoreCase("http")){
			
		}else{
			basePath	+=	":"+port;
		}
		basePath += request.getContextPath()+"";
	}
	env.getOut().append(basePath);
	

}
 
Example #8
Source File: RedirectTagDirective.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
		throws TemplateException, IOException {
		String location=params.get("url").toString();

		basePath = request.getScheme()+"://"+request.getServerName();
		int port=request.getServerPort();
		//Ignore 443 or 80 port
		if((port==443 && request.getScheme().equalsIgnoreCase("https"))
				||(port==80 && request.getScheme().equalsIgnoreCase("http"))){
		}else{
			basePath	+=	":"+port;
		}
		basePath += request.getContextPath()+"";
		
		response.sendRedirect(basePath+"/"+location);
}
 
Example #9
Source File: BaseTag.java    From OneBlog with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
    this.verifyParameters(map);
    String funName = getMethod(map);
    Method method = null;
    Class clazz = classBucket.get(clazzPath);
    try {
        if (clazz != null && (method = clazz.getDeclaredMethod(funName, Map.class)) != null) {
            // 核心处理,调用子类的具体方法,获取返回值
            Object res = method.invoke(this, map);
            environment.setVariable(funName, getModel(res));
        }
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
        log.error("无法获取[{}]的方法,或者调用[{}]方法发生异常", clazzPath, method, e);
    }
    templateDirectiveBody.render(environment.getOut());
}
 
Example #10
Source File: FreeMarkerServiceTest.java    From freemarker-online-tester with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void execute(Environment env, @SuppressWarnings("rawtypes") Map params,
        TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
    entered++;
    notifyAll();
    final long startTime = System.currentTimeMillis();
    while (!released) {
        // To avoid blocking the CI server forever is something goes wrong:
        if (System.currentTimeMillis() - startTime > BLOCKING_TEST_TIMEOUT) {
            LOG.error("JUnit test timed out");
        }
        try {
            wait(1000);
        } catch (InterruptedException e) {
            LOG.error("JUnit test was interrupted");
        }
    }
    LOG.debug("Blocker released");
}
 
Example #11
Source File: SiteTags.java    From cms with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
        throws TemplateException, IOException {
    if (params.get("id") == null) {
        return;
    }
    String alias = params.get("alias") == null ? null : params.get("alias").toString();
    String name = alias == null ? "site" : alias;
    String id = params.get("id").toString();
    Site site = SystemCacheManager.get(ConstantsUtils.SITE_ID_KEY + id, Site.class);
    if (site == null) {
        site = siteService.get(Long.parseLong(id));
    }
    env.setVariable(name, wrap(site));
    if (body != null) {
        body.render(env.getOut());
    }
    // env.getOut().write(site);
}
 
Example #12
Source File: SuperDirective.java    From metadata with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Environment env,
                    Map params, TemplateModel[] loopVars,
                    TemplateDirectiveBody body) throws TemplateException, IOException {

    TemplateDirectiveBodyOverrideWraper current = (TemplateDirectiveBodyOverrideWraper) env.getVariable(DirectiveUtils.OVERRIDE_CURRENT_NODE);
    if (current == null) {
        throw new TemplateException("<@super/> direction must be child of override", env);
    }
    TemplateDirectiveBody parent = current.parentBody;
    if (parent == null) {
        throw new TemplateException("not found parent for <@super/>", env);
    }
    parent.render(env.getOut());

}
 
Example #13
Source File: AmountDirective.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Environment env, @SuppressWarnings("rawtypes") Map args, TemplateModel[] loopVars, TemplateDirectiveBody body)
        throws TemplateException, IOException {
    Double amount = TransformUtil.getDoubleArg(args, "amount");
    if (amount == null) {
        throw new TemplateException("Missing or invalid amount", env);
    }
    Locale locale = TransformUtil.getOfbizLocaleArgOrCurrent(args, "locale", env);
    String format = TransformUtil.getStringNonEscapingArg(args, "format");

    if (Debug.verboseOn()) {
        Debug.logVerbose("Formatting amount: [amount=" + amount + ", format=" + format
                + ", locale=" + locale + "]", module);
    }
    String formattedAmount;
    try {
        if (AmountDirective.SPELLED_OUT_FORMAT.equals(format)) {
            formattedAmount = UtilFormatOut.formatSpelledOutAmount(amount.doubleValue(), locale);
        } else {
            formattedAmount = UtilFormatOut.formatAmount(amount, locale);
        }
    } catch (Exception e) {
        throw new TemplateException(e, env);
    }
    env.getOut().write(formattedAmount);
}
 
Example #14
Source File: LocaleTagDirective.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public void execute(Environment env, 
        Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
        throws TemplateException, IOException {
    WebApplicationContext webApplicationContext = 
            RequestContextUtils.findWebApplicationContext(request);
    String message = "";
    if (params.get("code") == null) {
        message = RequestContextUtils.getLocale(request).getLanguage();
    } else if (params.get("code").toString().equals("global.application.version")
            || params.get("code").toString().equals("application.version")) {
        message = WebContext.properties.getProperty("application.formatted-version");
    } else {
        _logger.trace("message code " + params.get("code"));
        try {
            message = webApplicationContext.getMessage(
                            params.get("code").toString(), 
                            null,
                            RequestContextUtils.getLocale(request));

        } catch (Exception e) {
            _logger.error("message code " + params.get("code"), e);
        }
    }
    env.getOut().append(message);
}
 
Example #15
Source File: FtlUtils.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static void render(String tag, Environment env, TemplateDirectiveBody body){
	if(body==null || env==null)
		return ;
	try {
		body.render(env.getOut());
	} catch (Exception e) {
		LangUtils.throwBaseException("render tempalte["+tag+"] error : "+e.getMessage(), e);
	} 
}
 
Example #16
Source File: ForeachDirective.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
	TemplateModel listModel = FtlUtils.getRequiredParameter(params, PARAMS_LIST);
	String joiner = FtlUtils.getParameterByString(params, PARAMS_JOINER, "");
	if(StringUtils.isBlank(joiner))
		joiner = FtlUtils.getParameterByString(params, PARAMS_SEPARATOR, "");//兼容当初定义错的写法
	
	Object datas = null;
	if(listModel instanceof BeanModel){
		datas = ((BeanModel) listModel).getWrappedObject();
	}else{
		throw new BaseException("error: " + listModel);
	}
	
	List<?> listDatas = LangUtils.asList(datas);
	int index = 0;
	for(Object data : listDatas){
		if(loopVars.length>=1)
			loopVars[0] = FtlUtils.wrapAsModel(data);
		if(loopVars.length>=2)
			loopVars[1] = FtlUtils.wrapAsModel(index);
		
		if(index!=0)
			env.getOut().write(joiner);
		
		body.render(env.getOut());
		index++;
	}
}
 
Example #17
Source File: PCStringDirective.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
	throws IOException, TemplateModelException
{
	// Check if no parameters were given:
	if (params.size() != 1 || params.get("tag") == null)
	{
		throw new TemplateModelException("This directive requires a single tag parameter.");
	}
	if (loopVars.length != 0)
	{
		throw new TemplateModelException("This directive doesn't allow loop variables.");
	}
	if (body != null)
	{
		throw new TemplateModelException("This directive cannot take a body.");
	}

	String tag = params.get("tag").toString();
	String value = getExportVariable(tag, pc, eh);

	if (tag.equals(value))
	{
		throw new TemplateModelException("Invalid export tag '" + tag + "'.");
	}

	env.getOut().append(value);
}
 
Example #18
Source File: BrowserTagDirective.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
		throws TemplateException, IOException {
	String browser = params.get("name").toString();
	String userAgent = request.getHeader("User-Agent");
	env.getOut().append("<!--<div style='display:none'>"+userAgent+"</div>-->");
	
	if(userAgent.indexOf(browser)>0){
		body.render(env.getOut());
	}
}
 
Example #19
Source File: DateRangeDirective.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
		TemplateModel from = FtlUtils.getRequiredParameter(params, PARAMS_FROM);
		TemplateModel to = FtlUtils.getRequiredParameter(params, PARAMS_TO);
		String joiner = FtlUtils.getParameterByString(params, PARAMS_JOINER, "");
		String type = FtlUtils.getParameterByString(params, PARAMS_TYPE, DateType.date.toString());
//		String format = FtlUtils.getParameterByString(params, PARAMS_FORMAT, DateUtil.Date_Only);
		boolean includeEnd = FtlUtils.getParameterByBoolean(params, PARAMS_INCLUDE_END, false);

		List<?> listDatas = null;
		DateType datetype = DateType.valueOf(type);
		String fromStr = from.toString();
		String toStr = to.toString();
		DateInterval interval = DateInterval.in(fromStr, toStr);
		listDatas = interval.getInterval(datetype, 1, includeEnd);
		
		int index = 0;
		for(Object data : listDatas){
			if(loopVars.length>=1)
				loopVars[0] = FtlUtils.wrapAsModel(data);
			if(loopVars.length>=2)
				loopVars[1] = FtlUtils.wrapAsModel(index);
			
			if(index!=0)
				env.getOut().write(joiner);
			
			body.render(env.getOut());
			index++;
		}
	}
 
Example #20
Source File: AdTags.java    From cms with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
    SimpleScalar positionCode = (SimpleScalar) params.getOrDefault("positionCode", "");
    List<Ad> ads = adService.getAdByPositionCode(positionCode.getAsString());

    env.setVariable("ads", wrap(ads));
    if (body != null) {
        body.render(env.getOut());
    }
}
 
Example #21
Source File: RequestTag.java    From cms with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] templateModels, TemplateDirectiveBody body) throws TemplateException, IOException {
    String alias = ((SimpleScalar) params.getOrDefault("alias", new SimpleScalar("currentURI"))).getAsString();
    String currentURI = request.getRequestURI();
    env.setVariable(alias, wrap(currentURI));
    if (body != null) {
        body.render(env.getOut());
    }
}
 
Example #22
Source File: OverrideDirective.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
	public void render(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
		String name = DirectivesUtils.getRequiredParameterByString(params, PARAMS_NAME);
//		DirectivesUtils.setVariable(env, "active", "test");
		OverrideBodyWraper preOverride = DirectivesUtils.getOverrideBody(env, name);
		OverrideBodyWraper curOverride = new OverrideBodyWraper(name, body);
		if(preOverride==null){
			DirectivesUtils.setOverrideBody(env, name, curOverride);
		}else{
			preOverride.parentBody = curOverride;
		}
	}
 
Example #23
Source File: ExtendsDirective.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
	String file = DirectivesUtils.getParameterByString(params, PARAMS_FILE, DEFAULT_LAYOUT);
	
	String template = env.toFullTemplateName("/", getActaulFile(params, file));
	if(!template.contains(".")){
		template += FTL;
	}
	body.render(env.getOut());
	env.include(template, DirectivesUtils.ENCODING, true);
}
 
Example #24
Source File: NavsTags.java    From cms with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
        throws TemplateException, IOException {
    if (params.get("id") == null)
        return;
    String id = params.get("id").toString();

    List<Navs> navs = SystemCacheManager.get(ConstantsUtils.TE_NAVS_KEY + id, List.class);

    if (navs == null) {
        Category model = new Category();
        model.setShowModes("1");
        model.setSiteId(Long.parseLong(id));
        List<Category> categorys = categoryService.getList(model);
        navs = getRootNodes(categorys);

        for (Navs nav : navs) {
            childNodes(categorys, nav);
        }
        SystemCacheManager.put(ConstantsUtils.TE_NAVS_KEY + id, navs);
    }

    env.setVariable("navs", wrap(navs));
    if (body != null) {
        body.render(env.getOut());
    }
}
 
Example #25
Source File: ArticleTags.java    From cms with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
        throws TemplateException, IOException {
    SimpleScalar id = (SimpleScalar) params.get("id");
    SimpleScalar categoryId = (SimpleScalar) params.get("categoryId");
    SimpleScalar type = (SimpleScalar) params.get("type");
    SimpleScalar showCountParms = (SimpleScalar) params.get("showCount");
    Integer showCount = showCountParms == null ? 10 : Integer.parseInt(showCountParms.toString());
    SimpleScalar nameParms = (SimpleScalar) params.get("alias");
    String name = nameParms == null ? "article" : nameParms.toString();

    List<Article> list = null;
    try {
        Long catId = null;
        Integer _type = null;
        if (categoryId != null) {
            catId = Long.parseLong(categoryId.toString());
        }
        if (type != null) {
            _type = Integer.parseInt(type.toString());
        }
        list = articleService.getArticleList(Long.parseLong(id.toString()), catId, _type, showCount);

    } catch (Exception e) {
    } finally {
        env.setVariable(name, wrap(list));
        if (body != null) {
            body.render(env.getOut());
        }
    }

}
 
Example #26
Source File: AdTags.java    From cms with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
    SimpleScalar id = (SimpleScalar) params.get("id");
    List<Ad> ads = adService.getAdByPositionId(Long.parseLong(id.toString()));

    env.setVariable("ads", wrap(ads));
    if (body != null) {
        body.render(env.getOut());
    }
}
 
Example #27
Source File: VirtualSectionDirective.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
protected void executeTyped(Environment env, Map<String, TemplateModel> params, TemplateModel[] loopVars, TemplateDirectiveBody body)
        throws TemplateException, IOException {
    Writer writer = env.getOut();

    // NOTE: this can only work if we already had a RenderWriter.
    // if not, don't even bother trying.
    if (writer instanceof RenderWriter) {
        Map<String, Object> context = ContextFtlUtil.getContext(env);
        WidgetRenderTargetState renderTargetState = WidgetRenderTargetExpr.getRenderTargetState(context);
        if (renderTargetState.isEnabled()) {
            String name = TransformUtil.getStringNonEscapingArg(params, "name");
            String containsExpr = TransformUtil.getStringNonEscapingArg(params, "contains");
            String location = "unknown-location"; // FIXME
            ModelFtlWidget widget = new ModelVirtualSectionFtlWidget(name, location, containsExpr);

            WidgetRenderTargetState.ExecutionInfo execInfo = renderTargetState.handleShouldExecute(widget, writer, context, null);
            if (!execInfo.shouldExecute()) {
                return;
            }
            try {
                if (body != null) {
                    body.render((Writer) execInfo.getWriterForElementRender());
                }
            } finally {
                execInfo.handleFinished(context); // SCIPIO: return logic
            }
            return;
        }
    }

    body.render(writer);
}
 
Example #28
Source File: CustomLayoutDirective.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env,
                    Map params,
                    TemplateModel[] loopVars,
                    TemplateDirectiveBody body)
        throws TemplateException, IOException {

    TemplateModel dataModel = env.getDataModel().get("this");
    if (!(dataModel instanceof ContentNodeHashModel)) {
        throw new TemplateModelException(
                "Data model is not a ContentNodeHashModel");
    }
    ContentNode node = ((ContentNodeHashModel) dataModel).getContentNode();
    if (node == null) {
        throw new TemplateModelException("'this' has a null content-node");
    }

    Object page = node.getDocument().getAttribute("page");
    if (page == null || !(page instanceof Page)) {
        throw new TemplateModelException("Unable to get page instance");
    }

    if (body == null) {
        throw new TemplateModelException("Body is null");
    }
    StringWriter writer = new StringWriter();
    body.render(writer);
    mappings.put(((Page) page).getSourcePath(), writer.toString());
}
 
Example #29
Source File: NoopDirective.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
        throws TemplateException, IOException {
    if (Debug.verboseOn()) {
        Debug.logVerbose("Freemarker: unimplemented directive invoked in template", module);
    }
}
 
Example #30
Source File: OverrideDirective.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public OverrideBodyWraper(String name, TemplateDirectiveBody body) {
			super();
			this.name = name;
			this.body = body;
//			this.env = env;
			this.render = false;
		}