Java 类freemarker.template.SimpleHash 实例源码

项目:scipio-erp    文件:LangFtlUtil.java   
/**
 * Adapts a map to a TemplateHashModelEx using an appropriate simple adapter, normally 
 * DefaultMapAdapter (or SimpleMapModel for BeansWrapper compatibility).
 * <p>
 * The ObjectWrapper is expected to implement at least ObjectWrapperWithAPISupport.
 * <p>
 * WARN: If impossible, it will duplicate the map using SimpleHash; but because this may result
 * in loss of ordering, a log warning will be printed.
 */
public static TemplateHashModelEx makeSimpleMapAdapter(Map<?, ?> map, ObjectWrapper objectWrapper, boolean permissive) throws TemplateModelException {
    // COMPATIBILITY MODE: check if exactly BeansWrapper, or a class that we know extends it WITHOUT extending DefaultObjectWrapper
    if (objectWrapper instanceof ScipioBeansWrapper || BeansWrapper.class.equals(objectWrapper.getClass())) {
        return new SimpleMapModel(map, (BeansWrapper) objectWrapper);
    } else if (objectWrapper instanceof ObjectWrapperWithAPISupport) {
        return DefaultMapAdapter.adapt(map, (ObjectWrapperWithAPISupport) objectWrapper);
    } else {
        if (permissive) {
            Debug.logWarning("Scipio: adaptSimpleMap: Unsupported Freemarker object wrapper (expected to implement ObjectWrapperWithAPISupport or BeansWrapper); forced to adapt map"
                    + " using SimpleHash; this could cause loss of map insertion ordering; please switch renderer setup to a different ObjectWrapper", module);
            return new SimpleHash(map, objectWrapper);
        } else {
            throw new TemplateModelException("Tried to wrap a Map using an adapter class,"
                    + " but our ObjectWrapper does not implement ObjectWrapperWithAPISupport or BeansWrapper"
                    + "; please switch renderer setup to a different ObjectWrapper");
        }
    }
}
项目:scipio-erp    文件:LangFtlUtil.java   
/**
 * Combines two maps with the given operator into a new hash.
 */
public static TemplateHashModelEx combineMaps(TemplateHashModelEx first, TemplateHashModelEx second, SetOperations ops, 
        ObjectWrapper objectWrapper) throws TemplateModelException {
    SimpleHash res = new SimpleHash(objectWrapper);
    if (ops == null || ops == SetOperations.UNION) {
        // this is less efficient than freemarker + operator, but provides the "alternative" implementation, so have choice
        addToSimpleMap(res, first);
        addToSimpleMap(res, second);
    }
    else if (ops == SetOperations.INTERSECT) {
        Set<String> intersectKeys = toStringSet(second.keys());
        intersectKeys.retainAll(toStringSet(first.keys()));
        addToSimpleMap(res, second, intersectKeys);
    }
    else if (ops == SetOperations.DIFFERENCE) {
        Set<String> diffKeys = toStringSet(first.keys());
        diffKeys.removeAll(toStringSet(second.keys()));
        addToSimpleMap(res, first, diffKeys);
    }
    else {
        throw new TemplateModelException("Unsupported combineMaps operation");
    }
    return res;
}
项目:bobcat    文件:HtmlReporter.java   
private void merge() {
    try (PrintWriter writer = new PrintWriter(fileCreator.getReportFile("html", getReportStartingDate()),
            StandardCharsets.UTF_8.name())) {
      SimpleHash root = new SimpleHash();
      root.put("collector", testEventCollector);
      root.put("date", new SimpleDateFormat("yyyy-MM-dd HH.mm.ss").format(new Date()));
      root.put("total", getTestCount());
      root.put("passed", getPassedTestCount());
      root.put("failed", getFailedCount());
      root.put("passedPercent", getPassedTestPercent());
      root.put("failedPercent", getFailedPercent());
      temp.process(root, writer);
      writer.flush();
    } catch (TemplateException | IOException e) {
      LOG.error("Exception when merging model with template", e);
    }
}
项目:bisis-v4    文件:Base.java   
public List getSubSubField(Subfield subfield,SimpleHash subField){

    List ssf=new ArrayList();;
    for (int j=0; j<subfield.getSubsubfieldCount(); j++){
        Subsubfield subsubfield=subfield.getSubsubfield(j);
        if(subsubfield!=null){
            SimpleHash subSubField=new SimpleHash();
            subSubField.put("name",subsubfield.getName()+"");
            String cont=subsubfield.getContent();
            cont=cont.replaceAll("<","&lt;");
            cont=cont.replaceAll(">","&gt;");
            subSubField.put("content",cont);

            if(!subsubfield.getContent().equals("")&& !subsubfield.getContent().equals(" ")){
                ssf.add(subSubField);
            }
        }
    }
    return ssf;
}
项目:ivif    文件:JavaTargetFile.java   
@Override
public void render(JAGeneratorContext context) throws Exception {
    util = new JavaClassGeneratorUtil(getId().getClassName());
    ByteArrayOutputStream bodyStream = renderBody(context);
    // Now render header in case there are injections
    ByteArrayOutputStream headerStream = renderHeader(context);
    // Now add the header
    SimpleHash freemarkerContext = context.createSimpleHash();
    freemarkerContext.put("model", this);
    freemarkerContext.put("util", util);
    freemarkerContext.put("context", context);
    Template template = context.getTemplate("JavaHeader.ftl");
    File file = getPath(context).toFile();
    // create file structure
    file.getParentFile().mkdirs();
    // before writing to it
    FileOutputStream outputStream = new FileOutputStream(file);
    template.process(freemarkerContext, new OutputStreamWriter(outputStream));
    // And append the header & body
    if (headerStream != null) {
        headerStream.writeTo(outputStream);
    }
    bodyStream.writeTo(outputStream);
}
项目:ivif    文件:JavaTargetFile.java   
private ByteArrayOutputStream renderHeader(JAGeneratorContext context) throws IOException, TemplateException {
    String headerTemplate = getFreemarkerHeaderTemplateName();
    if (headerTemplate != null) {
        SimpleHash freemarkerContext = context.createSimpleHash();
        freemarkerContext.put("model", getFreemarkerModel());
        freemarkerContext.put("util", util);
        freemarkerContext.put("context", context);
        // First process body
        Template template = context.getTemplate(headerTemplate);
        ByteArrayOutputStream headerStream = new ByteArrayOutputStream();
        template.process(freemarkerContext, new OutputStreamWriter(headerStream));
        return headerStream;
    } else {
        return null;
    }
}
项目:Improve    文件:FreemarkerRender.java   
/**
 * 渲染
 * 
 */
public void render(RenderClass target, String template, String outpath) {
    try {
        StringWriter writer = new StringWriter();
        Template tl = templateconfig.getTemplate(template,
                templateconfig.getLocale());
        SimpleHash root= new SimpleHash();
        root.put("entity", target);
        tl.process(root, writer);
        // Assistant.createNewFile(outpath);
        FileOutputStream fos = new FileOutputStream(outpath);
        PrintWriter pwriter = new PrintWriter(fos);
        pwriter.write(writer.toString());
        pwriter.close();
        fos.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
项目:Improve    文件:FreemarkerRender.java   
/**
 * 渲染
 *
 */
public void render(RenderClass target,String template,String outpath)
{
    try
    {
        StringWriter writer = new StringWriter();
        Template tl = templateconfig.getTemplate(
                template,
                templateconfig.getLocale());
        SimpleHash root = new SimpleHash();
        root.put("entity", target);
        tl.process(root, writer);
        Assistant.createNewFile(outpath);
        FileOutputStream fos = new FileOutputStream(outpath);
        PrintWriter pwriter = new PrintWriter(fos);
        pwriter.write(writer.toString());
        pwriter.close();
        fos.close();   
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}
项目:wadlcodegenerator    文件:CoffeeScriptClientModule.java   
@Override
public Set<FileInfo> generate(CGModel cgModel, CGConfig config) throws ModuleException {
    Set<FileInfo> targetFileSet = new HashSet<>();

    SimpleHash fmModel = this.getFreemarkerModel();
    fmModel.put("config", config);

    Map<String, String> enumConstants = new HashMap<>();
    for (EnumInfo enums : cgModel.getEnums()) {
        enumConstants.put(enums.getName(), joinEnumConstants(enums.getEnumConstants()));
    }
    fmModel.put("enumConstants", enumConstants);


    for (ClassInfo classInfo : cgModel.getClasses()) {
        fmModel.put("clazz", classInfo);
    }

    fmModel.put("classes", cgModel.getClasses());

    String relativePath = ClassNameUtil.packageNameToPath("com.vsc_technologies");
    FileInfo classFile = this.generateFile(classTemplate, fmModel, "schemas", "coffee", relativePath, SOURCE_FOLDER);
    targetFileSet.add(classFile);
    return targetFileSet;
}
项目:wadlcodegenerator    文件:EcmaScript6ClientModule.java   
@Override
public Set<FileInfo> generate(CGModel cgModel, CGConfig config) throws ModuleException {
    Set<FileInfo> targetFileSet = new HashSet<>();

    SimpleHash fmModel = this.getFreemarkerModel();
    fmModel.put("config", config);

    Map<String, String> enumConstants = new HashMap<>();
    for (EnumInfo enums : cgModel.getEnums()) {
        enumConstants.put(enums.getName(), joinEnumConstants(enums.getEnumConstants()));
    }
    fmModel.put("enumConstants", enumConstants);


    for (ClassInfo classInfo : cgModel.getClasses()) {
        fmModel.put("clazz", classInfo);
    }

    fmModel.put("classes", cgModel.getClasses());

    String relativePath = ClassNameUtil.packageNameToPath("com.vsc_technologies");
    FileInfo classFile = this.generateFile(classTemplate, fmModel, "schemas", "js", relativePath, SOURCE_FOLDER);
    targetFileSet.add(classFile);
    return targetFileSet;
}
项目:followt    文件:WebUI.java   
private static TemplateModel getModel (String screen_name, long interval) {
    List<Follower> followers = ui.getRecentFollowers(screen_name, interval);
    List<Unfollower> unfollowers = ui.getRecentUnfollowers(screen_name, interval);
    int unfollowers_deleted = 0;
    for (Iterator<Unfollower> i = unfollowers.iterator(); i.hasNext();) {
        Unfollower u = i.next();
        if (u.getFollowerScreenName().startsWith("*")) {
            i.remove();
            unfollowers_deleted++;
        }
    }
    SimpleHash root = new SimpleHash();
    root.put("screen_name", screen_name);
    root.put("interval", interval);
    root.put("followers", followers);
    root.put("unfollowers", unfollowers);
    root.put("unfollowers_deleted", unfollowers_deleted);
    return root;
}
项目:Smart_City    文件:ReportRoutes.java   
protected void initReportRoute() throws IOException {
    get(new FreemarkerBasedRoute("/item/report", "report.ftl") {
        @Override
        protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException {
            String itemId = request.queryParams("id");

            CityItem cityItem = CityItemDAO.getCityItem(itemId);

            SimpleHash data = new SimpleHash();
            data.put("id", itemId);
            data.put("type", cityItem.getTypeAsString());
            data.put("description", cityItem.getDescription());
            data.put("lat", cityItem.getLatitude());
            data.put("lng", cityItem.getLongitude());

            template.process(data, writer);
        }
    });

    post(new Route("/item/report") {
        @Override
        public Object handle(Request rqst, Response rspns) {
            Report.Builder b = new Report.Builder();
            b.cityItemId(rqst.queryParams("id"))
                    .comment(rqst.queryParams("comment"))
                    .priority(Integer.parseInt(rqst.queryParams("priority")))
                    .reportDate(new Date())
                    .resolved(false);

            ReportDAO.insertReport(b.build());

            JSONObject jsonResult = new JSONObject();
            jsonResult.put("success", true);
            return jsonResult.toString();
        }
    });
}
项目:Smart_City    文件:CityItemRoutes.java   
protected void initIndexRoute() throws IOException {
    get(new FreemarkerBasedRoute("/", "index.ftl") {
        @Override
        public void doHandle(
                Request request, Response response, Writer writer)
                throws IOException, TemplateException {
            SimpleHash data = new SimpleHash();
            data.put("Username", "dummy");

            template.process(data, writer);
        }
    });
}
项目:scipio-erp    文件:MultiVarMethod.java   
public TemplateHashModelEx toMapModel(Environment env) {
    SimpleHash map = new SimpleHash(env.getObjectWrapper());
    map.put("ctxVars", ctxVars);
    map.put("globalCtxVars", globalCtxVars);
    map.put("reqAttribs", reqAttribs);
    return map;
}
项目:scipio-erp    文件:ArgMapMethod.java   
@SuppressWarnings("unchecked")
protected Object execMergeArgMapsToLocals(List methodArgs, boolean recordArgNames) throws TemplateModelException {
    Environment env = CommonFtlUtil.getCurrentEnvironment();

    SimpleHash resArgs = (SimpleHash) execMergeArgMaps(methodArgs, recordArgNames, env);

    LangFtlUtil.localsPutAll(resArgs, env);
    env.setLocalVariable("args", resArgs);

    return new SimpleScalar(""); 
}
项目:scipio-erp    文件:LangFtlUtil.java   
/**
 * Adds to simple hash from source map.
 * <p>
 * <em>WARN</em>: This is not BeanModel-aware (complex map).
 */    
public static void addToSimpleMap(SimpleHash dest, TemplateHashModelEx source) throws TemplateModelException {
    TemplateCollectionModel keysModel = source.keys();
    TemplateModelIterator modelIt = keysModel.iterator();
    while(modelIt.hasNext()) {
        String key = getAsStringNonEscaping((TemplateScalarModel) modelIt.next());
        dest.put(key, source.get(key));
    }
}
项目:spring4-understanding    文件:FreeMarkerView.java   
/**
 * Build a FreeMarker template model for the given model Map.
 * <p>The default implementation builds a {@link AllHttpScopesHashModel}.
 * @param model the model to use for rendering
 * @param request current HTTP request
 * @param response current servlet response
 * @return the FreeMarker template model, as a {@link SimpleHash} or subclass thereof
 */
protected SimpleHash buildTemplateModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
    AllHttpScopesHashModel fmModel = new AllHttpScopesHashModel(getObjectWrapper(), getServletContext(), request);
    fmModel.put(FreemarkerServlet.KEY_JSP_TAGLIBS, this.taglibFactory);
    fmModel.put(FreemarkerServlet.KEY_APPLICATION, this.servletContextHashModel);
    fmModel.put(FreemarkerServlet.KEY_SESSION, buildSessionModel(request, response));
    fmModel.put(FreemarkerServlet.KEY_REQUEST, new HttpRequestHashModel(request, response, getObjectWrapper()));
    fmModel.put(FreemarkerServlet.KEY_REQUEST_PARAMETERS, new HttpRequestParametersHashModel(request));
    fmModel.putAll(model);
    return fmModel;
}
项目:bisis-v4    文件:Base.java   
public List getSubField(Field f,SimpleHash field){

    List sf=new ArrayList();


    for (int j=0; j<f.getSubfieldCount(); j++){
        Subfield subfield=f.getSubfield(j);
        if(subfield!=null){
            SimpleHash secField=new SimpleHash();               
            List ssf=new ArrayList();               
            SimpleHash subField=new SimpleHash();
            subField.put("name",subfield.getName()+"");
            String cont=subfield.getContent();
            cont=cont.replaceAll("<","&lt;");
            cont=cont.replaceAll(">","&gt;");
            subField.put("content",cont);               

            if(subfield.getSubsubfieldCount()>=1){
                ssf=getSubSubField(subfield,subField);
                subField.put("ssf",ssf);
            }

            if(subfield.getSecField()!=null){
                secField=getSecField(subfield,subField);
                subField.put("secField",secField);

            }
            if((!subfield.getContent().equals("")&& !subfield.getContent().equals(" ")) ||subfield.getSubsubfieldCount()>=1 || subfield.getSecField()!=null ){                  
               sf.add(subField);                   
            }
        }
    }
    return sf;
}
项目:bisis-v4    文件:Base.java   
public SimpleHash getSecField(Subfield subfield,SimpleHash subField){
    Field sec=subfield.getSecField();

    SimpleHash secField=new SimpleHash();

    List sf=new ArrayList();
    for(int i=0;i<sec.getSubfieldCount();i++){
        Subfield subfield1=sec.getSubfield(i);
        if(subfield!=null){ 
            SimpleHash subFieldSec=new SimpleHash();
            subFieldSec.put("name",subfield1.getName()+"");
            String cont=subfield1.getContent();
            cont=cont.replaceAll("<","&lt;");
            cont=cont.replaceAll(">","&gt;");
            subFieldSec.put("content",cont);
            if(!subfield1.getContent().equals(""))
                sf.add(subFieldSec);

        }
    }
    if(sf.size()>=1){
        //secField.put("one",sec.getName());
        subField.put("content",sec.getName());
        secField.put("ind1",sec.getInd1()+"");
        secField.put("ind2",sec.getInd2()+"");
        secField.put("sf",sf);
    }

    return secField;
}
项目:geeCommerce-Java-Shop-Software-and-PIM    文件:SetDirective.java   
@SuppressWarnings("rawtypes")
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
    throws TemplateException, IOException {
    TemplateModel pValue = (TemplateModel) params.get("value");
    SimpleScalar pVar = (SimpleScalar) params.get("var");

    if (pVar == null)
        throw new IllegalArgumentException("The var parameter cannot be null in set-directive");

    String var = pVar.getAsString();
    Object value = null;

    if (pValue != null) {
        if (pValue instanceof StringModel) {
            value = ((StringModel) pValue).getWrappedObject();
        } else if (pValue instanceof SimpleHash) {
            value = ((SimpleHash) pValue).toMap();
        } else {
            value = DeepUnwrap.unwrap(pValue);
        }
    } else if (body != null) {
        StringWriter sw = new StringWriter();

        try {
            body.render(sw);
            value = sw.toString().trim();
        } finally {
            IOUtils.closeQuietly(sw);
        }
    }

    env.setVariable(var, DefaultObjectWrapper.getDefaultInstance().wrap(value));
}
项目:ivif    文件:EntityBaseServiceTargetFile.java   
@Override
protected ByteArrayOutputStream renderBody(JAGeneratorContext context) throws IOException, TemplateException {
    SimpleHash freemarkerContext = context.createSimpleHash();
    freemarkerContext.put("model", getFreemarkerModel());
    freemarkerContext.put("util", util);
    freemarkerContext.put("context", context);
    // First process body start
    Template template;
    ByteArrayOutputStream bodyStream = new ByteArrayOutputStream();
    OutputStreamWriter out = new OutputStreamWriter(bodyStream);
    // Then each body parts
    for (RenderPart renderPart : renderParts) {
        try {
            template = context.getTemplate(renderPart.getFreemarkerTemplateName());
            SimpleHash partContext = context.createSimpleHash();
            partContext.put("baseModel", getFreemarkerModel());
            partContext.put("model", renderPart.getModel());
            partContext.put("util", util);
            partContext.put("context", context);
            template.process(partContext, out);
        } catch (Exception e) {
            throw new IllegalStateException("Problem while rendering "+getId()+"["+renderPart.getSource()+"]", e);
        }
    }
    // Then body end
    template = context.getTemplate("entities/EntityBaseService_bodyEnd.java.ftl");
    template.process(freemarkerContext, out);
    return bodyStream;
}
项目:ivif    文件:JavaTargetFile.java   
protected ByteArrayOutputStream renderBody(JAGeneratorContext context) throws IOException, TemplateException {
    SimpleHash freemarkerContext = context.createSimpleHash();
    freemarkerContext.put("model", getFreemarkerModel());
    freemarkerContext.put("util", util);
    freemarkerContext.put("context", context);
    // First process body
    Template template = context.getTemplate(getFreemarkerBodyTemplateName());
    ByteArrayOutputStream bodyStream = new ByteArrayOutputStream();
    template.process(freemarkerContext, new OutputStreamWriter(bodyStream));
    return bodyStream;
}
项目:ivif    文件:RenderUtils.java   
public static void simpleRender(String templateName, TargetFile targetFile, JAGeneratorContext context) throws Exception {
    SimpleHash freemarkerContext = context.createSimpleHash();
    freemarkerContext.put("model", targetFile);
    freemarkerContext.put("context", context);
    // First process body
    Template template = context.getTemplate(templateName);
    File file = targetFile.getPath(context).toFile();
    // create file structure
    file.getParentFile().mkdirs();
    // before writing to it
    FileOutputStream outputStream = new FileOutputStream(file);
    template.process(freemarkerContext, new OutputStreamWriter(outputStream));
}
项目:onetwo    文件:AbstractFreemarkerTemplateConfigurer.java   
/****
     * must be invoke after contruction
     */
    public void initialize() {
        if(isInitialized())
            return ;

        TemplateLoader loader = getTempateLoader();
        Assert.notNull(loader);
        try {
            this.configuration = new Configuration(Configuration.VERSION_2_3_0);
            this.configuration.setObjectWrapper(getBeansWrapper());
            this.configuration.setOutputEncoding(this.encoding);
            //设置默认不自动格式化数字……以防sb……
            this.configuration.setNumberFormat("#");
//          this.cfg.setDirectoryForTemplateLoading(new File(templateDir));

            /*if(templateProvider!=null){
                this.configuration.setTemplateLoader(new DynamicTemplateLoader(templateProvider));
            }*/
            if(LangUtils.isNotEmpty(getFreemarkerVariables()))
                configuration.setAllSharedVariables(new SimpleHash(freemarkerVariables, configuration.getObjectWrapper()));

            //template loader
            /*if(!LangUtils.isEmpty(templatePaths)){
                TemplateLoader loader = FtlUtils.getTemplateLoader(resourceLoader, templatePaths);
                this.configuration.setTemplateLoader(loader);
            }*/
            this.configuration.setTemplateLoader(loader);

            this.buildConfigration(this.configuration);

            initialized = true;
        } catch (Exception e) {
            throw new BaseException("create freemarker template error : " + e.getMessage(), e);
        }
    }
项目:max-ws    文件:NanoWSClientModule.java   
@Override
public Set<FileInfo> generate(WSCodeGenModel cgModel, CGConfig config)
        throws WscModuleException {
    // freemarker datamodel
    SimpleHash fmModel = this.getFreemarkerModel();

    // container for target codes
    Set<FileInfo> targetFileSet = new HashSet<FileInfo>();

    info("Generating the Nano web serivce client classes...");

    fmModel.put("group", config.picoServiceGroup);
    fmModel.put("config", config);

    // generate endpoint interface
    for (SEIInfo interfaceInfo : cgModel.getServiceEndpointInterfaces()) {
        fmModel.put("imports", this.getInterfaceImports(interfaceInfo));
        fmModel.put("endpointInterface", interfaceInfo);

        String relativePath = ClassNameUtil.packageNameToPath(interfaceInfo.getPackageName());
        relativePath += File.separator + "client";
        FileInfo eiSoapClient = this.generateFile(soapClientTemplate, fmModel, interfaceInfo.getName() + "_SOAPClient", "java", relativePath);
        targetFileSet.add(eiSoapClient);
        FileInfo eiXmlClient = this.generateFile(xmlClientTemplate, fmModel, interfaceInfo.getName() + "_XMLClient", "java", relativePath);
        targetFileSet.add(eiXmlClient);
    }

    return targetFileSet;
}
项目:private-freemarker    文件:SaicObjectWrapper.java   
@SuppressWarnings("rawtypes")
@Override
protected TemplateModel handleUnknownType(Object obj)
        throws TemplateModelException {
    if(obj instanceof Tupple){
        return new TuppleAdapter((Tupple) obj, this);
    }else if (obj instanceof Map) {
           return new SimpleHash((Map) obj, this);
       }

    return super.handleUnknownType(obj);
}
项目:elpi    文件:FreeMarkerViewRenderer.java   
protected Object createViewContext(JPublishContext context, String path) throws ViewRenderException {
    HttpServletRequest request = context.getRequest();
    HttpServletResponse response = context.getResponse();

    WrappingTemplateModel.setDefaultObjectWrapper(FreeMarkerWorker.getDefaultOfbizWrapper());
    Map contextMap = new HashMap();
    SimpleHash root = new SimpleHash(FreeMarkerWorker.getDefaultOfbizWrapper());
    try {
        Object[] keys = context.getKeys();
        for (int i = 0; i < keys.length; i++) {
            String key = (String) keys[i];
            Object value = context.get(key);
            if (value != null) {
                contextMap.put(key, value);
                //no longer wrapping; let FM do it if needed, more efficient
                //root.put(key, FreeMarkerWorker.getDefaultOfbizWrapper().wrap(value));
                root.put(key, value);
            }
        }
        root.put("context", FreeMarkerWorker.getDefaultOfbizWrapper().wrap(contextMap));
        root.put("cachedInclude", new JpCacheIncludeTransform()); // only adding this in for JP!
        //root.put("jpublishContext", FreeMarkerWorker.getDefaultOfbizWrapper().wrap(context));
        FreeMarkerViewHandler.prepOfbizRoot(root, request, response);
    } catch (Exception e) {
        throw new ViewRenderException(e);
    }
    return root;
}
项目:MortarLib    文件:ScreenGenerator.java   
private SimpleHash preferencesToHash(TemplatePrefs prefs) {
  SimpleHash hash = new SimpleHash();
  Field[] declaredFields = prefs.getClass().getDeclaredFields();
  try {
    for (Field field : declaredFields) {
      hash.put(field.getName(), field.get(prefs));
    }
  } catch (IllegalAccessException e) {
    throw new RuntimeException(e);
  }
  return hash;
}
项目:o3erp    文件:FreeMarkerViewRenderer.java   
protected Object createViewContext(JPublishContext context, String path) throws ViewRenderException {
    HttpServletRequest request = context.getRequest();
    HttpServletResponse response = context.getResponse();

    WrappingTemplateModel.setDefaultObjectWrapper(FreeMarkerWorker.getDefaultOfbizWrapper());
    Map contextMap = new HashMap();
    SimpleHash root = new SimpleHash(FreeMarkerWorker.getDefaultOfbizWrapper());
    try {
        Object[] keys = context.getKeys();
        for (int i = 0; i < keys.length; i++) {
            String key = (String) keys[i];
            Object value = context.get(key);
            if (value != null) {
                contextMap.put(key, value);
                //no longer wrapping; let FM do it if needed, more efficient
                //root.put(key, FreeMarkerWorker.getDefaultOfbizWrapper().wrap(value));
                root.put(key, value);
            }
        }
        root.put("context", FreeMarkerWorker.getDefaultOfbizWrapper().wrap(contextMap));
        root.put("cachedInclude", new JpCacheIncludeTransform()); // only adding this in for JP!
        //root.put("jpublishContext", FreeMarkerWorker.getDefaultOfbizWrapper().wrap(context));
        FreeMarkerViewHandler.prepOfbizRoot(root, request, response);
    } catch (Exception e) {
        throw new ViewRenderException(e);
    }
    return root;
}
项目:class-guard    文件:FreeMarkerView.java   
/**
 * Build a FreeMarker template model for the given model Map.
 * <p>The default implementation builds a {@link AllHttpScopesHashModel}.
 * @param model the model to use for rendering
 * @param request current HTTP request
 * @param response current servlet response
 * @return the FreeMarker template model, as a {@link SimpleHash} or subclass thereof
 */
protected SimpleHash buildTemplateModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
    AllHttpScopesHashModel fmModel = new AllHttpScopesHashModel(getObjectWrapper(), getServletContext(), request);
    fmModel.put(FreemarkerServlet.KEY_JSP_TAGLIBS, this.taglibFactory);
    fmModel.put(FreemarkerServlet.KEY_APPLICATION, this.servletContextHashModel);
    fmModel.put(FreemarkerServlet.KEY_SESSION, buildSessionModel(request, response));
    fmModel.put(FreemarkerServlet.KEY_REQUEST, new HttpRequestHashModel(request, response, getObjectWrapper()));
    fmModel.put(FreemarkerServlet.KEY_REQUEST_PARAMETERS, new HttpRequestParametersHashModel(request));
    fmModel.putAll(model);
    return fmModel;
}
项目:wadlcodegenerator    文件:ObjectiveCClientModule.java   
@Override
public Set<FileInfo> generate(CGServices cgServices, CGConfig cgConfig) throws ModuleException {
    // freemarker datamodel
    SimpleHash fmModel = this.getFreemarkerModel();
    final String projectPrefix = cgConfig.prefix;

    fmModel.put("projectPrefix", projectPrefix);

    // container for target codes
    Set<FileInfo> targetFileSet = new HashSet<>();

    FileInfo clientObjectImpl = this.generateFile(clientServicesApiClientImplTemplate, fmModel, projectPrefix + "ApiClient", "m", "Services", SOURCE_FOLDER);
    targetFileSet.add(clientObjectImpl);
    FileInfo clientObjectInt = this.generateFile(clientServicesApiClientIntTemplate, fmModel, projectPrefix + "ApiClient", "h", "Services", SOURCE_FOLDER);
    targetFileSet.add(clientObjectInt);

    for (CGService cgService : cgServices.getServices()) {
        final List<CGMethod> methods = dissociateMethodsWithSameName(cgService.getMethods());
        fmModel.put("imports", getImports(methods, projectPrefix));
        fmModel.put("className", projectPrefix + cgService.getName());
        fmModel.put("methods", methods);
        FileInfo clientServicesApiServiceImpl = this.generateFile(clientServicesApiServiceImplTemplate, fmModel, projectPrefix + cgService.getName() + "Api", "m", "Services", SOURCE_FOLDER);
        targetFileSet.add(clientServicesApiServiceImpl);
        FileInfo clientServicesApiServiceInt = this.generateFile(clientServicesApiServiceIntTemplate, fmModel, projectPrefix + cgService.getName() + "Api", "h", "Services", SOURCE_FOLDER);
        targetFileSet.add(clientServicesApiServiceInt);
    }

    return targetFileSet;
}
项目:wadlcodegenerator    文件:AndroidClientModule.java   
@Override
public Set<FileInfo> generateProjectModel(CGConfig cgConfig) throws ModuleException {
    Set<FileInfo> targetFileSet = new HashSet<FileInfo>();

    SimpleHash fmModel = this.getFreemarkerModel();
    fmModel.put("groupId", cgConfig.packageName);
    FileInfo apiJSonUtilFile = this.generateFile(projectModelTemplate, fmModel, "pom", "xml", "", "");
    targetFileSet.add(apiJSonUtilFile);

    return targetFileSet;
}
项目:codefather    文件:BeanDynaAttrModel.java   
public BeanDynaAttrModel(Object object, BeansWrapper wrapper) {
  super(object, wrapper);
  attrMap = new SimpleHash();
  if (object instanceof Described) {
    for(Map.Entry<String, String> e : ((Described)object).getAttrMap().entrySet()) {
      attrMap.put(e.getKey(),e.getValue());
    }
  }
}
项目:private-freemarker    文件:SaicObjectWrapper.java   
@SuppressWarnings("rawtypes")
@Override
protected TemplateModel handleUnknownType(Object obj)
        throws TemplateModelException {
    if(obj instanceof Tupple){
        return new TuppleAdapter((Tupple) obj, this);
    }else if (obj instanceof Map) {
           return new SimpleHash((Map) obj, this);
       }

    return super.handleUnknownType(obj);
}
项目:nutz_frame    文件:FreemarkerView.java   
/**
 * @param request 请求
 * @param response 反应
 * @param value 对象
 * @throws Exception 异常
 */
@SuppressWarnings({"rawtypes"})
public void render(HttpServletRequest request, HttpServletResponse response, Object value) throws Exception {
    HttpSession session = request.getSession();
    ServletContext sc = session.getServletContext();
    cfg = getConfiguration(sc);
    SimpleHash root = new SimpleHash(ObjectWrapper.BEANS_WRAPPER);

    root.put("theme", theme);
    root.put("version", VER_TAG);
    root.put(VALUE, value);
    root.put(REQUEST, request);
    // 返回地址
    root.put("refererUrl",
             this.getRefererUrl(session.getAttribute("referer"), (Map) session.getAttribute("refererMap")));

    // 地址和参数
    session.setAttribute("referer", request.getRequestURI());
    session.setAttribute("refererMap", getRefererMap(request));

    root.put(CONTEXT, request.getContextPath());
    root.put(RESPONSE, response);
    root.put(SESSION, session);
    root.put(APPLICATION, sc);

    Enumeration reqs = request.getAttributeNames();
    while (reqs.hasMoreElements()) {
        String strKey = (String) reqs.nextElement();
        root.put(strKey, request.getAttribute(strKey));
    }

    Template t = cfg.getTemplate(path);
    response.setContentType("text/html; charset=utf-8");
    t.process(root, response.getWriter());
}
项目:GEO-label-java    文件:Label.java   
public void toSVG(Writer writer, final String id, final int size) throws IOException {
    try {
        SimpleHash model = new SimpleHash();
        model.put("size", Integer.valueOf(size));
        model.put("id", id);
        model.put("label", this);

        getSVGTemplate().process(model, writer);
    }
    catch (TemplateException e) {
        log.error("Error in geolabel template", e);
        throw new IOException("Unable to process SVG template");
    }
}
项目:mwsc    文件:NanoWSClientModule.java   
@Override
public Set<FileInfo> generate(WSCodeGenModel cgModel, CGConfig config)
        throws WscModuleException {
    // freemarker datamodel
    SimpleHash fmModel = this.getFreemarkerModel();

    // container for target codes
    Set<FileInfo> targetFileSet = new HashSet<FileInfo>();

    info("Generating the Nano web serivce client classes...");

    fmModel.put("group", config.picoServiceGroup);
    fmModel.put("config", config);

    // generate endpoint interface
    for (SEIInfo interfaceInfo : cgModel.getServiceEndpointInterfaces()) {
        fmModel.put("imports", this.getInterfaceImports(interfaceInfo));
        fmModel.put("endpointInterface", interfaceInfo);

        String relativePath = ClassNameUtil.packageNameToPath(interfaceInfo.getPackageName());
        relativePath += File.separator + "client";
        FileInfo eiSoapClient = this.generateFile(soapClientTemplate, fmModel, interfaceInfo.getName() + "_SOAPClient", "java", relativePath);
        targetFileSet.add(eiSoapClient);
        FileInfo eiXmlClient = this.generateFile(xmlClientTemplate, fmModel, interfaceInfo.getName() + "_XMLClient", "java", relativePath);
        targetFileSet.add(eiXmlClient);
    }

    return targetFileSet;
}
项目:digital-model-repository    文件:AbstractModelResource.java   
private SimpleHash getModelTemplateDataModel() {
    SimpleHash result = new SimpleHash() ;
    result.put("entryName", entryName) ;
    result.put("modelName", modelName) ;
    result.put("model", model) ;
    result.put("funcs", new TemplateFunctions()) ;
    return result ;
}
项目:digital-model-repository    文件:NewModelResource.java   
@Get("htm|html")
   public Representation getNewModelForm() {
SimpleHash root = new SimpleHash() ;
root.put("entryName", entryName) ;
root.put("funcs", new TemplateFunctions()) ;

return new TemplateRepresentation("newModel.html", getFreeMarkerConfig(), root, MediaType.TEXT_HTML) ;
   }
项目:digital-model-repository    文件:AbstractJobResource.java   
protected Representation buildHtmlJob() {
    SimpleHash root = new SimpleHash() ;
    root.put("entryName", entryName) ;
    root.put("modelName", modelName) ;
    root.put("jobName", jobName) ;
    root.put("model", model) ;
    root.put("job", job) ;
    root.put("isRunning", isRunning(job)) ;
    root.put("funcs", new TemplateFunctions()) ;

    Configuration config = getFreeMarkerConfig() ;
    Representation result = new TemplateRepresentation("job.html", config, root, MediaType.TEXT_HTML) ;
    result.setCharacterSet(CharacterSet.UTF_8) ;
    return result ;
}