/** * Gets a deep-unwrapped map. * FIXME: nonEscaping bool is currently not handled... it may bypass escaping in some cases but not others... */ public static <K,V> Map<K, V> getMapArg(TemplateModel obj, Map<K, V> defaultValue, boolean useDefaultWhenEmpty, boolean nonEscaping) throws TemplateModelException { if (!nonEscaping) { throw new UnsupportedOperationException("getMapArg currently only supports escaping-bypassing (nonEscaping true)"); } Map<K, V> result = null; if (obj instanceof TemplateHashModel) { result = UtilGenerics.checkMap(LangFtlUtil.unwrapAlways(obj)); } else if (obj == null) { return defaultValue; } else { throw new TemplateModelException("Expected hash/map model or something coercible to map, but got a " + obj.getClass() + " instead"); } if (useDefaultWhenEmpty && result.isEmpty()) { return defaultValue; } return result; }
/** * Copies map. * <p> * WARN: For complex maps, auto-escaping is bypassed; caller must decide how to handle. * (e.g. the object wrapper used to rewrap the result). * <p> * FIXME: The rewrapping objectWrapper behavior is inconsistent! may lead to auto-escape issues */ public static Object copyMap(TemplateModel object, Set<String> inExKeys, Boolean include, TemplateValueTargetType targetType, ObjectWrapper objectWrapper) throws TemplateModelException { if (targetType == null) { targetType = TemplateValueTargetType.PRESERVE; } if (OfbizFtlObjectType.COMPLEXMAP.isObjectType(object)) { // WARN: bypasses auto-escaping Map<String, Object> wrappedObject = UtilGenerics.cast(((WrapperTemplateModel) object).getWrappedObject()); // TODO: this only handles most urgent targetType case if (targetType == TemplateValueTargetType.SIMPLEMODEL) { return LangFtlUtil.copyMapToSimple(wrappedObject, inExKeys, include, objectWrapper); } else { return LangFtlUtil.copyMapToRawMap(wrappedObject, inExKeys, include); } } else if (object instanceof TemplateHashModel && OfbizFtlObjectType.MAP.isObjectType(object)) { // TODO: this ignores targetType return LangFtlUtil.copyMapToSimple((TemplateHashModel) object, inExKeys, include, objectWrapper); } throw new TemplateModelException("Cannot copy map of type " + object.getClass().toString() + " to target type: " + targetType.toString()); }
/** * Converts map to a simple wrapper, if applicable. Currently only applies to complex maps. * <p> * 2017-01-26: This has been changed so that it will by default try to wrap everything * with DefaultMapAdapter (or SimpleMapModel for BeansWrapper compatibility), which will always work as long as * the ObjectWrapper implements ObjectWrapperWithAPISupport. * <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. */ public static TemplateHashModel toSimpleMap(TemplateModel object, Boolean copy, ObjectWrapper objectWrapper) throws TemplateModelException { if (OfbizFtlObjectType.COMPLEXMAP.isObjectType(object)) { // WARN: bypasses auto-escaping Map<?, ?> wrappedObject = UtilGenerics.cast(((WrapperTemplateModel) object).getWrappedObject()); if (Boolean.TRUE.equals(copy)) { return makeSimpleMapCopy(wrappedObject, objectWrapper); } else { return makeSimpleMapAdapter(wrappedObject, objectWrapper, true); } } else if (object instanceof TemplateHashModel) { return (TemplateHashModel) object; } else { throw new TemplateModelException("object is not a recognized map type"); } }
/** * 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"); } }
/** * 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"); } }
/** * FreeMarker (ftl) configuration */ @Bean public FreeMarkerConfigurer freemarkerConfig() throws IOException, TemplateException { final FreeMarkerConfigurer result = new FreeMarkerConfigurer(); // template path result.setTemplateLoaderPath("/WEB-INF/ftl/"); result.setDefaultEncoding("UTF-8"); // static access final Version version = freemarker.template.Configuration.getVersion(); final BeansWrapper wrapper = new BeansWrapper(version); final TemplateHashModel statics = wrapper.getStaticModels(); final Map<String, Object> shared = new HashMap<>(); for (final Class<?> clazz : ElFunctions.staticClasses) { shared.put(clazz.getSimpleName(), statics.get(clazz.getName())); } result.setFreemarkerVariables(shared); return result; }
public Map<String, Object> getRoot(HttpServletRequest request) throws ServletException { Map<String, Object> root = new HashMap<String, Object>(); root.put("basePath", this.getBasePath()); try { BeansWrapper beansWrapper = new BeansWrapperBuilder(Configuration.VERSION_2_3_21).build(); TemplateHashModel staticModels = beansWrapper.getStaticModels(); TemplateHashModel stringUtils = (TemplateHashModel) staticModels.get(StringUtils.class.getCanonicalName()); TemplateHashModel planInvocationHelper = (TemplateHashModel) staticModels.get(PlanInvocationHelper.class .getCanonicalName()); root.put("StringUtils", stringUtils); root.put("PlanInvocationHelper", planInvocationHelper); } catch (TemplateModelException e) { throw new ServletException(e); } root.put(ERRORS, request.getSession().getAttribute(ERRORS)); root.put(SUCCESSES, request.getSession().getAttribute(SUCCESSES)); request.getSession().setAttribute(ERRORS, new ArrayList<String>()); request.getSession().setAttribute(SUCCESSES, new ArrayList<String>()); return root; }
/** * Sets up the static and common template objects including static methods * of math and constant classes. These are placed into a map for use by * the templates. * * @param map The map to be populated by this method * @throws freemarker.template.TemplateException If there is an error creating the objects */ protected void addStatics(Map<String, Object> map) throws TemplateException { BeansWrapper wrapper = BeansWrapper.getDefaultInstance(); TemplateHashModel staticModels = wrapper.getStaticModels(); TemplateHashModel constantStatics = (TemplateHashModel) staticModels.get("com.alvermont.terraj.stargen.Constants"); map.put("constants", constantStatics); TemplateHashModel mathStatics = (TemplateHashModel) staticModels.get("java.lang.Math"); map.put("math", mathStatics); TemplateHashModel uiStatics = (TemplateHashModel) staticModels.get("com.alvermont.terraj.stargen.ui.UIUtils"); map.put("uiutils", uiStatics); map.put("enviro", new Enviro()); map.put("imageroot", "images/"); }
public static TemplateHashModel useStaticPackage(String key) { try { BeansWrapper wrapper = new BeansWrapperBuilder(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS).build(); TemplateHashModel staticModels = wrapper.getStaticModels(); TemplateHashModel statics = (TemplateHashModel) staticModels.get(key); return statics; } catch (Exception e) { e.printStackTrace(); } return null; }
/*** * 拿到静态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 Object execTyped(List<TemplateModel> args) throws TemplateModelException { if (args.size() != 2) { throw new TemplateModelException("Invalid number of arguments (expected: 2)"); } Environment env = FreeMarkerWorker.getCurrentEnvironment(); TemplateModel arg1 = args.get(0); if (!(arg1 instanceof TemplateScalarModel)) { throw new TemplateModelException("First argument (type) was not a string"); } String type = LangFtlUtil.getAsStringNonEscaping((TemplateScalarModel) arg1); TemplateModel arg2 = args.get(1); if (!(arg2 instanceof TemplateHashModel)) { throw new TemplateModelException("Second argument (sectionsMap) was not a map"); } TemplateHashModelEx sectionsMapModel = (TemplateHashModelEx) LangFtlUtil.toSimpleMap(arg2, false, env.getObjectWrapper()); if ("ftl".equals(type)) { FtlSectionsRenderer sections = FtlSectionsRenderer.create(sectionsMapModel); return sections; } else if ("screen".equals(type)) { // TODO: "screen": WARN: due to build dependencies we won't be able to invoke widget renderer from here // may be forced to use reflection (dirty)... throw new TemplateModelException("First argument (type) currently only supports: ftl (screen type not yet implemented)"); } else { throw new TemplateModelException("First argument (type) currently only supports: ftl"); } }
/** * generate static model * @param packageName * @return */ public static TemplateHashModel generateStaticModel(String packageName) { try { BeansWrapper wrapper = BeansWrapper.getDefaultInstance(); TemplateHashModel staticModels = wrapper.getStaticModels(); TemplateHashModel fileStatics = (TemplateHashModel) staticModels.get(packageName); return fileStatics; } catch (Exception e) { e.printStackTrace(); } return null; }
/** * ftl中增强Java类对象 (不推荐在ftl中使用Java静态类方法,View层只处理自己职责范围内功能即可) * @param packageName * @return */ public static TemplateHashModel generateStaticModel(String packageName) { try { BeansWrapper wrapper = BeansWrapper.getDefaultInstance(); TemplateHashModel staticModels = wrapper.getStaticModels(); TemplateHashModel fileStatics = (TemplateHashModel) staticModels.get(packageName); return fileStatics; } catch (Exception e) { e.printStackTrace(); } return null; }
public void addEnumModel(Class<?> clazz) throws TemplateModelException { TemplateHashModel enumModels = beansWrapper.getEnumModels(); TemplateHashModel enums = (TemplateHashModel) enumModels.get(clazz.getName()); if (enums != null) { freeMarkerConfigurer.getConfiguration().setSharedVariable(clazz.getSimpleName(), enums); } }
public void addStaticModel(Class<?> clazz) throws TemplateModelException { TemplateHashModel staticModels = beansWrapper.getStaticModels(); TemplateHashModel statics = (TemplateHashModel) staticModels.get(clazz.getName()); if (statics != null) { freeMarkerConfigurer.getConfiguration().setSharedVariable(clazz.getSimpleName(), statics); } }
@Override protected void onConfigConstant(Constants me) { me.setBaseViewPath("/WEB-INF/pages"); me.setDevMode(PropKit.getBoolean("devMode", false)); me.setEncoding(Const.DEFAULT_ENCODING); me.setError404View("/WEB-INF/error/404.html"); me.setError500View("/WEB-INF/error/500.html"); // freemarker add static template Set<String> packages = new HashSet<>(); packages.add("com.codeyn.wechat.*.enums"); packages.add("com.codeyn.wechat.utils"); packages.add("com.codeyn.wechat.jfinal.bridger"); Set<Class<?>> clazzes = PackageScanner.scanPackage(packages.toArray(new String[packages.size()])); for (Class<?> clazz : clazzes) { TemplateHashModel tmp = buildStaticTemplate(clazz.getName()); FreeMarkerRender.getConfiguration().setSharedVariable(clazz.getSimpleName(), tmp); } // TODO download me.setFileRenderPath("/download"); // TODO upload smartUpload me.setUploadedFileSaveDirectory("/upload"); }
/** * 1)判断是否已经生成了内容<br/> * 2)若没有生成则生成 */ public String getTagContent(String name, Map params, TemplateHashModel tplModel) { StringBuffer rs = new StringBuffer(); //从缓存中获得模板标记 TemplateTag tplTag = TemplateTagCache.getTagByName(name); // if (tplTag != null) { TemplateContext context = new TemplateContext(); //设置模板内容或者名称 if (tplTag.getTplType().equals(TemplateTag.TPL_TYPE_FILE)) { context.setTplName(tplTag.getTemplatePath()); } else { context.setTplContent(tplTag.getTemplateContent()); } List errors = new ArrayList(); Map model = Collections.synchronizedMap(new HashMap()); model.putAll(params); model.put("__direct_out__", "yes"); context.setModel(model); //渲染模板输出内容 getTemplateEngine().renderTemplate(context, errors); String content = context.getTplContent(); rs.append(content); if (errors.size() > 0) { for (Object o : errors) { System.out.println("error:" + o); } } } return rs.toString(); }
@SuppressWarnings("unchecked") @Override public Object exec(List args) throws TemplateModelException { if (args == null || args.size() < 1 || args.size() > 2 ) { throw new TemplateModelException("Invalid number of arguments (expected: 1-2)"); } ObjectWrapper objectWrapper = CommonFtlUtil.getCurrentEnvironment().getObjectWrapper(); TemplateHashModelEx argsMap = (TemplateHashModelEx) args.get(0); // caller-supplied excludes TemplateModel excludesModel = (args.size() >=2) ? (TemplateModel) args.get(1) : null; Set<String> excludes; if (excludesModel != null) { excludes = LangFtlUtil.getAsStringSet(excludesModel); } else { excludes = new HashSet<>(); } SimpleHash res = null; final Boolean useExclude = Boolean.FALSE; // put attribs from explicit attribs map first, if any TemplateModel attribsModel = argsMap.get("attribs"); if (attribsModel != null && OfbizFtlObjectType.isObjectType(OfbizFtlObjectType.MAP, attribsModel)) { if (OfbizFtlObjectType.isObjectType(OfbizFtlObjectType.COMPLEXMAP, attribsModel)) { attribsModel = LangFtlUtil.toSimpleMap(attribsModel, false, objectWrapper); } res = LangFtlUtil.copyMapToSimple((TemplateHashModel) attribsModel, excludes, useExclude, objectWrapper); } // to get inline attribs, add list of all arg names to excludes as well as the lists themselves TemplateModel allArgNamesModel = argsMap.get("allArgNames"); if (allArgNamesModel != null) { excludes.addAll(LangFtlUtil.getAsStringSet(allArgNamesModel)); } excludes.add("allArgNames"); excludes.add("localArgNames"); // add the inline attribs over the attribs map (if any) if (res == null) { res = LangFtlUtil.copyMapToSimple(argsMap, excludes, useExclude, objectWrapper); } else { LangFtlUtil.putAll(res, argsMap, excludes, useExclude, objectWrapper); } return res; }
public static SimpleHash copyMapToSimple(TemplateHashModel hashModel, Set<String> inExKeys, Boolean include, ObjectWrapper objectWrapper) throws TemplateModelException { SimpleHash res = new SimpleHash(objectWrapper); putAll(res, hashModel, inExKeys, include, objectWrapper); return res; }
public static void addToSimpleMap(SimpleHash dest, TemplateHashModel source, Set<String> keys) throws TemplateModelException { for(String key : keys) { dest.put(key, source.get(key)); } }
public static void addModelsToMap(Map<String, ? super TemplateModel> dest, TemplateHashModel source, Set<String> keys) throws TemplateModelException { for(String key : keys) { dest.put(key, source.get(key)); } }
/** * Makes a simple hash from source map; only specified keys. * <p> * <em>WARN</em>: This is not BeanModel-aware (complex map). */ public static SimpleHash makeSimpleMap(TemplateHashModel map, Set<String> keys, ObjectWrapper objectWrapper) throws TemplateModelException { SimpleHash res = new SimpleHash(objectWrapper); addToSimpleMap(res, map, keys); return res; }
public static SimpleHash makeSimpleMap(TemplateHashModel map, TemplateCollectionModel keys, ObjectWrapper objectWrapper) throws TemplateModelException { SimpleHash res = new SimpleHash(objectWrapper); addToSimpleMap(res, map, LangFtlUtil.toStringSet(keys)); return res; }
public static SimpleHash makeSimpleMap(TemplateHashModel map, TemplateSequenceModel keys, ObjectWrapper objectWrapper) throws TemplateModelException { SimpleHash res = new SimpleHash(objectWrapper); addToSimpleMap(res, map, LangFtlUtil.toStringSet(keys)); return res; }
public TemplateModel get(ActionDataModel m) { return (TemplateHashModel)obj; }
@Override protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) { // Fetching request params Map<String, String> templateArgs = req.getServiceMatch().getTemplateVars(); String storeId = templateArgs.get("storeId"); String storeProtocol = templateArgs.get("storeProtocol"); String uuid= templateArgs.get("uuid"); // Getting the Store ID on which the changes are requested Pair<Long, StoreRef> store = nodeDao.getStore(new StoreRef(storeProtocol, storeId)); if (store == null) { throw new IllegalArgumentException("Invalid store reference: " + storeProtocol + "://" + storeId); } Set<NodeEntity> nodes = new HashSet<NodeEntity>(); NodeEntity node= indexingService.getNodeByUuid(store, uuid); if(node!=null){ nodes.add(node); } // Render them out Map<String, Object> model = new HashMap<String, Object>(1, 1.0f); model.put("qnameDao", qnameDao); model.put("nsResolver", namespaceService); model.put("nodes", nodes); model.put("storeId", storeId); model.put("storeProtocol", storeProtocol); model.put("propertiesUrlPrefix", propertiesUrlPrefix); // This allows to call the static method QName.createQName from the FTL template try { BeansWrapper wrapper = BeansWrapper.getDefaultInstance(); TemplateHashModel staticModels = wrapper.getStaticModels(); TemplateHashModel qnameStatics = (TemplateHashModel) staticModels.get("org.alfresco.service.namespace.QName"); model.put("QName", qnameStatics); } catch (Exception e) { throw new AlfrescoRuntimeException( "Cannot add BeansWrapper for static QName.createQName method to be used from a Freemarker template", e); } logger.debug(String.format("Attaching %s nodes to the WebScript template", nodes.size())); return model; }
public static TemplateHashModel getTemplateHashModel(String clazz) throws Exception { BeansWrapper wrapper = BeansWrapper.getDefaultInstance(); TemplateHashModel staticModels = wrapper.getStaticModels(); return(TemplateHashModel) staticModels.get(clazz); }
/** * 拿到静态Class的Model * * @param className * @return * @throws TemplateModelException */ public static TemplateModel useClass(String className) throws TemplateModelException { BeansWrapper wrapper = (BeansWrapper) configuration.getObjectWrapper(); TemplateHashModel staticModels = wrapper.getStaticModels(); return staticModels.get(className); }
/** * 拿到目标对象某个方法的Model * * @param target * @param methodName * @return * @throws TemplateModelException */ public static TemplateModel useObjectMethod(Object target, String methodName) throws TemplateModelException { TemplateHashModel model = (TemplateHashModel) useObjectModel(target); return model.get(methodName); }
/** * Puts all values in hash into FTL globals (#global). * <p> * @see copyMapToSimple */ public static void globalsPutAll(TemplateHashModel hashModel, Set<String> inExKeys, Boolean include, Environment env) throws TemplateModelException { varsPutAll(hashModel, inExKeys, include, new GlobalFtlVarHandler(env), env); }
/** * Puts all values in hash into FTL current namespace vars (#assign). * <p> * @see copyMapToSimple */ public static void varsPutAll(TemplateHashModel hashModel, Set<String> inExKeys, Boolean include, Environment env) throws TemplateModelException { varsPutAll(hashModel, inExKeys, include, new CurrentFtlVarHandler(env), env); }
/** * Puts all values in hash into FTL locals (#local). * <p> * @see copyMapToSimple */ public static void localsPutAll(TemplateHashModel hashModel, Set<String> inExKeys, Boolean include, Environment env) throws TemplateModelException { varsPutAll(hashModel, inExKeys, include, new LocalFtlVarHandler(env), env); }
/** * 获得标签的内容 * * @param name * 标签名 * @param params * 宏参数 * @param tplModel * 当前模板上下文参数 * @return */ public String getTagContent(String name, Map params, TemplateHashModel tplModel);