Java Code Examples for freemarker.core.Environment

The following are top voted examples for showing how to use freemarker.core.Environment. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Equella   File: ButtonListDirective.java   View source code 6 votes vote down vote up
@Override
@SuppressWarnings("nls")
protected TagRenderer createTagRenderer(HtmlMutableListState state, Environment env, Map<?, ?> params,
	TemplateDirectiveBody body, TemplateModel[] loopVars) throws TemplateModelException
{
	String tag = "div";
	if( params.containsKey("tag") )
	{
		tag = ((SimpleScalar) params.get("tag")).getAsString();
	}

	boolean hideDisabledOptions = false;
	if( params.containsKey("hideDisabledOptions") )
	{
		hideDisabledOptions = ((TemplateBooleanModel) params.get("hideDisabledOptions")).getAsBoolean();
	}

	return new ButtonListTagRenderer(tag, (HtmlListState) state, env, body, loopVars, hideDisabledOptions);
}
 
Example 2
Project: Equella   File: ButtonListDirective.java   View source code 6 votes vote down vote up
@SuppressWarnings("nls")
public ButtonListTagRenderer(String tag, HtmlListState state, Environment env, TemplateDirectiveBody body,
	TemplateModel[] loopVars, boolean hideDisabledOptions)
{
	super(tag, state); //$NON-NLS-1$
	this.wrapper = (BeansWrapper) env.getObjectWrapper();
	this.listState = state;
	this.body = body;
	this.loopVars = loopVars;
	this.hideDisabledOptions = hideDisabledOptions;

	this.hiddenId = new AppendedElementId(state, "_hid");
	ScriptVariable valVar = new ScriptVariable("val");
	JSStatements changeBody = new AssignStatement(new ElementValueExpression(hiddenId), valVar);

	JSHandler lsChangeHandler = state.getHandler(JSHandler.EVENT_CHANGE);
	if( lsChangeHandler != null )
	{
		changeBody = StatementBlock.get(changeBody, lsChangeHandler);
	}
	clickFunc = new SimpleFunction(JSHandler.EVENT_CHANGE, state, changeBody, valVar);
}
 
Example 3
Project: Equella   File: SectionsTemplateModel.java   View source code 6 votes vote down vote up
public SectionWriter getSectionWriter()
{
	try
	{
		AdapterTemplateModel model = (AdapterTemplateModel) Environment.getCurrentEnvironment().getGlobalVariable(
			"_info");
		if( model != null )
		{
			return (SectionWriter) model.getAdaptedObject(SectionWriter.class);
		}
		return null;
	}
	catch( TemplateModelException e )
	{
		throw new SectionsRuntimeException(e);
	}
}
 
Example 4
Project: Equella   File: SectionsBeansWrapper.java   View source code 6 votes vote down vote up
public SectionWriter getSectionWriter()
{
	try
	{
		return (SectionWriter) ((AdapterTemplateModel) Environment.getCurrentEnvironment().getGlobalVariable(
			"_info")) //$NON-NLS-1$
			.getAdaptedObject(SectionWriter.class);
	}
	catch( TemplateModelException e )
	{
		throw new SectionsRuntimeException(e);
	}
}
 
Example 5
Project: incubator-freemarker-online-tester   File: FreeMarkerServiceTest.java   View source code 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 6
Project: my-paper   File: ProductCategoryParentListDirective.java   View source code 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
	Long productCategoryId = FreemarkerUtils.getParameter(PRODUCT_CATEGORY_ID_PARAMETER_NAME, Long.class, params);

	ProductCategory productCategory = productCategoryService.find(productCategoryId);

	List<ProductCategory> productCategories;
	if (productCategoryId != null && productCategory == null) {
		productCategories = new ArrayList<ProductCategory>();
	} else {
		boolean useCache = useCache(env, params);
		String cacheRegion = getCacheRegion(env, params);
		Integer count = getCount(params);
		if (useCache) {
			productCategories = productCategoryService.findParents(productCategory, count, cacheRegion);
		} else {
			productCategories = productCategoryService.findParents(productCategory, count);
		}
	}
	setLocalVariable(VARIABLE_NAME, productCategories, env, body);
}
 
Example 7
Project: geeCommerce-Java-Shop-Software-and-PIM   File: WaitDirective.java   View source code 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
    throws TemplateException, IOException {
    try {
        SimpleNumber pFor = (SimpleNumber) params.get("for");

        Number forMillis = null;

        if (pFor != null) {
            forMillis = pFor.getAsNumber();

            try {
                Thread.sleep(forMillis.longValue());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
}
 
Example 8
Project: scipio-erp   File: RequestStackMethod.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected Object execPush(List args, boolean setLast) throws TemplateModelException {
    if (args == null || args.size() != 2) {
        throw new TemplateModelException("Invalid number of arguments (expected: 2)");
    }
    TemplateModel nameModel = (TemplateModel) args.get(0);
    if (!(nameModel instanceof TemplateScalarModel)) {
        throw new TemplateModelException("First argument not an instance of TemplateScalarModel (string)");
    }
    TemplateModel valueModel = (TemplateModel) args.get(1);

    Environment env = CommonFtlUtil.getCurrentEnvironment();
    ContextFtlUtil.pushRequestStack(LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) nameModel)), valueModel, setLast, env);
    
    return new SimpleScalar("");
}
 
Example 9
Project: scipio-erp   File: CmsRenderUtil.java   View source code 6 votes vote down vote up
/**
 * Special helper for directives to check what the render mode is going to be when exception is caught.
 * This can be used for alternate output.
 * WARN: this must be maintained carefully so it matches behavior of our modified OFBizTemplateExceptionHandler
 * and methods above.
 */
public static RenderExceptionMode getDirectiveRenderExceptionMode(Environment env, RenderExceptionMode liveExMode) {
    MapStack<String> context = null;
    CmsPageContext pageContext = null;
    try {
        context = CmsRenderUtil.getRenderContextAlways(env);
        pageContext = CmsRenderUtil.getPageContextAlways(context);
    } catch(Throwable t) {
        Debug.logError(t, "Cms: isDirectiveCaughtRenderExceptionMode: internal error: could not fetch all page context info from environment", module);
    }
    boolean isPreview = false;
    if (pageContext != null) {
        isPreview = pageContext.isPreview();
    }
    if (!isPreview && liveExMode != null) return liveExMode;
    return UtilRender.getRenderExceptionMode(pageContext != null ? pageContext.getRequest() : null);
}
 
Example 10
Project: scipio-erp   File: WrappingOptions.java   View source code 6 votes vote down vote up
public static WrappingOptions makeOptions(String wrapper, String mode, Environment env) throws TemplateModelException {
    ObjectWrapper targetWrapper = ObjectWrapperUtil.getObjectWrapperByName(wrapper, env);
    if (targetWrapper == null) {
        throw new TemplateModelException("Unrecognized wrapper name: " + wrapper);
    }
    if (wrapper == null) {
        wrapper = "";
    }
    
    RewrapMode rewrapMode = RewrapMode.ALWAYS_DEEP;
    if (mode != null && !mode.isEmpty()) {
        rewrapMode = RewrapMode.fromString(mode);
        if (rewrapMode == null) {
            throw new TemplateModelException("Unrecognized rewrapping mode: " + mode);
        }
    }
    
    return new WrappingOptions(wrapper, ObjectWrapperUtil.getObjectWrapperByName(wrapper, env), 
            rewrapMode, env.getObjectWrapper());
}
 
Example 11
Project: scipio-erp   File: ContextFtlUtil.java   View source code 6 votes vote down vote up
static Integer getRequestStackSize(String name, HttpServletRequest request, 
        Map<String, Object> context, Environment env) throws TemplateModelException {
    if (request != null) {
        return getStackSize(getRequestVarMapFromReqAttribs(request), name);
    }
    else {
        Map<String, Object> globalContext = getGlobalContext(context, env);
        if (globalContext != null) {  
            return getStackSize(getRequestVarMapFromGlobalContext(globalContext), name);
        }
        else if (env != null) {
            return getStackSize(getRequestVarMapFromFtlGlobals(env), name);
        }
        else {
            return null;
        }
    }
}
 
Example 12
Project: my-paper   File: ProductCategoryChildrenListDirective.java   View source code 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
	Long productCategoryId = FreemarkerUtils.getParameter(PRODUCT_CATEGORY_ID_PARAMETER_NAME, Long.class, params);

	ProductCategory productCategory = productCategoryService.find(productCategoryId);

	List<ProductCategory> productCategories;
	if (productCategoryId != null && productCategory == null) {
		productCategories = new ArrayList<ProductCategory>();
	} else {
		boolean useCache = useCache(env, params);
		String cacheRegion = getCacheRegion(env, params);
		Integer count = getCount(params);
		if (useCache) {
			productCategories = productCategoryService.findChildren(productCategory, count, cacheRegion);
		} else {
			productCategories = productCategoryService.findChildren(productCategory, count);
		}
	}
	setLocalVariable(VARIABLE_NAME, productCategories, env, body);
}
 
Example 13
Project: scipio-erp   File: FreeMarkerWorker.java   View source code 6 votes vote down vote up
/**
* Gets BeanModel from FreeMarker context and returns the object that it wraps.
* @param varName the name of the variable in the FreeMarker context.
* @param env the FreeMarker Environment
*/
public static <T> T getWrappedObject(String varName, Environment env) {
    Object obj = null;
    try {
        obj = env.getVariable(varName);
        if (obj != null) {
            if (obj == TemplateModel.NOTHING) {
                obj = null;
            } else if (obj instanceof BeanModel) {
                BeanModel bean = (BeanModel) obj;
                obj = bean.getWrappedObject();
            } else if (obj instanceof SimpleScalar) {
                obj = obj.toString();
            }
        }
    } catch (TemplateModelException e) {
        Debug.logInfo(e.getMessage(), module);
    }
    return UtilGenerics.<T>cast(obj);
}
 
Example 14
Project: scipio-erp   File: FreeMarkerWorker.java   View source code 6 votes vote down vote up
public static Map<String, Object> createEnvironmentMap(Environment env) {
    Map<String, Object> templateRoot = new HashMap<String, Object>();
    Set<String> varNames = null;
    try {
        varNames = UtilGenerics.checkSet(env.getKnownVariableNames());
    } catch (TemplateModelException e1) {
        Debug.logError(e1, "Error getting FreeMarker variable names, will not put pass current context on to sub-content", module);
    }
    if (varNames != null) {
        for (String varName: varNames) {
            //freemarker.ext.beans.StringModel varObj = (freemarker.ext.beans.StringModel) varNameIter.next();
            //Object varObj =  varNameIter.next();
            //String varName = varObj.toString();
            templateRoot.put(varName, FreeMarkerWorker.getWrappedObject(varName, env));
        }
    }
    return templateRoot;
}
 
Example 15
Project: geeCommerce-Java-Shop-Software-and-PIM   File: FreemarkerExceptionHandler.java   View source code 6 votes vote down vote up
/**
 * Only prints errors when the configuration-property
 * 'core/dev/print_errors' is set to true.
 */
public void handleTemplateException(TemplateException te, Environment env, Writer out) throws TemplateException {
    try {
        // Make sure that the error message is not swallowed somewhere
        // unnoticed
        // in dev-mode. This way it is clearly visible in the console.
        if (false /* app.isDevPrintErrorMessages() */) {
            // Print stack trace if we are in debug mode.
            te.printStackTrace();
            // Print message to template if we are in debug mode.
            out.write("[ERROR: " + te.getMessage() + "]");
        }
    } catch (IOException e) {
        e.printStackTrace();
        // throw new TemplateException("Failed to print error message.
        // Cause: " + e, env);
    }
}
 
Example 16
Project: leopard   File: MenuTemplateDirective.java   View source code 6 votes vote down vote up
@Override
public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
	HttpServletRequest request = RequestHolder.getRequest();

	String uri = request.getRequestURI();
	StringBuilder sb = new StringBuilder();

	Iterator<Menu> iterator = loader.iterator();
	// System.out.println("iterator:" + iterator + " url:" + request.getRequestURI());
	while (iterator.hasNext()) {
		Menu menu = iterator.next();
		boolean active = uri.equals(menu.getUrl());
		sb.append("<li");
		if (active) {
			sb.append(" class=\"active\"");
		}
		sb.append("><a href=\"");
		sb.append(menu.getUrl());
		sb.append("\"><span class=\"isw-grid\"></span><span class=\"text\">");
		sb.append(menu.getName());
		sb.append("</span></a></li>");
	}
	env.getOut().write(sb.toString());
}
 
Example 17
Project: scipio-erp   File: MultiVarMethod.java   View source code 6 votes vote down vote up
public static void setVars(CommonVarMaps<Map<String, Object>> maps, CommonVarMaps<Boolean> skipSet, Environment env) throws TemplateModelException {
    if (maps.ctxVars != null && !maps.ctxVars.isEmpty() && !skipSet.ctxVars) {
        Map<String, Object> context = ContextFtlUtil.getContext(env);
        context.putAll(maps.ctxVars);
    }
    
    if (maps.globalCtxVars != null && !maps.globalCtxVars.isEmpty() && !skipSet.globalCtxVars) {
        Map<String, Object> globalContext = ContextFtlUtil.getGlobalContext(env);
        globalContext.putAll(maps.globalCtxVars);
    }
    
    if (maps.reqAttribs != null && !maps.reqAttribs.isEmpty() && !skipSet.reqAttribs) {
        HttpServletRequest request = ContextFtlUtil.getRequest(env);
        for(Map.Entry<String, Object> entry : maps.reqAttribs.entrySet()) {
            request.setAttribute(entry.getKey(), entry.getValue());
        }
    }
}
 
Example 18
Project: tc   File: GuestTag.java   View source code 6 votes vote down vote up
@Override
public void render(Environment env, 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 19
Project: ants-project   File: TestTag.java   View source code 6 votes vote down vote up
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
    System.out.println("################# Start env ##"+env);
    System.out.println("################# Start params ##" + JSON.toJSON(params)+"- "+(SimpleNumber)params.get("length")+"- "+(SimpleScalar)params.get("text"));
    System.out.println("################# Start loopVars ##"+JSON.toJSON(loopVars));
    System.out.println("################# Start body ##" + body.toString());
    System.out.println("@@@:" + env.getOut().toString());
    List list = testService.getList(null);
    System.out.println("#######:"+list);

    //  System.out.println("################# Start body ##"+body.render(new UpperCaseFilterWriter(env.getOut()));
    // 指令内容体不为空
    if (body != null) {
        // Executes the nested body. Same as <#nested> in FTL, except
        // that we use our own writer instead of the current output writer.
        body.render(env.getOut());
    } else {
        throw new RuntimeException("missing body");
    }
}
 
Example 20
Project: scipio-erp   File: ContextFtlUtil.java   View source code 6 votes vote down vote up
/**
 * Wipes all request vars and sets a new holder map.
 * <p>
 * Attempts to set the same map for as many contexts present as possible, for compatibility.
 * <p>
 * <em>NOTE:</em> in some cases this call is not necessary, but it's a good idea anyway
 * because it will set the same map for request and context (but not ftl - FIXME?),
 * which might prevent problems in odd rendering cases.
 * This should be called at beginning of rendering at a point where as many of the parameters 
 * are non-null as possible (but env will probably usually be null).
 */
public static void resetRequestVars(HttpServletRequest request, 
        Map<String, Object> context, Environment env) throws TemplateModelException {
    RequestVarMapWrapper mapWrapper = new RequestVarMapWrapper();
    if (request != null) {
        request.setAttribute(ContextFtlUtil.REQUEST_VAR_MAP_NAME_REQATTRIBS, mapWrapper);
    }
    Map<String, Object> globalContext = getGlobalContext(context, env);
    if (globalContext != null) {
        globalContext.put(ContextFtlUtil.REQUEST_VAR_MAP_NAME_GLOBALCONTEXT, mapWrapper);
    }
    if (env != null) {
        // Here we "hide" our variables in freemarker globals
        env.setGlobalVariable(ContextFtlUtil.REQUEST_VAR_MAP_NAME_FTLGLOBALS, new RequestVarMapWrapperModel(mapWrapper.getRawMap()));
    }
}
 
Example 21
Project: scipio-erp   File: ContextFtlUtil.java   View source code 6 votes vote down vote up
/**
 * Method for getting request-scope variables, with fallback to globals.
 * <p>
 * Must and should only be used to read values set by {@link setRequestVar}.
 * <p>
 * Return value may or may not be a <code>TemplateModel</code>; caller must wrap or unwrap as needed.
 * Can use {@link com.ilscipio.scipio.ce.webapp.ftl.TransformFtlUtil} <code>unwrapXxx</code> methods.
 * 
 * @see setRequestVar
 */
static Object getRequestVar(String name, HttpServletRequest request, 
        Map<String, Object> context, Environment env) throws TemplateModelException {
    Object res = null;

    if (request != null) {
        res = getRequestVarMapFromReqAttribs(request).get(name);
        //Debug.logInfo("getRequestVar: request attrib (name: " + name + ")", module);
    }
    else {
        Map<String, Object> globalContext = getGlobalContext(context, env);
        if (globalContext != null) {    
            res = getRequestVarMapFromGlobalContext(globalContext).get(name);
            //Debug.logInfo("getRequestVar: globalContext var (name: " + name + ")", module);
        }
        else if (env != null) {
            res = getRequestVarMapFromFtlGlobals(env).get(name);
            //Debug.logInfo("getRequestVar: ftl global var (name: " + name + ")", module);
        }
        else {
            throw new IllegalArgumentException("No request, context or ftl environment to get request scope var (name: " + name + ")");
        }
    }
    
    return res;
}
 
Example 22
Project: my-paper   File: PromotionListDirective.java   View source code 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
	Boolean hasBegun = FreemarkerUtils.getParameter(HAS_BEGUN_PARAMETER_NAME, Boolean.class, params);
	Boolean hasEnded = FreemarkerUtils.getParameter(HAS_ENDED_PARAMETER_NAME, Boolean.class, params);

	List<Promotion> promotions;
	boolean useCache = useCache(env, params);
	String cacheRegion = getCacheRegion(env, params);
	Integer count = getCount(params);
	List<Filter> filters = getFilters(params, Promotion.class);
	List<Order> orders = getOrders(params);
	if (useCache) {
		promotions = promotionService.findList(hasBegun, hasEnded, count, filters, orders, cacheRegion);
	} else {
		promotions = promotionService.findList(hasBegun, hasEnded, count, filters, orders);
	}
	setLocalVariable(VARIABLE_NAME, promotions, env, body);
}
 
Example 23
Project: scipio-erp   File: TemplateSource.java   View source code 6 votes vote down vote up
/**
 * Tries to get appropriate location-based UtilCache in use for templates being rendered.
 * <p>
 * FIXME: WARNING: massive limitations here, we do not have access to all the Configuration instances
 * we'd need to test to implement this, and a host of problems...
 * as a result I am creating a new two-layer cache system that first keys on the Configuration instances.
 */
public static UtilCache<String, Template> getTemplateLocationCacheForConfig(Configuration config, Environment env) throws TemplateModelException {
    Map<Configuration, UtilCache<String, Template>> configTmplLocCaches = TemplateSource.configTmplLocCaches;
    
    UtilCache<String, Template> cache = configTmplLocCaches.get(config);
    if (cache == null) {
        // double-locking idiom, with configTmplLocCaches as unmodifiable
        synchronized(TemplateSource.class) {
            configTmplLocCaches = TemplateSource.configTmplLocCaches;
            cache = configTmplLocCaches.get(config);
            if (cache == null) {
                Map<Configuration, UtilCache<String, Template>> newConfigCacheMap = new HashMap<>(configTmplLocCaches);
                cache = UtilCache.createUtilCache("templatesource.ftl.location." + (configTmplLocCaches.size() + 1), 
                            0, configTmplCacheExpireTime, false);
                newConfigCacheMap.put(config, cache);
                
                TemplateSource.configTmplLocCaches = newConfigCacheMap;
            }
        }
    }
    return cache;
}
 
Example 24
Project: incubator-netbeans   File: RsrcLoader.java   View source code 5 votes vote down vote up
public void handleTemplateException(TemplateException ex, Environment env, Writer w) throws TemplateException {
    try {
        w.append(ex.getLocalizedMessage());
        LOG.log(Level.INFO, "Failure processing " + fo, ex);
        LOG.log(Level.INFO, "Bindings:"); // NOI18N
        for (Map.Entry<String, Object> entry : engineScope.entrySet()) {
            LOG.log(Level.INFO, "  key: " + entry.getKey() + " value: " + entry.getValue()); // NOI18N
        }
    } catch (IOException e) {
        Exceptions.printStackTrace(e);
    }
}
 
Example 25
Project: incubator-netbeans   File: ProcessorTest.java   View source code 5 votes vote down vote up
@Override
public void handleTemplateException(TemplateException te, Environment e, Writer writer) throws TemplateException {
    if (exceptions == null) {
        exceptions = new ArrayList<TemplateException>();
    }
    exceptions.add(te);
    try {
        writer.append(te.getLocalizedMessage());
    } catch (IOException ioex) {
        Exceptions.printStackTrace(ioex);
    }
}
 
Example 26
Project: pyblog   File: BlogsDirective.java   View source code 5 votes vote down vote up
@Override
public void execute(Environment environment, Map map, TemplateModel[] templateModels,
                    TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
  DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_26);

  environment.setVariable("blogs", builder.build().wrap(fileUtil.getBlogs()));

  templateDirectiveBody.render(environment.getOut());
}
 
Example 27
Project: Equella   File: ListRendererDirective.java   View source code 5 votes vote down vote up
public FreemarkerListRenderer(HtmlMutableListState state, Environment env, TemplateDirectiveBody body,
	TemplateModel[] loopVars)
{
	super("ul", state); //$NON-NLS-1$
	this.wrapper = (BeansWrapper) env.getObjectWrapper();
	this.listState = state;
	this.body = body;
	this.loopVars = loopVars;
}
 
Example 28
Project: Equella   File: BooleanListDirective.java   View source code 5 votes vote down vote up
public FreemarkerCheckListRenderer(BooleanListRenderer renderer, Environment env, TemplateDirectiveBody body,
	TemplateModel[] loopVars)
{
	super("ul", renderer.getListState()); //$NON-NLS-1$
	this.wrapper = (BeansWrapper) env.getObjectWrapper();
	this.body = body;
	this.loopVars = loopVars;
	this.renderer = renderer;
}
 
Example 29
Project: Equella   File: AbstractFreemarkerFactory.java   View source code 5 votes vote down vote up
public Environment render(FreemarkerSectionResult result, Writer writer)
{
	Thread currentThread = Thread.currentThread();
	ClassLoader origLoader = currentThread.getContextClassLoader();
	Template template = result.getTemplate();
	Map<String, Object> rootObjects = new HashMap<String, Object>();
	addRootObjects(rootObjects, result, writer);
	Map<String, Object> extraObjects = result.getExtraObjects();
	if( extraObjects != null )
	{
		rootObjects.putAll(extraObjects);
	}
	currentThread.setContextClassLoader(getContextClassLoader());
	try
	{
		Environment environment = template.createProcessingEnvironment(rootObjects, writer);
		setupEnvironment(writer, result, environment);
		environment.process();
		finishedRender(writer, result, environment);
		return environment;
	}
	catch( Throwable te )
	{
		LOGGER.error("Error rendering " + result.getTemplate().getName());
		throw Throwables.propagate(te);
	}
	finally
	{
		currentThread.setContextClassLoader(origLoader);
	}
}
 
Example 30
Project: Equella   File: AbstractRenderDirective.java   View source code 5 votes vote down vote up
@Nullable
private static synchronized Object getBodyField(Environment env) throws Exception
{
	Object context = currentContextMethod.invoke(env);
	if( bodyField == null )
	{
		bodyField = context.getClass().getDeclaredField("nestedContent");
		bodyField.setAccessible(true);
	}
	return bodyField.get(context);
}
 
Example 31
Project: Equella   File: FreemarkerTemplateResult.java   View source code 5 votes vote down vote up
public Environment getEnvironment(RenderContext info)
{
	if( environment == null )
	{
		this.environment = factory.render(freemarkerResult, new SectionWriter(new DevNullWriter(), info));
	}
	return environment;
}
 
Example 32
Project: Equella   File: FreemarkerTemplateResult.java   View source code 5 votes vote down vote up
private TemplateModel getTemplateVariable(RenderContext context)
{
	Environment environment = template.getEnvironment(context);
	try
	{
		return environment.getVariable("TEMP_" + name); //$NON-NLS-1$
	}
	catch( TemplateModelException e )
	{
		throw new SectionsRuntimeException(e);
	}

}
 
Example 33
Project: hippo   File: RestrictableDateFormatterDirective.java   View source code 5 votes vote down vote up
private void assertRequiredParameterPresent(final Map parameters, final Environment environment)
    throws TemplateException {

    if (!parameters.containsKey(DATE_PARAM_NAME)) {
        throw new TemplateException(format("Required parameter ''{0}'' was not provided to template {1}.",
            DATE_PARAM_NAME, getClass().getName()), environment);
    }
}
 
Example 34
Project: hippo   File: TruncateFormatterDirective.java   View source code 5 votes vote down vote up
@Override
public void execute(final Environment environment, final Map parameters, final TemplateModel[] loopVariables,
                    final TemplateDirectiveBody body) throws TemplateException, IOException {

    assertRequiredParameterPresent(parameters, environment, MAX_SIZE_PARAM_NAME);
    assertRequiredParameterPresent(parameters, environment, INPUT_PARAM_NAME);

    final int size = getValueAsInt(parameters, MAX_SIZE_PARAM_NAME);
    final String text = getValueAsString(parameters, INPUT_PARAM_NAME);
    final String result = truncate(text, size);

    environment.getOut().append(result);
}
 
Example 35
Project: hippo   File: FileSizeFormatterDirective.java   View source code 5 votes vote down vote up
private void assertRequiredParameterPresent(final Map parameters, final Environment environment)
    throws TemplateException {

    if (!parameters.containsKey(BYTES_COUNT_PARAM_NAME)) {
        throw new TemplateException(format("Required parameter ''{0}'' was not provided to template {1}.",
            BYTES_COUNT_PARAM_NAME, getClass().getName()), environment);
    }
}
 
Example 36
Project: hippo   File: CoverageDatesFormatterDirective.java   View source code 5 votes vote down vote up
@Override
public void execute(Environment environment, Map parameters, TemplateModel[] templateModels,
                    TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {

    assertRequiredParameterPresent(parameters, environment, START_PARAM_NAME);
    assertRequiredParameterPresent(parameters, environment, END_PARAM_NAME);

    final Date start = getValueAsDate(parameters, START_PARAM_NAME);
    final Date end = getValueAsDate(parameters, END_PARAM_NAME);
    final String result = formatCoverageDates(start, end);

    environment.getOut().append(result);
}
 
Example 37
Project: hippo   File: FileSizeFormatterDirectiveTest.java   View source code 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    template = mock(Template.class);
    writer = mock(Writer.class);
    environment = new Environment(template, null, writer);

    parameters = new HashMap(1);
    final int arbitraryByteCount = 10; // some value is required by most of the test cases
    parameters.put(BYTES_COUNT_PARAM_NAME, new SimpleNumber(arbitraryByteCount));

    loopVariables = new TemplateModel[0];
    body = null;

    fileSizeFormatterDirective = new FileSizeFormatterDirective();
}
 
Example 38
Project: incubator-freemarker-online-tester   File: FreeMarkerService.java   View source code 5 votes vote down vote up
private FreeMarkerService(Builder bulder) {
     maxOutputLength = bulder.getMaxOutputLength();
     maxThreads = bulder.getMaxThreads();
     maxQueueLength = bulder.getMaxQueueLength();
     maxTemplateExecutionTime = bulder.getMaxTemplateExecutionTime();

     int actualMaxQueueLength = maxQueueLength != null
             ? maxQueueLength
             : Math.max(
                     MIN_DEFAULT_MAX_QUEUE_LENGTH,
                     (int) (MAX_DEFAULT_MAX_QUEUE_LENGTH_MILLISECONDS / maxTemplateExecutionTime));
     ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
             maxThreads, maxThreads,
             THREAD_KEEP_ALIVE_TIME, TimeUnit.MILLISECONDS,
             new BlockingArrayQueue<Runnable>(actualMaxQueueLength));
     threadPoolExecutor.allowCoreThreadTimeOut(true);
     templateExecutor = threadPoolExecutor;

     freeMarkerConfig = new Configuration(Configuration.getVersion());
     freeMarkerConfig.setNewBuiltinClassResolver(TemplateClassResolver.ALLOWS_NOTHING_RESOLVER);
     freeMarkerConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
     freeMarkerConfig.setLogTemplateExceptions(false);
     freeMarkerConfig.setAttemptExceptionReporter(new AttemptExceptionReporter() {
@Override
public void report(TemplateException te, Environment env) {
	// Suppress it
}
     });
     freeMarkerConfig.setLocale(AllowedSettingValuesMaps.DEFAULT_LOCALE);
     freeMarkerConfig.setTimeZone(AllowedSettingValuesMaps.DEFAULT_TIME_ZONE);
     freeMarkerConfig.setOutputFormat(AllowedSettingValuesMaps.DEFAULT_OUTPUT_FORMAT);
     freeMarkerConfig.setOutputEncoding("UTF-8");
 }
 
Example 39
Project: scipio-erp   File: MacroScreenRenderer.java   View source code 5 votes vote down vote up
private Environment getEnvironment(Appendable writer) throws TemplateException, IOException {
    Environment environment = environments.get(writer);
    if (environment == null) {
        // SCIPIO: custom render context
        Map<String, Object> input = contextHandler.createRenderContext(writer, null, UtilMisc.toMap("key", null));
        environment = FreeMarkerWorker.renderTemplate(macroLibrary, input, writer);
        environments.put(writer, environment);
    }
    return environment;
}
 
Example 40
Project: scipio-erp   File: CmsRenderUtil.java   View source code 5 votes vote down vote up
@Override
protected void handleTemplateExceptionDebug(TemplateException te, Environment env, Writer out) throws TemplateException {
    CmsTemplateException cte = CmsTemplateException.getFromExceptionOrCauseDeep(te);
    if (cte != null) {
        handleTemplateExceptionDebugCms(cte, te, env, out);
    } else {
        super.handleTemplateExceptionDebug(te, env, out);
    }
}