@Override public TemplateModel getSharedVariable(String string) { Object value = map.getAttribute(string); if (value == null) { value = engineScope.get(string); } if (value == null && fo != null) { value = fo.getAttribute(string); } try { return getObjectWrapper().wrap(value); } catch (TemplateModelException ex) { Exceptions.printStackTrace(ex); return null; } }
@Override protected ObjectWrapper initialValue() { return new DefaultObjectWrapper() { /* (non-Javadoc) * @see freemarker.template.DefaultObjectWrapper#wrap(java.lang.Object) */ @Override public TemplateModel wrap(Object obj) throws TemplateModelException { if (obj instanceof QNameMap) { return new QNameHash((QNameMap)obj, this); } else { return super.wrap(obj); } } }; }
@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); }
@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); }
@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"); }
@Override public TemplateModel get(String s) throws TemplateModelException { Object value = null; if ("topic".equals(s)) { value = this.connectRecord.topic(); } else if ("partition".equals(s)) { value = this.connectRecord.kafkaPartition(); } else if (null != (this.struct.schema().field(s))) { value = this.struct.get(s); } if (null == value) { return TemplateModel.NOTHING; } return wrap(value); }
@SuppressWarnings({ "unchecked", "rawtypes" }) public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { AdPosition adPosition; Long id = getId(params); boolean useCache = useCache(env, params); String cacheRegion = getCacheRegion(env, params); if (useCache) { adPosition = adPositionService.find(id, cacheRegion); } else { adPosition = adPositionService.find(id); } if (body != null) { setLocalVariable(VARIABLE_NAME, adPosition, env, body); } else { if (adPosition != null && adPosition.getTemplate() != null) { try { Map<String, Object> model = new HashMap<String, Object>(); model.put(VARIABLE_NAME, adPosition); Writer out = env.getOut(); new Template("adTemplate", new StringReader(adPosition.getTemplate()), freeMarkerConfigurer.getConfiguration()).process(model, out); } catch (Exception e) { e.printStackTrace(); } } } }
public static boolean getBoolParam(final Environment env,Map params,String key,boolean def) throws TemplateException { final TemplateModel tv = (TemplateModel)params.get(key); if(tv == null) { return def; } if(tv instanceof TemplateBooleanModel) { return ((TemplateBooleanModel)tv).getAsBoolean(); //throw new TemplateException( // String.format("Expected a boolean model. '%s' is instead %s", key,tv.getClass().getName()) // , env); } return Convert.parseBool(tv.toString()); }
public static void overrideWithArgs(Map<String, Object> ctx, Map<String, Object> args) { for (Map.Entry<String, Object> entry: args.entrySet()) { String key = entry.getKey(); Object obj = entry.getValue(); //if (Debug.infoOn()) Debug.logInfo("in overrideWithArgs, key(3):" + key + " obj:" + obj + " class:" + obj.getClass().getName() , module); if (obj != null) { if (obj == TemplateModel.NOTHING) { ctx.put(key, null); } else { Object unwrappedObj = unwrap(obj); if (unwrappedObj == null) { unwrappedObj = obj; } ctx.put(key, unwrappedObj.toString()); } } else { ctx.put(key, null); } } }
/** * Gets boolean arg. * <p> * Will automatically interpret string true/false as boolean. */ public static Boolean getBooleanArg(TemplateModel obj, Boolean defaultValue) throws TemplateModelException { if (obj instanceof TemplateBooleanModel) { return ((TemplateBooleanModel) obj).getAsBoolean(); } else if (obj instanceof TemplateScalarModel) { TemplateScalarModel s = (TemplateScalarModel) obj; String val = s.getAsString(); // SCIPIO: empty check is desirable and makes it so caller can request default by specifying "" if (!val.isEmpty()) { return "true".equalsIgnoreCase(s.getAsString()); } } else if (obj != null) { throw new TemplateModelException("Expected boolean model or string model representation of boolean, but got a " + obj.getClass() + " instead"); } return defaultValue; }
@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(); } }
@SuppressWarnings("unchecked") @Override public <T> T getParam(String name, Class<?> type, Object defaultValue) { try { Object o = params.get(name); if (o != null) { if (o instanceof TemplateModel) { return (T) eval(BeansWrapper.getDefaultInstance().unwrap((TemplateModel) o), type, defaultValue); } else { return (T) eval(o, type, defaultValue); } } else { TemplateModel tm = hash().get(name); if (tm != null) { return (T) eval(BeansWrapper.getDefaultInstance().unwrap(tm), type, defaultValue); } } } catch (TemplateModelException e) { throw new RuntimeException(e); } return null; }
/** * Gets integer arg. * <p> * If string passed, will be parsed as integer. Other types such as maps or lists * will throw TemplateModelException. */ public static Integer getIntegerArg(TemplateModel obj, Integer defaultValue) throws TemplateModelException, NumberFormatException { if (obj instanceof TemplateNumberModel) { return ((TemplateNumberModel) obj).getAsNumber().intValue(); } else if (obj instanceof TemplateScalarModel) { TemplateScalarModel s = (TemplateScalarModel) obj; String strResult = LangFtlUtil.getAsString(s, true); if (strResult.isEmpty()) { return defaultValue; } else { return Integer.parseInt(strResult); } } else if (obj == null) { return defaultValue; } else { throw new TemplateModelException("Expected integer model or string representing of integer, but got a " + obj.getClass() + " instead"); } }
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { String name = Directives.getStringParam(env, params, "name"); name = BLOCK_NAME_PRE+name; Namespace ns = env.getCurrentNamespace(); if(ns.get(name) == null) /*block���ܶ�α���д�����ж�����ģ���е�����Ϊ����*/ { //java.io.Writer out = new java.io.StringWriter(); //body.render(out); env.getCurrentNamespace().put(name, body); //env.getCurrentNamespace().put(name, out.toString()); //env.setLocalVariable(name, out.toString()); } }
@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); }
@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); }
@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(""); }
@SuppressWarnings({ "unchecked", "rawtypes" }) public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { Long articleCategoryId = FreemarkerUtils.getParameter(ARTICLE_CATEGORY_ID_PARAMETER_NAME, Long.class, params); ArticleCategory articleCategory = articleCategoryService.find(articleCategoryId); List<ArticleCategory> articleCategories; if (articleCategoryId != null && articleCategory == null) { articleCategories = new ArrayList<ArticleCategory>(); } else { boolean useCache = useCache(env, params); String cacheRegion = getCacheRegion(env, params); Integer count = getCount(params); if (useCache) { articleCategories = articleCategoryService.findChildren(articleCategory, count, cacheRegion); } else { articleCategories = articleCategoryService.findChildren(articleCategory, count); } } setLocalVariable(VARIABLE_NAME, articleCategories, env, body); }
@SuppressWarnings("rawtypes") @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { SimpleScalar pVar = (SimpleScalar) params.get("var"); List<RetailStore> retailStoreList = retailStores.enabledRetailStores(); if (pVar != null) { // Sets the result into the current template as if using <#assign // name=model>. env.setVariable(pVar.getAsString(), DefaultObjectWrapper.getDefaultInstance().wrap(retailStoreList)); } else { // Sets the result into the current template as if using <#assign // name=model>. env.setVariable("retailStores", DefaultObjectWrapper.getDefaultInstance().wrap(retailStoreList)); } }
@SuppressWarnings("unchecked") @Override public Object exec(List args) throws TemplateModelException { if (args == null || args.size() < 0 || args.size() > 1) { throw new TemplateModelException("Invalid number of arguments (expected: 0-1)"); } Environment env = CommonFtlUtil.getCurrentEnvironment(); if (args.size() > 0) { TemplateModel object = (TemplateModel) args.get(0); ObjectWrapper objectWrapper = LangFtlUtil.getCurrentObjectWrapper(env); return LangFtlUtil.toSet(object, objectWrapper); } else { return new HashSet<Object>(); } }
public static int getIntParam(final Environment env,Map params,String key,int def) throws TemplateException { final TemplateModel tv = (TemplateModel)params.get(key); if(tv == null) { return def; } if(!(tv instanceof TemplateNumberModel)) { throw new TemplateException( String.format("Expected a number model. '%s' is instead %s", key,tv.getClass().getName()) , env); } return ((TemplateNumberModel)tv).getAsNumber().intValue(); }
/** * Converts map to a simple wrapper, if applicable, by rewrapping * any map wrappers that implement <code>WrapperTemplateModel</code>. * <p> * This method is very permissive: anything that wraps a Map is accepted. * Other types of hashes are returned as-is. * <p> * If the specified ObjectWrapper is a BeansWrapper, this forces rewrapping as a SimpleMapModel. * If it isn't we assume caller specified an objectWrapper that will rewrap the map with * a simple model (we have no way of knowing). * <p> * WARN: Bypasses auto-escaping for complex maps; caller must decide how to handle * (e.g. the object wrapper used to rewrap the result). * Other types of maps are not altered. * * @deprecated don't use */ @Deprecated private static TemplateHashModel toSimpleMapRewrapAny(TemplateModel object, ObjectWrapper objectWrapper) throws TemplateModelException { if (object instanceof WrapperTemplateModel) { // Permissive Map<?, ?> wrappedObject = (Map<?, ?>) ((WrapperTemplateModel) object).getWrappedObject(); if (objectWrapper instanceof BeansWrapper) { // Bypass the beanswrapper wrap method and always make simple wrapper return new SimpleMapModel(wrappedObject, (BeansWrapper) objectWrapper); } else { // If anything other than BeansWrapper, assume caller is aware and his wrapper will create a simple map return (TemplateHashModel) objectWrapper.wrap(wrappedObject); } } else if (object instanceof TemplateHashModel) { return (TemplateHashModel) object; } else { throw new TemplateModelException("object is not a recognized map type"); } }
@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); }
/*** * 拿到静态Class的Model * * @param config * Configuration * @param className * className * @return TemplateModel */ public static TemplateModel useClass(Configuration config, String className) { BeansWrapper wrapper = (BeansWrapper) config.getObjectWrapper(); TemplateHashModel staticModels = wrapper.getStaticModels(); try { return staticModels.get(className); } catch (TemplateModelException e) { e.printStackTrace(); } throw new RuntimeException(className); }
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; }
@SuppressWarnings("nls") private void setupStyles(TagRenderer renderer, Map<String, TemplateModel> params) { String id = getParam(params, "id"); String style = getParam(params, "style"); String styleClass = getParam(params, "class"); renderer.setStyles(style, styleClass, id); }
private String getParam(Map<String, TemplateModel> params, String key) { TemplateModel templateModel = params.get(key); if( templateModel != null ) { return templateModel.toString(); } return null; }
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; }
@Override public Object exec(@SuppressWarnings("rawtypes") List list) throws TemplateModelException { RenderContext info = getSectionWriter(); Object wrapped = DeepUnwrap.unwrap((TemplateModel) list.get(0)); String type = list.get(1).toString(); SectionRenderable renderable = getSectionRenderable(info, wrapped, type, factory); if( renderable == null ) { return TemplateModel.NOTHING; } return renderable; }
@Override public TemplateModel wrap(Object object) throws TemplateModelException { if( object instanceof JSExpression || object instanceof JSStatements || object instanceof JSCallable ) { return new JSTemplateModel(object); } if( object instanceof TemplateResult ) { return new TemplateResultModel((TemplateResult) object); } if( object instanceof Label ) { return new LabelTemplateModel((Label) object); } if( object instanceof SectionRenderable ) { return new RenderableModel((SectionRenderable) object); } if( object != null ) { SectionsTemplateModelProvider m = getModelMap().get(object.getClass().getName()); if( m != null ) { return m.getTemplateModel(object); } } return super.wrap(object); }
@Override public void realRender(SectionWriter writer) throws IOException { TemplateModel variable = getTemplateVariable(writer); if( variable != null ) { writer.write(variable.toString()); } }
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); } }
@Override public Object exec(List list) throws TemplateModelException { if( list.size() != 2 ) { throw new RuntimeException("Needs a key and a value"); //$NON-NLS-1$ } String key = (String) DeepUnwrap.unwrap((TemplateModel) list.get(0)); map.put(key, (TemplateModel) list.get(1)); return TemplateModel.NOTHING; }
protected TemplateModel createModel(ObjectWrapper objectWrapper, ServletContext servletContext, final HttpServletRequest request, final HttpServletResponse response) throws TemplateModelException { AllHttpScopesHashModel params = (AllHttpScopesHashModel) super.createModel(objectWrapper, servletContext, request, response); for (String key : FREEMARKER_EXT_METHODS.keySet()) { params.putUnlistedModel(key, FREEMARKER_EXT_METHODS.get(key)); } params.putUnlistedModel("urlEncode", URLENCODEMETHOD); params.putUnlistedModel("sleep", SLEEPMETHOD); return params; }
@SuppressWarnings("rawtypes") @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { App app = App.get(); app.servletResponse().setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP // 1.1. app.servletResponse().setHeader("Pragma", "no-cache"); // HTTP 1.0. app.servletResponse().setDateHeader("Expires", 0); }
@Override protected TemplateModel handleUnknownType(Object obj) throws TemplateModelException { if (obj instanceof ConnectObjectWrapper) { return (TemplateModel) obj; } return super.handleUnknownType(obj); }
@SuppressWarnings("unchecked") public static MapStack<String> getRenderContext(Environment env) throws TemplateModelException { TemplateModel pcm = env.getVariable("context"); if (pcm != null && pcm instanceof WrapperTemplateModel) { Object obj = ((WrapperTemplateModel) pcm).getWrappedObject(); if (obj instanceof MapStack) { return (MapStack<String>) obj; } } return null; }
/** * @see freemarker.template.TemplateDirectiveModel#execute(freemarker.core.Environment, * java.util.Map, freemarker.template.TemplateModel[], * freemarker.template.TemplateDirectiveBody) */ @SuppressWarnings("rawtypes") @Override public void execute(Environment env, Map argsUntyped, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { String output = makeLinkFromFtl(env, UtilGenerics.<String, TemplateModel>checkMap(argsUntyped), loopVars, body); Writer out = env.getOut(); if (output != null) out.write(output); }
@Override public TemplateModel wrap(Object object) throws TemplateModelException { if (object != null) { for(ScipioModelFactory factory : getCustomWrapperFactoriesInternal()) { TemplateModel model = factory.wrap(object, this); if (model != null) return model; } } return super.wrap(object); }
@SuppressWarnings("rawtypes") public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes(); if (requestAttributes != null) { Message message = (Message) requestAttributes.getAttribute(FLASH_MESSAGE_ATTRIBUTE_NAME, RequestAttributes.SCOPE_REQUEST); if (body != null) { setLocalVariable(VARIABLE_NAME, message, env, body); } else { if (message != null) { Writer out = env.getOut(); out.write("$.message(\"" + message.getType() + "\", \"" + message.getContent() + "\");"); } } } }