@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; } }
/** * @see freemarker.template.TemplateMethodModel#exec(java.util.List) */ public Object exec(List args) throws TemplateModelException { Object result = null; if (args.size() == 1) { Object arg0 = args.get(0); if (arg0 instanceof TemplateDateModel) { result = ISO8601DateFormat.format(((TemplateDateModel)arg0).getAsDate()); } else if (arg0 instanceof TemplateScalarModel) { result = ISO8601DateFormat.parse(((TemplateScalarModel)arg0).getAsString()); } } return result != null ? result : ""; }
@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); } } }; }
/** * @see freemarker.template.TemplateMethodModel#exec(java.util.List) */ public Object exec(List args) throws TemplateModelException { String result = ""; if (args.size() != 0) { String s = ""; Object arg0 = args.get(0); if (arg0 instanceof TemplateScalarModel) { s = ((TemplateScalarModel)arg0).getAsString(); } if (s != null) { result = URLDecoder.decode(s); } } return result; }
/** * 执行方法 * * @param argList * 参加列表 * @return 格式化后的字符串 * @throws TemplateModelException * 模版异常 */ @Override public Object exec(@SuppressWarnings("rawtypes") List argList) throws TemplateModelException { // 限定方法中必须且只能传递一个参数 if (argList.size() != 1) { throw new TemplateModelException("Wrong arguments!"); } // String u[] = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"}; String[] u = { "〇", "一", "二", "三", "四", "五", "六", "七", "八", "九" }; char[] str = String.valueOf(argList.get(0)).toCharArray(); String rstr = ""; for (int i = 0; i < str.length; i++) { rstr = rstr + u[Integer.parseInt(str[i] + "")]; } return rstr; }
@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); }
@Override public String getAsString() throws TemplateModelException { DateRenderer d = dateRendererFactory.createDateRenderer(date); SectionWriter context = getSectionWriter(); d.preRender(context); try { StringWriter s = new StringWriter(); SectionWriter n = new SectionWriter(s, context); d.realRender(n); return s.toString(); } catch( IOException e ) { throw new TemplateModelException(e); } }
@Override public Object exec(List arguments) throws TemplateModelException { // You can use it as a function to prevent the time-ago ness return new TemplateDateModel() { @Override public Date getAsDate() throws TemplateModelException { return date; } @Override public int getDateType() { return TemplateDateModel.DATETIME; } }; }
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); } }
@Override public Object exec(@SuppressWarnings("rawtypes") List args) throws TemplateModelException { JSCallable function = (JSCallable) jsObject; RenderContext context = getSectionWriter(); context.preRender(function); Object[] exprArgs = new Object[args.size()]; int i = 0; for( Object obj : args ) { if( obj instanceof AdapterTemplateModel ) { Object adapted = ((AdapterTemplateModel) obj).getAdaptedObject(Object.class); exprArgs[i] = adapted; } else { exprArgs[i] = new ScriptExpression(obj.toString()); } i++; } return function.getExpressionForCall(context, JSUtils.convertExpressions(exprArgs)); }
public SectionWriter getSectionWriter() { try { return (SectionWriter) ((AdapterTemplateModel) Environment.getCurrentEnvironment().getGlobalVariable( "_info")) //$NON-NLS-1$ .getAdaptedObject(SectionWriter.class); } catch( TemplateModelException e ) { throw new SectionsRuntimeException(e); } }
@SuppressWarnings("rawtypes") @Override public Object exec(List arguments) throws TemplateModelException { String str = String.valueOf(arguments.get(0)); String type = String.valueOf(arguments.get(1)); try { if (type == null || "0".equals(type)) { return URLEncoder.encode(str, "utf-8"); } else { return URLDecoder.decode(str, "utf-8"); } } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } }
@SuppressWarnings("rawtypes") @Override public Object exec(List arguments) throws TemplateModelException { if (arguments.size() != 1) { throw new TemplateModelException("Wrong number of arguments. Must be 1."); } String userPartOfStep = ""; Step step = getStepFromFreemarker(arguments.get(0)); if (hasUser(step)) { String userActorName = getUserActor(step).getName(); String wordsOfUserEventClassName = getLowerCaseWordsOfClassName(step.getUserEventClass()); userPartOfStep = userActorName + " " + wordsOfUserEventClassName + USER_POSTFIX; } return new SimpleScalar(userPartOfStep); }
@Singleton @Provides public static Configuration configuration(LinkHelper linkHelper, MultiTemplateLoader templateLoader) { try { freemarker.log.Logger.selectLoggerLibrary(Logger.LIBRARY_SLF4J); Configuration cfg = new freemarker.template.Configuration(Configuration.VERSION_2_3_25); cfg.setTagSyntax(freemarker.template.Configuration.SQUARE_BRACKET_TAG_SYNTAX); cfg.setLazyAutoImports(true); cfg.setLocale(Locale.GERMANY); // todo make configurable cfg.addAutoImport("saito", "saito.ftl"); cfg.setSharedVariable("saitoLinkHelper", linkHelper); cfg.setDefaultEncoding("UTF-8"); cfg.setLogTemplateExceptions(false); cfg.setTemplateLoader(templateLoader); return cfg; } catch (TemplateModelException | ClassNotFoundException e) { log.error("Error creating config", e); throw new IllegalStateException(e); } }
/** * Converts map to a simple wrapper, if applicable, by rewrapping * known complex map wrappers that implement <code>WrapperTemplateModel</code>. * <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 toSimpleMapRewrapAdapters(TemplateModel object, ObjectWrapper objectWrapper) throws TemplateModelException { if (object instanceof SimpleMapModel || object instanceof BeanModel || object instanceof DefaultMapAdapter) { // 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"); } }
/** * Gets string arg. * <p> * If number or date passed, will be coerced to string. Other types such as maps or lists * will throw TemplateModelException. */ public static String getStringArg(TemplateModel obj, String defaultValue, boolean useDefaultWhenEmpty, boolean nonEscaping) throws TemplateModelException { String result = null; if (obj instanceof TemplateScalarModel) { TemplateScalarModel s = (TemplateScalarModel) obj; result = LangFtlUtil.getAsString(s, nonEscaping); } else if (obj == null) { return defaultValue; } else if (obj instanceof TemplateNumberModel || obj instanceof TemplateDateModel) { // TODO: optimize this call result = LangFtlUtil.execStringBuiltIn(obj, FreeMarkerWorker.getCurrentEnvironment()).getAsString(); } else { throw new TemplateModelException("Expected string model or something coercible to string, but got a " + obj.getClass() + " instead"); } if (useDefaultWhenEmpty && result.isEmpty()) { return defaultValue; } return result; }
@Override public Object execute(HttpServletRequest request, Object... args) throws TemplateModelException { Date datetime = (Date) args[0]; long time = datetime.getTime() / 1000; long current = System.currentTimeMillis() / 1000; long second = current - time; long minute = second / 60; if (minute <= 0) { return "刚刚"; } if (minute < 60) { return minute + "分钟前"; } long hour = minute / 60; if (hour < 24) { return hour + "小时前"; } return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(datetime); }
@Override public Object execute(HttpServletRequest request, Object... args) throws TemplateModelException { double time = (Double) args[0]; if (time <= 0) { return "-"; } String str; if (time < 0.01) { str = new DecimalFormat("0.000").format(time); } else if (time < 0.1) { str = new DecimalFormat("0.00").format(time); } else if (time < 1) { str = new DecimalFormat("0.0").format(time); } else if (time < 10) { str = new DecimalFormat("0.0").format(time); } else { str = new DecimalFormat("0").format(time); } return str + "ms"; }
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()); } } }
@SuppressWarnings("unchecked") @Override public Object exec(List args) throws TemplateModelException { if (args == null || args.size() != 2) throw new TemplateModelException("Invalid number of arguements"); if (!(args.get(0) instanceof TemplateScalarModel)) throw new TemplateModelException("First argument not an instance of TemplateScalarModel (string)"); if (!(args.get(1) instanceof TemplateScalarModel)) throw new TemplateModelException("Second argument not an instance of TemplateScalarModel (string)"); String resource = LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) args.get(0))); String name = LangFtlUtil.getAsStringNonEscaping(((TemplateScalarModel) args.get(1))); String res = UtilProperties.getPropertyValue(resource, name); // here we do opposite of UtilProperties and return null if empty, so ! operator can work if (res != null && res.isEmpty()) { res = null; } // Prevent escaping by EscapingObjectWrapper - values from properties are always coded // by trusted people return LangFtlUtil.wrapNonEscaping(res); }
@Override public String formatToPlainText(TemplateNumberModel numberModel) throws UnformattableValueException, TemplateModelException { Number n = TemplateFormatUtil.getNonNullNumber(numberModel); try { String number = Integer.toHexString(NumberUtil.toIntExact(n)); if(number.length() == 1) if(NumberUtil.toIntExact(n) <= 9) number = "0"+number; else number = number + number; return number; } catch (ArithmeticException e) { throw new UnformattableValueException(n + " doesn't fit into an int"); } }
private static Object getStackAsList(Map<String, Object> varMap, String name, TemplateValueTargetType copyTargetType, ObjectWrapper objectWrapper, String desc) throws TemplateModelException { List<Object> stack = null; Object stackObj = varMap.get(name); if (stackObj instanceof List) { stack = UtilGenerics.checkList(stackObj); } if (stack != null) { if (copyTargetType == null) { return Collections.unmodifiableList(stack); } else { return LangFtlUtil.copyList(stack, copyTargetType, objectWrapper); } } else { return null; } }
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()); }
@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; }
@Override public Object exec(final List arguments) throws TemplateModelException { if (arguments.size() != ARG_SIZE) { logger.debug("FillTagArticles with wrong arguments!"); throw new TemplateModelException("Wrong arguments!"); } final String tagTitle = (String) arguments.get(0); final int currentPageNum = Integer.parseInt((String) arguments.get(1)); final int pageSize = Integer.parseInt((String) arguments.get(2)); try { final JSONObject result = tagQueryService.getTagByTitle(tagTitle); if (null == result) { return new ArrayList<JSONObject>(); } final JSONObject tag = result.getJSONObject(Tag.TAG); final String tagId = tag.getString(Keys.OBJECT_ID); final List<JSONObject> ret = articleQueryService.getArticlesByTag(tagId, currentPageNum, pageSize); return ret; } catch (final Exception e) { logger.error("Fill tag articles failed", e); } return null; }
/** * 添加共享变量 * * @param params * 变量 */ public static void addSharedVariable(Map<String, Object> params) { if (params != null) { for (Entry<String, Object> entry : params.entrySet()) { try { configuration.setSharedVariable(entry.getKey(), entry.getValue()); } catch (TemplateModelException e) { e.printStackTrace(); } } } }
/** * @see freemarker.template.TemplateMethodModel#exec(java.util.List) */ public Object exec(List args) throws TemplateModelException { String result = null; if (args.size() == 2) { Object arg0 = args.get(0); Object arg1 = args.get(1); if (arg0 instanceof BeanModel && arg1 instanceof TemplateNumberModel) { Object wrapped = ((BeanModel)arg0).getWrappedObject(); if (wrapped instanceof TemplateContentData) { int bytes = ((TemplateNumberModel)arg1).getAsNumber().intValue(); try { result = ((TemplateContentData)wrapped).getContentAsText(bytes); } catch (ContentIOException e) { logger.warn("unable to getContentAsText", e); /* * Unable to extract content - return empty text instead. * Probably here through a transformation failure. * This method is called from FreeMarker so throwing the * exception causes problems. */ result = ""; } } } } return result != null ? result : ""; }
/** * @see freemarker.template.TemplateMethodModel#exec(java.util.List) */ public Object exec(List args) throws TemplateModelException { int result = 0; if (args.size() == 2) { // arg 0 must be a wrapped TemplateNode object BeanModel arg0 = (BeanModel)args.get(0); // arg 1 can be either wrapped QName object or a String String arg1String = null; Object arg1 = args.get(1); if (arg1 instanceof BeanModel) { arg1String = ((BeanModel)arg1).getWrappedObject().toString(); } else if (arg1 instanceof TemplateScalarModel) { arg1String = ((TemplateScalarModel)arg1).getAsString(); } if (arg0.getWrappedObject() instanceof TemplateNode) { // test to see if this node has the aspect if ( ((TemplateNode)arg0.getWrappedObject()).hasAspect(arg1String) ) { result = 1; } } } return Integer.valueOf(result); }
/** * @see freemarker.template.TemplateMethodModel#exec(java.util.List) */ public Object exec(List args) throws TemplateModelException { int result = 0; if (args.size() == 2) { // arg 0 must be a wrapped TemplateNode object BeanModel arg0 = (BeanModel)args.get(0); // arg 1 must be a String permission name String permission; Object arg1 = args.get(1); if (arg1 instanceof TemplateScalarModel) { permission = ((TemplateScalarModel)arg1).getAsString(); if (arg0.getWrappedObject() instanceof TemplateNode) { // test to see if this node has the permission if ( ((TemplateNode)arg0.getWrappedObject()).hasPermission(permission) ) { result = 1; } } } } return Integer.valueOf(result); }
/** * @see freemarker.template.TemplateMethodModel#exec(java.util.List) */ public Object exec(List args) throws TemplateModelException { String result = null; if (args.size() == 1) { // arg 0 can be either wrapped QName object or a String String arg0String = null; Object arg0 = args.get(0); if (arg0 instanceof BeanModel) { arg0String = ((BeanModel)arg0).getWrappedObject().toString(); } else if (arg0 instanceof TemplateScalarModel) { arg0String = ((TemplateScalarModel)arg0).getAsString(); } try { result = createQName(arg0String).toPrefixString(services.getNamespaceService()); } catch (NamespaceException e) { // not valid qname -> return original value result = arg0String; } } return result != null ? result : ""; }
/** * 执行方法 * * @param argList * 方法参数列表 * @return Object 方法返回值 * @throws TemplateModelException * 模版错误 */ @SuppressWarnings("rawtypes") public Object exec(List argList) throws TemplateModelException { // 限定方法中必须且只能传递一个参数 if (argList.size() != 1) { throw new TemplateModelException("Wrong arguments!"); } // 返回response.encodeURL执行结果 return response.encodeURL((String) argList.get(0)); }
/** * 执行方法 * * @param argList * 方法参数列表 * @return Object 方法返回值 * @throws TemplateModelException * 模版错误 */ @SuppressWarnings("rawtypes") public Object exec(List argList) throws TemplateModelException { // 限定方法中必须且只能传递一个参数 if (argList.size() != 1) { throw new TemplateModelException("Wrong arguments!"); } // 返回getText执行结果 return getProperties().getProperty((String) argList.get(0)); }
@Override public Object exec(List arguments) throws TemplateModelException { if(arguments == null || arguments.size() < 1) throw new TemplateModelException("Syntax: route('Class.method', arg1, arg2…)"); Object arg0 = arguments.get(0); if(arg0 instanceof SimpleScalar != true) throw new TemplateModelException("Syntax: route('Class.method', arg1, arg2…)"); String arg1 = ((SimpleScalar)arg0).getAsString(); int dot = arg1.indexOf('.'); if(dot == -1) throw new TemplateModelException("Syntax: route('Class.method', arg1, arg2…)"); String klass = arg1.substring(0, dot); String method = arg1.substring(dot+1); for (Class resource : AppGlobals.get().getDeployment().getActualResourceClasses()) { dot = resource.getName().lastIndexOf('.'); String shortName = dot == -1 ? resource.getName() : resource.getName().substring(dot+1); if(shortName.equals(klass)) { for (Method m : resource.getMethods()) { // FIXME: overloading? if(m.getName().equals(method) && Modifier.isPublic(m.getModifiers())) { UriInfo uriInfo = ResteasyProviderFactory.getContextData(UriInfo.class); UriBuilder builder = uriInfo.getBaseUriBuilder().path(resource); if(m.isAnnotationPresent(Path.class)) builder.path(m); Object[] params = arguments.subList(1, arguments.size()).toArray(); return builder.build(params).toString(); } } throw new TemplateModelException("Could not find method named "+method+" in resource class "+resource.getName()); } } throw new TemplateModelException("Could not find resource class named "+klass); }
public Object exec(List list) throws TemplateModelException { if (list.size() < 1) { throw new TemplateModelException("Wrong arguments"); } TemplateScalarModel model = (TemplateScalarModel)list.get(0); if ((null == model) || (null == model.getAsString())) { return ""; } return camel(model.getAsString()); }
public Object exec(List arguments) throws TemplateModelException { if (arguments.size() < 1) { throw new TemplateModelException("Wrong arguments"); } //所有参数都要先转成SimpleSequence SimpleSequence arg0 = (SimpleSequence)arguments.get(0); //把参数转换为list List<String> list = arg0.toList(); TemplateScalarModel value = (TemplateScalarModel)arguments.get(1); return list.contains(value.getAsString()); }
/*** * 拿到静态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); }
private Object convertToJava(Object paramVal) throws TemplateModelException { if( paramVal instanceof TemplateNumberModel ) { return ((TemplateNumberModel) paramVal).getAsNumber(); } return paramVal.toString(); }
@Override @SuppressWarnings("unchecked") public Object exec(List list) throws TemplateModelException { RenderContext info = getSectionWriter(); Object section = list.get(0); String tag = list.get(1).toString(); if( section instanceof AdapterTemplateModel ) { Object wrapped = ((AdapterTemplateModel) section).getAdaptedObject(Object.class); if( wrapped instanceof HtmlComponentState ) { return new TagRenderer(tag, ((HtmlComponentState) wrapped)); } if( wrapped instanceof SectionId ) { SectionId sectionId = (SectionId) wrapped; AbstractRenderedComponent<HtmlComponentState> component = (AbstractRenderedComponent<HtmlComponentState>) info .getSectionForId(sectionId); component.setRendererType(info, "null"); //$NON-NLS-1$ ResultListCollector results = new ResultListCollector(false); try { info.processEvent(new RenderEvent(info, sectionId.getSectionId(), results)); } catch( Exception e ) { throw new RuntimeException(e); } HtmlComponentState state = component.getState(info); TagRenderer renderer = new TagRenderer(tag, state); state.fireRendererCallback(info, renderer); return renderer; } } throw new SectionsRuntimeException("Needs to be a HtmlComponentState or AbstractRenderedComponent"); //$NON-NLS-1$ }
@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; }