Java 类org.apache.velocity.context.Context 实例源码

项目:spring-velocity-adapter    文件:VelocityLayoutView.java   
/**
 * Overrides the normal rendering process in order to pre-process the Context,
 * merging it with the screen template into a single value (identified by the
 * value of screenContentKey). The layout template is then merged with the
 * modified Context in the super class.
 */
@Override
protected void doRender(Context context, HttpServletResponse response) throws Exception {
    renderScreenContent(context);

    // Velocity context now includes any mappings that were defined
    // (via #set) in screen content template.
    // The screen template can overrule the layout by doing
    // #set( $layout = "MyLayout.vm" )
    String layoutUrlToUse = (String) context.get(this.layoutKey);
    if (layoutUrlToUse != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Screen content template has requested layout [" + layoutUrlToUse + "]");
        }
    }
    else {
        // No explicit layout URL given -> use default layout of this view.
        layoutUrlToUse = this.layoutUrl;
    }

    mergeTemplate(getTemplate(layoutUrlToUse), context, response);
}
项目:spring-velocity-adapter    文件:VelocityView.java   
/**
 * Merge the template with the context.
 * Can be overridden to customize the behavior.
 * @param template the template to merge
 * @param context the Velocity context to use for rendering
 * @param response servlet response (use this to get the OutputStream or Writer)
 * @throws Exception if thrown by Velocity
 * @see org.apache.velocity.Template#merge
 */
protected void mergeTemplate(
        Template template, Context context, HttpServletResponse response) throws Exception {

    try {
        template.merge(context, response.getWriter());
    }
    catch (MethodInvocationException ex) {
        Throwable cause = ex.getWrappedThrowable();
        throw new NestedServletException(
                "Method invocation failed during rendering of Velocity view with name '" +
                getBeanName() + "': " + ex.getMessage() + "; reference [" + ex.getReferenceName() +
                "], method '" + ex.getMethodName() + "'",
                cause==null ? ex : cause);
    }
}
项目:spring-velocity-adapter    文件:VelocityToolboxView.java   
/**
 * Overridden to create a ChainedContext, which is part of the view package
 * of Velocity Tools, as special context. ChainedContext is needed for
 * initialization of ViewTool instances.
 * @see #initTool
 */
@Override
protected Context createVelocityContext(
        Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

    // Create a ChainedContext instance.
    ChainedContext velocityContext = new ChainedContext(
            new VelocityContext(model), getVelocityEngine(), request, response, getServletContext());

    // Load a Velocity Tools toolbox, if necessary.
    if (getToolboxConfigLocation() != null) {
        ToolboxManager toolboxManager = ServletToolboxManager.getInstance(
                getServletContext(), getToolboxConfigLocation());
        Map<String, Object> toolboxContext = toolboxManager.getToolbox(velocityContext);
        velocityContext.setToolbox(toolboxContext);
    }

    return velocityContext;
}
项目:spring4-understanding    文件:VelocityLayoutView.java   
/**
 * Overrides the normal rendering process in order to pre-process the Context,
 * merging it with the screen template into a single value (identified by the
 * value of screenContentKey). The layout template is then merged with the
 * modified Context in the super class.
 */
@Override
protected void doRender(Context context, HttpServletResponse response) throws Exception {
    renderScreenContent(context);

    // Velocity context now includes any mappings that were defined
    // (via #set) in screen content template.
    // The screen template can overrule the layout by doing
    // #set( $layout = "MyLayout.vm" )
    String layoutUrlToUse = (String) context.get(this.layoutKey);
    if (layoutUrlToUse != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Screen content template has requested layout [" + layoutUrlToUse + "]");
        }
    }
    else {
        // No explicit layout URL given -> use default layout of this view.
        layoutUrlToUse = this.layoutUrl;
    }

    mergeTemplate(getTemplate(layoutUrlToUse), context, response);
}
项目:spring4-understanding    文件:VelocityView.java   
/**
 * Merge the template with the context.
 * Can be overridden to customize the behavior.
 * @param template the template to merge
 * @param context the Velocity context to use for rendering
 * @param response servlet response (use this to get the OutputStream or Writer)
 * @throws Exception if thrown by Velocity
 * @see org.apache.velocity.Template#merge
 */
protected void mergeTemplate(
        Template template, Context context, HttpServletResponse response) throws Exception {

    try {
        template.merge(context, response.getWriter());
    }
    catch (MethodInvocationException ex) {
        Throwable cause = ex.getWrappedThrowable();
        throw new NestedServletException(
                "Method invocation failed during rendering of Velocity view with name '" +
                getBeanName() + "': " + ex.getMessage() + "; reference [" + ex.getReferenceName() +
                "], method '" + ex.getMethodName() + "'",
                cause==null ? ex : cause);
    }
}
项目:spring4-understanding    文件:VelocityToolboxView.java   
/**
 * Overridden to create a ChainedContext, which is part of the view package
 * of Velocity Tools, as special context. ChainedContext is needed for
 * initialization of ViewTool instances.
 * @see #initTool
 */
@Override
protected Context createVelocityContext(
        Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

    // Create a ChainedContext instance.
    ChainedContext velocityContext = new ChainedContext(
            new VelocityContext(model), getVelocityEngine(), request, response, getServletContext());

    // Load a Velocity Tools toolbox, if necessary.
    if (getToolboxConfigLocation() != null) {
        ToolboxManager toolboxManager = ServletToolboxManager.getInstance(
                getServletContext(), getToolboxConfigLocation());
        Map<?, ?> toolboxContext = toolboxManager.getToolbox(velocityContext);
        velocityContext.setToolbox(toolboxContext);
    }

    return velocityContext;
}
项目:spring4-understanding    文件:VelocityMacroTests.java   
@Test
public void exposeSpringMacroHelpers() throws Exception {
    VelocityView vv = new VelocityView() {
        @Override
        protected void mergeTemplate(Template template, Context context, HttpServletResponse response) {
            assertTrue(context.get(VelocityView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE) instanceof RequestContext);
            RequestContext rc = (RequestContext) context.get(VelocityView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE);
            BindStatus status = rc.getBindStatus("tb.name");
            assertEquals("name", status.getExpression());
            assertEquals("juergen", status.getValue());
        }
    };
    vv.setUrl(TEMPLATE_FILE);
    vv.setApplicationContext(wac);
    vv.setExposeSpringMacroHelpers(true);

    Map<String, Object> model = new HashMap<String, Object>();
    model.put("tb", new TestBean("juergen", 99));
    vv.render(model, request, response);
}
项目:spring4-understanding    文件:VelocityMacroTests.java   
@Test
public void springMacroRequestContextAttributeUsed() {
    final String helperTool = "wrongType";

    VelocityView vv = new VelocityView() {
        @Override
        protected void mergeTemplate(Template template, Context context, HttpServletResponse response) {
            fail();
        }
    };
    vv.setUrl(TEMPLATE_FILE);
    vv.setApplicationContext(wac);
    vv.setExposeSpringMacroHelpers(true);

    Map<String, Object> model = new HashMap<String, Object>();
    model.put(VelocityView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE, helperTool);

    try {
        vv.render(model, request, response);
    }
    catch (Exception ex) {
        assertTrue(ex instanceof ServletException);
        assertTrue(ex.getMessage().contains(VelocityView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE));
    }
}
项目:beyondj    文件:AuthenticationServlet.java   
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    Template template = null;

    try {
        template = velocityEngine.getTemplate("authentication.tpl");
    } catch (Exception e) {
        LOG.error("Could not find authentication.tpl");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not find authentication.tpl");
    }
    request.getSession().invalidate();

    Context context = localizedVelocityContexts.get(request.getLocale());
    if (context == null) {
        context = localizedVelocityContexts.get(Locale.ENGLISH);
    }

    StringWriter writer = new StringWriter();
    template.merge(context, writer);

    response.setContentType(TEXT_HTML);
    response.getWriter().write(writer.toString());
}
项目:beyondj    文件:InstallationServlet.java   
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    //TODO: use authentication servlet an redirect back and forth
    Template template = null;

    try {
        template = velocityEngine.getTemplate("authentication.tpl");
    } catch (Exception e) {
        LOG.error("Could not find authentication.tpl");
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not find authentication.tpl");
    }
    req.getSession().invalidate();

    Context context = localizedVelocityContexts.get(req.getLocale());
    if (context == null) {
        context = localizedVelocityContexts.get(Locale.ENGLISH);
    }

    StringWriter writer = new StringWriter();
    template.merge(context, writer);

    resp.setContentType(TEXT_HTML);
    resp.getWriter().write(writer.toString());
}
项目:nbone    文件:VlocityFormat.java   
public static String format(VelocityEngine ve,String pattern, Object dataModel){
    if(ve == null){
        ve = VlocityFormat.ve;
    }
    Context context = createVelocityContext(dataModel);

    //raw return 
    if(context == null){
        return pattern;
    }

    StringWriter writer = new StringWriter();
    ve.evaluate(context, writer, "logTag", pattern);

    return writer.toString();
}
项目:nbone    文件:VlocityFormat.java   
public static String format(VelocityEngine ve,Reader reader, Object dataModel){
    if(ve == null){
        ve = VlocityFormat.ve;
    }
    Context context = createVelocityContext(dataModel);

    //raw return 
    if(context == null){
        return reader.toString();
    }

    StringWriter writer = new StringWriter();
    ve.evaluate(context, writer, "logTag", reader);

    return writer.toString();
}
项目:java-template-simple    文件:VelocityToolboxView.java   
@Override
protected Context createVelocityContext(Map<String, Object> model,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    ViewToolContext velocityContext = new ViewToolContext(getVelocityEngine(), request, response, getServletContext());
    velocityContext.putAll(model);
    if(getToolboxConfigLocation() != null ||getToolboxConfigResource() != null){
        XmlFactoryConfiguration cfg = new XmlFactoryConfiguration();
        URL cfgUrl;
        if(getToolboxConfigLocation() != null){
            cfgUrl = new ServletContextResource(getServletContext(), getToolboxConfigLocation()).getURL();
            cfg.read(cfgUrl);
        }else if(getToolboxConfigResource() != null){
            cfgUrl = getToolboxConfigResource().getURL();
            cfg.read(cfgUrl);
            ToolboxFactory factory = cfg.createFactory();

            velocityContext.addToolbox(factory.createToolbox(Scope.APPLICATION));
            velocityContext.addToolbox(factory.createToolbox(Scope.REQUEST));
            velocityContext.addToolbox(factory.createToolbox(Scope.SESSION));
        }
    }
    return velocityContext;
}
项目:fengduo    文件:CustomVelocityLayoutView.java   
/**
 * 创建velocity的Context后注如一些工具类和widget
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Context createVelocityContext(Map model, HttpServletRequest request, HttpServletResponse response)
                                                                                                            throws Exception {
    Context context = super.createVelocityContext(model, request, response);
    if (contextPath == null) {
        contextPath = request.getContextPath();
    }
    context.put("base", contextPath);

    if (viewTools == null) {
        initViewTools();
    }
    if (viewTools.size() != 0) {
        for (String name : viewTools.keySet()) {
            context.put(name, viewTools.get(name));
            logger.debug("the view tool named " + name + " is added to velocity context");
        }
    }

    context.put("widget", new Widget(applicationContext, request, response));
    return context;
}
项目:sakai    文件:VelocityPortalRenderEngine.java   
public void render(String template, PortalRenderContext rcontext, Writer out)
        throws Exception
{
    if (log.isTraceEnabled()) {
       log.trace("Portal trace is on, dumping PortalRenderContext to log:\n" + rcontext.dump());
    }

    Context vc = ((VelocityPortalRenderContext) rcontext).getVelocityContext();
    String skin = (String) vc.get("pageCurrentSkin");
    if (skin == null || skin.length() == 0)
    {
        skin = defaultSkin;
    }
    if (!defaultSkin.equals(skin))
    {
        vengine.getTemplate("/vm/" + skin + "/macros.vm");
    }
    vengine.mergeTemplate("/vm/" + skin + "/" + template + ".vm",
            ((VelocityPortalRenderContext) rcontext).getVelocityContext(), out);

}
项目:olat    文件:TACourseNodeEditController.java   
private String getTaskDeletedMailBody(final UserRequest ureq, final String fileName, final String courseName, final String courseLink) {
    // grab standard text
    final String confirmation = translate("task.deleted.body");

    final Context c = new VelocityContext();
    final Identity identity = ureq.getIdentity();
    c.put("login", identity.getName());
    c.put("first", getUserService().getUserProperty(identity.getUser(), UserConstants.FIRSTNAME, getLocale()));
    c.put("last", getUserService().getUserProperty(identity.getUser(), UserConstants.LASTNAME, getLocale()));
    c.put("email", getUserService().getUserProperty(identity.getUser(), UserConstants.EMAIL, getLocale()));
    c.put("filename", fileName);
    c.put("coursename", courseName);
    c.put("courselink", courseLink);
    final VelocityHelper vh = (VelocityHelper) CoreSpringFactory.getBean(VelocityHelper.class);
    return vh.evaluateVTL(confirmation, c);
}
项目:olat    文件:VelocityContainerRenderer.java   
/**
 * org.olat.presentation.framework.components.Component, org.olat.presentation.framework.render.URLBuilder, org.olat.presentation.framework.translator.Translator,
 * org.olat.presentation.framework.render.RenderResult, java.lang.String[])
 */
@Override
public void render(Renderer renderer, StringOutput target, Component source, URLBuilder ubu, Translator translator, RenderResult renderResult, String[] args) {
    VelocityContainer vc = (VelocityContainer) source;
    String pagePath = vc.getPage();
    Context ctx = vc.getContext();

    // the component id of the urlbuilder will be overwritten by the recursive render call for
    // subcomponents (see Renderer)
    Renderer fr = Renderer.getInstance(vc, translator, ubu, renderResult, renderer.getGlobalSettings());
    VelocityRenderDecorator vrdec = new VelocityRenderDecorator(fr, vc);
    ctx.put("r", vrdec);
    String mm = velocityHelper.mergeContent(pagePath, ctx, theme);

    // experimental!!!
    // surround with red border if recording mark indicates so.
    if (vc.markingCommandString != null) {
        target.append("<table style=\"border:3px solid red; background-color:#E0E0E0; padding:4px; margin:0px;\"><tr><td>").append(mm).append("</td></tr></table>");
    } else {
        target.append(mm);
    }
}
项目:olat    文件:AbstractDropboxBaseController.java   
private String getConfirmation(final UserRequest ureq, final String filename) {
    // grab standard text
    final String confirmation = getDefaultConfirmationText();

    final Context c = new VelocityContext();
    final Identity identity = ureq.getIdentity();
    c.put("login", identity.getName());
    c.put("first", getUserService().getUserProperty(identity.getUser(), UserConstants.FIRSTNAME, getLocale()));
    c.put("last", getUserService().getUserProperty(identity.getUser(), UserConstants.LASTNAME, getLocale()));
    c.put("email", getUserService().getUserProperty(identity.getUser(), UserConstants.EMAIL, getLocale()));
    c.put("filename", filename);
    final Date now = new Date();
    final Formatter f = Formatter.getInstance(ureq.getLocale());
    c.put("date", f.formatDate(now));
    c.put("time", f.formatTime(now));

    VelocityHelper vh = CoreSpringFactory.getBean(VelocityHelper.class);
    return vh.evaluateVTL(confirmation, c);
}
项目:olat    文件:VelocityContainerRenderer.java   
/**
 * org.olat.presentation.framework.components.Component, org.olat.presentation.framework.render.URLBuilder, org.olat.presentation.framework.translator.Translator,
 * org.olat.presentation.framework.render.RenderResult, java.lang.String[])
 */
@Override
public void render(Renderer renderer, StringOutput target, Component source, URLBuilder ubu, Translator translator, RenderResult renderResult, String[] args) {
    VelocityContainer vc = (VelocityContainer) source;
    String pagePath = vc.getPage();
    Context ctx = vc.getContext();

    // the component id of the urlbuilder will be overwritten by the recursive render call for
    // subcomponents (see Renderer)
    Renderer fr = Renderer.getInstance(vc, translator, ubu, renderResult, renderer.getGlobalSettings());
    VelocityRenderDecorator vrdec = new VelocityRenderDecorator(fr, vc);
    ctx.put("r", vrdec);
    String mm = velocityHelper.mergeContent(pagePath, ctx, theme);

    // experimental!!!
    // surround with red border if recording mark indicates so.
    if (vc.markingCommandString != null) {
        target.append("<table style=\"border:3px solid red; background-color:#E0E0E0; padding:4px; margin:0px;\"><tr><td>").append(mm).append("</td></tr></table>");
    } else {
        target.append(mm);
    }
}
项目:computoser    文件:EmailService.java   
private String constructEmailMessages(EmailDetails details) {
    String emailMessage = null;

    if (details.getMessageTemplate() != null) {
        Template template = engine.getTemplate(details.getMessageTemplate(), "UTF-8");
        StringWriter writer = new StringWriter();
        Context ctx = new VelocityContext();
        for (Map.Entry<String, Object> entry : details.getMessageTemplateModel().entrySet()) {
            ctx.put(entry.getKey(), entry.getValue());
        }
        ctx.put("baseUrl", baseUrl);
        ctx.put("currentUser", details.getCurrentUser());

        template.merge(ctx, writer);
        return writer.toString();
    }

    if (details.getMessage() != null) {
        emailMessage = details.getMessage();
    }

    return emailMessage;
}
项目:class-guard    文件:VelocityLayoutView.java   
/**
 * Overrides the normal rendering process in order to pre-process the Context,
 * merging it with the screen template into a single value (identified by the
 * value of screenContentKey). The layout template is then merged with the
 * modified Context in the super class.
 */
@Override
protected void doRender(Context context, HttpServletResponse response) throws Exception {
    renderScreenContent(context);

    // Velocity context now includes any mappings that were defined
    // (via #set) in screen content template.
    // The screen template can overrule the layout by doing
    // #set( $layout = "MyLayout.vm" )
    String layoutUrlToUse = (String) context.get(this.layoutKey);
    if (layoutUrlToUse != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Screen content template has requested layout [" + layoutUrlToUse + "]");
        }
    }
    else {
        // No explicit layout URL given -> use default layout of this view.
        layoutUrlToUse = this.layoutUrl;
    }

    mergeTemplate(getTemplate(layoutUrlToUse), context, response);
}
项目:class-guard    文件:VelocityView.java   
/**
 * Merge the template with the context.
 * Can be overridden to customize the behavior.
 * @param template the template to merge
 * @param context the Velocity context to use for rendering
 * @param response servlet response (use this to get the OutputStream or Writer)
 * @throws Exception if thrown by Velocity
 * @see org.apache.velocity.Template#merge
 */
protected void mergeTemplate(
        Template template, Context context, HttpServletResponse response) throws Exception {

    try {
        template.merge(context, response.getWriter());
    }
    catch (MethodInvocationException ex) {
        Throwable cause = ex.getWrappedThrowable();
        throw new NestedServletException(
                "Method invocation failed during rendering of Velocity view with name '" +
                getBeanName() + "': " + ex.getMessage() + "; reference [" + ex.getReferenceName() +
                "], method '" + ex.getMethodName() + "'",
                cause==null ? ex : cause);
    }
}
项目:class-guard    文件:VelocityToolboxView.java   
/**
 * Overridden to create a ChainedContext, which is part of the view package
 * of Velocity Tools, as special context. ChainedContext is needed for
 * initialization of ViewTool instances.
 * @see #initTool
 */
@Override
protected Context createVelocityContext(
        Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

    // Create a ChainedContext instance.
    ChainedContext velocityContext = new ChainedContext(
            new VelocityContext(model), getVelocityEngine(), request, response, getServletContext());

    // Load a Velocity Tools toolbox, if necessary.
    if (getToolboxConfigLocation() != null) {
        ToolboxManager toolboxManager = ServletToolboxManager.getInstance(
                getServletContext(), getToolboxConfigLocation());
        Map toolboxContext = toolboxManager.getToolbox(velocityContext);
        velocityContext.setToolbox(toolboxContext);
    }

    return velocityContext;
}
项目:class-guard    文件:VelocityMacroTests.java   
public void testExposeSpringMacroHelpers() throws Exception {
    VelocityView vv = new VelocityView() {
        @Override
        protected void mergeTemplate(Template template, Context context, HttpServletResponse response) {
            assertTrue(context.get(VelocityView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE) instanceof RequestContext);
            RequestContext rc = (RequestContext) context.get(VelocityView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE);
            BindStatus status = rc.getBindStatus("tb.name");
            assertEquals("name", status.getExpression());
            assertEquals("juergen", status.getValue());
        }
    };
    vv.setUrl(TEMPLATE_FILE);
    vv.setApplicationContext(wac);
    vv.setExposeSpringMacroHelpers(true);

    Map<String, Object> model = new HashMap<String, Object>();
    model.put("tb", new TestBean("juergen", 99));
    vv.render(model, request, response);
}
项目:class-guard    文件:VelocityMacroTests.java   
public void testSpringMacroRequestContextAttributeUsed() {
    final String helperTool = "wrongType";

    VelocityView vv = new VelocityView() {
        @Override
        protected void mergeTemplate(Template template, Context context, HttpServletResponse response) {
            fail();
        }
    };
    vv.setUrl(TEMPLATE_FILE);
    vv.setApplicationContext(wac);
    vv.setExposeSpringMacroHelpers(true);

    Map<String, Object> model = new HashMap<String, Object>();
    model.put(VelocityView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE, helperTool);

    try {
        vv.render(model, request, response);
    }
    catch (Exception ex) {
        assertTrue(ex instanceof ServletException);
        assertTrue(ex.getMessage().contains(VelocityView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE));
    }
}
项目:java-course-ee    文件:Test3.java   
public Test3() throws Exception {
    //init
    Velocity.init("Velocity/GS_Velocity_1/src/main/java/velocity.properties");
    // get Template
    Template template = Velocity.getTemplate("Test3.vm");
    // getContext
    Context context = new VelocityContext();

    String name = "Vova";
    int age = 21;
    boolean flag = true;

    context.put("name", name);
    context.put("age", age);
    context.put("flag", flag);

    context.put("today", new Date());
    context.put("product", new Product("Book", 12.3));

    // get Writer
    Writer writer = new StringWriter();
    // merge
    template.merge(context, writer);

    System.out.println(writer.toString());
}
项目:java-course-ee    文件:Test1.java   
public Test1() throws Exception {

        //init
        Velocity.init("Velocity/GS_Velocity_1/src/main/java/velocity.properties");
        // get Template
        Template template = Velocity.getTemplate("Test1.vm");
        // getContext
        Context context = new VelocityContext();
        // get Writer
        Writer writer = new StringWriter();
        // merge
        template.merge(context, writer);

        System.out.println(writer.toString());

    }
项目:java-course-ee    文件:TestServlet.java   
@Override
public Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) {


    if (request.getParameter("submit") != null) {
        List<String> errors = new ArrayList();
        String name = request.getParameter("name");
        System.out.println("name = " + name);
        try {
            double price = Double.parseDouble(request.getParameter("price"));
            System.out.println("price = " + price);
            products.add(new Product(name, price));
        } catch (NumberFormatException e) {
            System.err.println(e);
            errors.add("Price must be a number");
        }
        context.put("errors", errors);
    }

    Template template = null;
    context.put("products", products);
    context.put("company", "Gemini Systems");
    template = getTemplate("products.vm");
    return template;
}
项目:sharding    文件:VelocityView.java   
@Override
protected void renderMergedTemplateModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    exposeHelpers(model, request);
    Context velocityContext = createVelocityContext(model, request, response);
    Map<String, Object> templateVariables = getApplicationContext().getBeansWithAnnotation(WebModuleVariable.class);
    if (templateVariables != null && templateVariables.size() > 0) {
        for (Map.Entry<String, Object> e : templateVariables.entrySet()) {
            // 注入自定义工具
            String name = e.getKey();
            Object tool = e.getValue();
            if (tool == null) {
                continue;
            }
            if (tool instanceof ContextAware) {
                ((ContextAware) tool).setContext(velocityContext);
            }
            velocityContext.put(name, tool);
        }
    }
    exposeHelpers(velocityContext, request, response);
    doRender(velocityContext, response);
}
项目:sharding    文件:VelocityView.java   
protected void doRender(Context context, HttpServletResponse response) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("Rendering Velocity template [" + getUrl() + "] in VelocityView '" + getBeanName()
                + "', velocity '" + viewName + "'");
    }

    Template screenTemplate = getTemplate(getUrl());
    // 同名的layout
    String layoutTemplateURL = templates + layout + viewName + suffix;
    Template layoutTemplate = loadTemplate(layoutTemplateURL);

    if (layoutTemplate == null) {// 默认的layout
        layoutTemplateURL = templates + layout + defaultLayoutTemplate;
        layoutTemplate = loadTemplate(layoutTemplateURL);
    }

    if (layoutTemplate == null) {// 没有找到layout就只解析screen
        mergeTemplate(screenTemplate, context, response);
        return;
    }

    context.put(screenTemplateKey, templateRender(context, screenTemplate));
    mergeTemplate(layoutTemplate, context, response);
}
项目:sharding    文件:VelocityView.java   
/**
 * 渲染一个模板。
 * 
 * @param context
 * @param template
 * @return
 */
protected String templateRender(Context context, Template template) {
    if (template == null || context == null) {
        return "";
    }
    try {
        StringWriter sw = new StringWriter();
        template.merge(context, sw);
        return sw.toString();
    } catch (Exception e) {
        if (logger.isErrorEnabled()) {
            logger.error(String.format("Template[%s] Render Error.", template.getName()), e);
        }
    }
    return "";
}
项目:spring-velocity-adapter    文件:VelocityLayoutView.java   
/**
 * The resulting context contains any mappings from render, plus screen content.
 */
private void renderScreenContent(Context velocityContext) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("Rendering screen content template [" + getUrl() + "]");
    }

    StringWriter sw = new StringWriter();
    Template screenContentTemplate = getTemplate(getUrl());
    screenContentTemplate.merge(velocityContext, sw);

    // Put rendered content into Velocity context.
    velocityContext.put(this.screenContentKey, sw.toString());
}
项目:spring-velocity-adapter    文件:VelocityView.java   
/**
 * Process the model map by merging it with the Velocity template.
 * Output is directed to the servlet response.
 * <p>This method can be overridden if custom behavior is needed.
 */
@Override
protected void renderMergedTemplateModel(
        Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

    exposeHelpers(model, request);

    Context velocityContext = createVelocityContext(model, request, response);
    exposeHelpers(velocityContext, request, response);
    exposeToolAttributes(velocityContext, request);

    doRender(velocityContext, response);
}
项目:spring-velocity-adapter    文件:VelocityView.java   
/**
 * Expose the tool attributes, according to corresponding bean property settings.
 * <p>Do not override this method unless for further tools driven by bean properties.
 * Override one of the {@code exposeHelpers} methods to add custom helpers.
 * @param velocityContext Velocity context that will be passed to the template
 * @param request current HTTP request
 * @throws Exception if there's a fatal error while we're adding model attributes
 * @see #setDateToolAttribute
 * @see #setNumberToolAttribute
 * @see #exposeHelpers(Map, HttpServletRequest)
 * @see #exposeHelpers(org.apache.velocity.context.Context, HttpServletRequest, HttpServletResponse)
 */
protected void exposeToolAttributes(Context velocityContext, HttpServletRequest request) throws Exception {
    // Expose generic attributes.
    if (this.toolAttributes != null) {
        for (Map.Entry<String, Class<?>> entry : this.toolAttributes.entrySet()) {
            String attributeName = entry.getKey();
            Class<?> toolClass = entry.getValue();
            try {
                Object tool = toolClass.newInstance();
                initTool(tool, velocityContext);
                velocityContext.put(attributeName, tool);
            }
            catch (Exception ex) {
                throw new NestedServletException("Could not instantiate Velocity tool '" + attributeName + "'", ex);
            }
        }
    }

    // Expose locale-aware DateTool/NumberTool attributes.
    if (this.dateToolAttribute != null || this.numberToolAttribute != null) {
        if (this.dateToolAttribute != null) {
            velocityContext.put(this.dateToolAttribute, new LocaleAwareDateTool(request));
        }
        if (this.numberToolAttribute != null) {
            velocityContext.put(this.numberToolAttribute, new LocaleAwareNumberTool(request));
        }
    }
}
项目:spring-velocity-adapter    文件:VelocityToolboxView.java   
/**
 * Overridden to check for the ViewContext interface which is part of the
 * view package of Velocity Tools. This requires a special Velocity context,
 * like ChainedContext as set up by {@link #createVelocityContext} in this class.
 */
@Override
protected void initTool(Object tool, Context velocityContext) throws Exception {
    // Velocity Tools 1.3: a class-level "init(Object)" method.
    Method initMethod = ClassUtils.getMethodIfAvailable(tool.getClass(), "init", Object.class);
    if (initMethod != null) {
        ReflectionUtils.invokeMethod(initMethod, tool, velocityContext);
    }
}
项目:PrOfESSOS    文件:RPLearningBrowser.java   
private String evalSubmitFormTemplate(String inputName) {
    logger.log("Found input field with name '" + inputName + "'.");

    // eval template
    Reader r = new InputStreamReader(getClass().getResourceAsStream("/submit-form.vlt"), StandardCharsets.UTF_8);
    Context ctx = createRPContext();
    ctx.put("input-field", inputName);
    String result = te.eval(ctx, r);

    logger.log("Created Selenium script based on found input field '" + inputName + "'.");
    logger.log(result);

    return result;
}
项目:Gargoyle    文件:ValueUtil.java   
/**
 * Velocity문법의 텍스트를 맵핑된 텍스트결과값으로 반환
 *
 * @작성자 : KYJ
 * @작성일 : 2015. 10. 22.
 * @param dynamicSql
 * @param paramMap
 * @param replaceNamedValue
 *            namedParameter값을 바인드 변수로 사용하여 보여줄지 유무
 * @param customReplaceFormat
 *            변환할 문자열을 커스텀한 포멧으로 리턴받을 수 있는 기능을 제공하기 위한 파라미터
 * @return
 */
public static String getVelocityToText(String dynamicSql, Map<String, Object> paramMap, boolean replaceNamedValue,
        Context velocityContext, Function<String, String> customReplaceFormat) {
    StringWriter writer = new StringWriter();
    VelocityContext context = new VelocityContext(paramMap, new ExtensionDateFormatVelocityContext(velocityContext));

    String _dynamicSql = dynamicSql;

    Velocity.evaluate(context, writer, "DaoWizard", _dynamicSql);
    String convetedString = writer.toString();
    if (replaceNamedValue) {
        convetedString = replace(convetedString, paramMap, customReplaceFormat);
    }
    return convetedString.trim();
}
项目:spring4-understanding    文件:VelocityLayoutView.java   
/**
 * The resulting context contains any mappings from render, plus screen content.
 */
private void renderScreenContent(Context velocityContext) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("Rendering screen content template [" + getUrl() + "]");
    }

    StringWriter sw = new StringWriter();
    Template screenContentTemplate = getTemplate(getUrl());
    screenContentTemplate.merge(velocityContext, sw);

    // Put rendered content into Velocity context.
    velocityContext.put(this.screenContentKey, sw.toString());
}
项目:spring4-understanding    文件:VelocityView.java   
/**
 * Process the model map by merging it with the Velocity template.
 * Output is directed to the servlet response.
 * <p>This method can be overridden if custom behavior is needed.
 */
@Override
protected void renderMergedTemplateModel(
        Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {

    exposeHelpers(model, request);

    Context velocityContext = createVelocityContext(model, request, response);
    exposeHelpers(velocityContext, request, response);
    exposeToolAttributes(velocityContext, request);

    doRender(velocityContext, response);
}
项目:spring4-understanding    文件:VelocityView.java   
/**
 * Expose the tool attributes, according to corresponding bean property settings.
 * <p>Do not override this method unless for further tools driven by bean properties.
 * Override one of the {@code exposeHelpers} methods to add custom helpers.
 * @param velocityContext Velocity context that will be passed to the template
 * @param request current HTTP request
 * @throws Exception if there's a fatal error while we're adding model attributes
 * @see #setDateToolAttribute
 * @see #setNumberToolAttribute
 * @see #exposeHelpers(Map, HttpServletRequest)
 * @see #exposeHelpers(org.apache.velocity.context.Context, HttpServletRequest, HttpServletResponse)
 */
protected void exposeToolAttributes(Context velocityContext, HttpServletRequest request) throws Exception {
    // Expose generic attributes.
    if (this.toolAttributes != null) {
        for (Map.Entry<String, Class<?>> entry : this.toolAttributes.entrySet()) {
            String attributeName = entry.getKey();
            Class<?> toolClass = entry.getValue();
            try {
                Object tool = toolClass.newInstance();
                initTool(tool, velocityContext);
                velocityContext.put(attributeName, tool);
            }
            catch (Exception ex) {
                throw new NestedServletException("Could not instantiate Velocity tool '" + attributeName + "'", ex);
            }
        }
    }

    // Expose locale-aware DateTool/NumberTool attributes.
    if (this.dateToolAttribute != null || this.numberToolAttribute != null) {
        if (this.dateToolAttribute != null) {
            velocityContext.put(this.dateToolAttribute, new LocaleAwareDateTool(request));
        }
        if (this.numberToolAttribute != null) {
            velocityContext.put(this.numberToolAttribute, new LocaleAwareNumberTool(request));
        }
    }
}