Java Code Examples for org.apache.velocity.context.Context

The following examples show how to use org.apache.velocity.context.Context. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: lams   Source File: VelocityLayoutView.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 2
Source Project: velocity-engine   Source File: EvaluateTestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test that the event handlers work in #evaluate (since they are
 * attached to the context).  Only need to check one - they all
 * work the same.
 * @throws Exception
 */
public void testEventHandler()
throws Exception
{
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.EVENTHANDLER_REFERENCEINSERTION, EscapeHtmlReference.class.getName());
    ve.init();

    Context context = new VelocityContext();
    context.put("lt","<");
    context.put("gt",">");
    StringWriter writer = new StringWriter();
    ve.evaluate(context, writer, "test","${lt}test${gt} #evaluate('${lt}test2${gt}')");
    assertEquals("&lt;test&gt; &lt;test2&gt;", writer.toString());

}
 
Example 3
Source Project: lams   Source File: VelocityView.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 4
Source Project: scoold   Source File: VelocityLayoutView.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 5
Source Project: velocity-engine   Source File: IncludeErrorTestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Check that an exception is thrown for the given template
 * @param templateName
 * @param exceptionClass
 * @throws Exception
 */
private void checkException(String templateName,Class exceptionClass)
throws Exception
{
    Context context = new VelocityContext();
    Template template = ve.getTemplate(templateName, "UTF-8");

    try (StringWriter writer = new StringWriter())
    {
        template.merge(context, writer);
        writer.flush();
        fail("File should have thrown an exception");
    }
    catch (Exception E)
    {
        assertTrue(exceptionClass.isAssignableFrom(E.getClass()));
    }

}
 
Example 6
Source Project: opoopress   Source File: VelocityRenderer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String render(Page base, Object rootMap) {
    Context context = convert(rootMap);

    String content = base.getContent();
    String layout = base.getLayout();

    boolean isContentRenderRequired = isRenderRequired(site, base, content);
    boolean isValidLayout = isValidLayout(layout);

    if (isContentRenderRequired) {
        content = renderContent(content, context);
    }

    if (isValidLayout) {
        context.put("content", content);
        content = render("_" + layout + ".vm", context);
    } else {
        //do nothing
        //content = content;
    }

    return content;
}
 
Example 7
Source Project: spring4-understanding   Source File: VelocityLayoutView.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 8
public boolean invalidSetMethod(Context context, String leftreference, String rightreference, Info info)
{

    // as a test, make sure this EventHandler is initialized
    if (rs == null)
        fail ("Event handler not initialized!");

    // good object, bad method
    if (leftreference.equals("xx"))
    {
        assertEquals("q1.afternoon()",rightreference);
        throw new RuntimeException("expected exception");
    }
    if (leftreference.equals("yy"))
    {
        assertEquals("$q1",rightreference);
        throw new RuntimeException("expected exception");
    }
    else
    {
        fail("Unexpected left hand side.  " + leftreference);
    }

    return false;
}
 
Example 9
Source Project: velocity-tools   Source File: ContextTool.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Actually do the work of filling in the set of keys
 * for {@link #getKeys} here so subclasses can add keys too.
 * @param keys set to fill with keys
 */
protected void fillKeyset(Set keys)
{
    //NOTE: we don't need to manually add the toolbox keys here
    //      because retrieval of those depends on the context being
    //      a ToolContext which would already give tool keys below

    // recurse down the velocity context collecting keys
    Context velctx = this.context;
    while (velctx != null)
    {
        Object[] ctxKeys = velctx.getKeys();
        keys.addAll(Arrays.asList(ctxKeys));
        if (velctx instanceof AbstractContext)
        {
            velctx = ((AbstractContext)velctx).getChainedContext();
        }
        else
        {
            velctx = null;
        }
    }
}
 
Example 10
@Override
public String render(Object object, String velocityTemplate) {
	String renderedObject = null;
	try {
		Context velocityContext = new VelocityContext();
		velocityContext.put(this.getWrapperContextName(), object);
		StringWriter stringWriter = new StringWriter();
		boolean isEvaluated = Velocity.evaluate(velocityContext, stringWriter, "render", velocityTemplate);
		if (!isEvaluated) {
			throw new ApsSystemException("Rendering error");
		}
		stringWriter.flush();
		renderedObject = stringWriter.toString();
	} catch (Throwable t) {
		_logger.error("Rendering error, class: {} - template: {}", object.getClass().getSimpleName(), velocityTemplate, t);
		//ApsSystemUtils.logThrowable(t, this, "render", "Rendering error");
		renderedObject = "";
	}
	return renderedObject;
}
 
Example 11
Source Project: velocity-engine   Source File: PrintExceptions.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Render the method exception, and optionally the exception message and stack trace.
 *
 * @param context current context
 * @param claz the class of the object the method is being applied to
 * @param method the method
 * @param e the thrown exception
 * @param info template name and line, column informations
 * @return an object to insert in the page
 */
public Object methodException(Context context, Class claz, String method, Exception e, Info info)
{
    boolean showTemplateInfo = rs.getBoolean(SHOW_TEMPLATE_INFO, false);
    boolean showStackTrace = rs.getBoolean(SHOW_STACK_TRACE,false);

    StringBuilder st = new StringBuilder();
    st.append("Exception while executing method ").append(claz.toString()).append(".").append(method);
    st.append(": ").append(e.getClass().getName()).append(": ").append(e.getMessage());

    if (showTemplateInfo)
    {
        st.append(" at ").append(info.getTemplateName()).append(" (line ").append(info.getLine()).append(", column ").append(info.getColumn()).append(")");
    }
    if (showStackTrace)
    {
        st.append(System.lineSeparator()).append(getStackTrace(e));
    }
    return st.toString();

}
 
Example 12
Source Project: velocity-engine   Source File: WrappedExceptionTestCase.java    License: Apache License 2.0 6 votes vote down vote up
public void testMethodException() throws Exception
{

    // accumulate a list of invalid references
    Context context = new VelocityContext();
    StringWriter writer = new StringWriter();
    context.put("test",new TestProvider());

    try
    {
        ve.evaluate(context,writer,"test","$test.getThrow()");
        fail ("expected an exception");
    }
    catch (MethodInvocationException E)
    {
        assertEquals(Exception.class,E.getCause().getClass());
        assertEquals("From getThrow()",E.getCause().getMessage());
    }

}
 
Example 13
Source Project: velocity-tools   Source File: RenderTool.java    License: Apache License 2.0 6 votes vote down vote up
protected String internalEval(Context ctx, String vtl) throws Exception
{
    if (vtl == null)
    {
        return null;
    }
    StringWriter sw = new StringWriter();
    boolean success;
    if (engine == null)
    {
        success = Velocity.evaluate(ctx, sw, "RenderTool.eval()", vtl);
    }
    else
    {
        success = engine.evaluate(ctx, sw, "RenderTool.eval()", vtl);
    }
    if (success)
    {
        return sw.toString();
    }
    /* or would it be preferable to return the original? */
    return null;
}
 
Example 14
Source Project: spring4-understanding   Source File: VelocityMacroTests.java    License: Apache License 2.0 6 votes vote down vote up
@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));
	}
}
 
Example 15
/**
 * Get the context of a robot component with all it's properties filled in.
 *
 * @param comp The component to base the context off of.
 * @return The context, which also inherits from the rootContext
 */
private Context getContext(RobotComponent comp) {
    Context context = new VelocityContext(rootContext);
    final Map<String, String> instructions = componentInstructions.get(comp.getBase().getName());
    context.put("ClassName", instructions.get("ClassName"));
    context.put("Name", comp.getName());
    context.put("Short_Name", comp.getName());
    if (!comp.getSubsystem().isEmpty()) {
        context.put("Subsystem", comp.getSubsystem().substring(0, comp.getSubsystem().length() - 1));
    }
    context.put("Component", comp);
    for (String property : comp.getPropertyKeys()) {
        context.put(property.replace(" ", "_").replace("(", "").replace(")", ""),
                comp.getProperty(property).getValue());
    }
    return context;
}
 
Example 16
public String render(DataObject dataobject, String contentModel, String langCode, RequestContext reqCtx) {
    String renderedEntity;
    try {
        Context velocityContext = new VelocityContext();
        DataObjectWrapper contentWrapper = (DataObjectWrapper) this.getEntityWrapper(dataobject);
        contentWrapper.setRenderingLang(langCode);
        velocityContext.put("data", contentWrapper);
        I18nManagerWrapper i18nWrapper = new I18nManagerWrapper(langCode, this.getI18nManager());
        velocityContext.put("i18n", i18nWrapper);
        SystemInfoWrapper systemInfoWrapper = new SystemInfoWrapper(reqCtx);
        velocityContext.put("info", systemInfoWrapper);
        StringWriter stringWriter = new StringWriter();
        boolean isEvaluated = Velocity.evaluate(velocityContext, stringWriter, "render", contentModel);
        if (!isEvaluated) {
            throw new ApsSystemException("Error rendering DataObject");
        }
        stringWriter.flush();
        renderedEntity = stringWriter.toString();
    } catch (Throwable t) {
        logger.error("Error rendering dataobject", t);
        renderedEntity = "";
    }
    return renderedEntity;
}
 
Example 17
private void doTestMethods(VelocityEngine ve, String[] templateStrings, boolean shouldeval)
{
    Context c = new VelocityContext();
    c.put("test", this);

    try
    {
        for (String templateString : templateStrings)
        {
            if (shouldeval && !doesStringEvaluate(ve, c, templateString))
            {
                fail("Should have evaluated: " + templateString);
            }

            if (!shouldeval && doesStringEvaluate(ve, c, templateString))
            {
                fail("Should not have evaluated: " + templateString);
            }
        }

    }
    catch (Exception e)
    {
        fail(e.toString());
    }
}
 
Example 18
Source Project: velocity-tools   Source File: RenderTool.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sets the {@link Context} to be used by the {@link #eval(String)}
 * and {@link #recurse(String)} methods.
 * @param context Velocity context
 */
public void setVelocityContext(Context context)
{
    if (!isConfigLocked())
    {
        if (context == null)
        {
            throw new NullPointerException("context must not be null");
        }
        this.context = context;
    }
    else if (this.context != context)
    {
        getLog().error("Attempt was made to set a new context while config was locked.");
    }
}
 
Example 19
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);

}
 
Example 20
Source Project: velocity-engine   Source File: ExceptionTestCase.java    License: Apache License 2.0 5 votes vote down vote up
public void assertException(VelocityEngine ve, String input)
throws Exception
{
    Context context = new VelocityContext();
    context.put ("test","test");
    assertException(ve,context,input);
}
 
Example 21
Source Project: cloudbreak   Source File: AmbariViewResponse.java    License: Apache License 2.0 5 votes vote down vote up
public AmbariViewResponse(String mockServerAddress) {
    Context c = new VelocityContext();
    c.put("mockServerAddress", mockServerAddress);
    StringWriter sw = new StringWriter();
    TEMPLATE.merge(c, sw);
    ambariViewJson = sw.toString();
}
 
Example 22
Source Project: velocity-engine   Source File: ExceptionTestCase.java    License: Apache License 2.0 5 votes vote down vote up
public void assertException(VelocityEngine ve)
throws Exception
{
    Context context = new VelocityContext();
    context.put ("test","test");
    assertException(ve,context,"this is a $test");
}
 
Example 23
Source Project: java-course-ee   Source File: Test4.java    License: MIT License 5 votes vote down vote up
public Test4() throws Exception {

        Velocity.init("src/main/java/velocity.properties");
        // get Template
        Template template = Velocity.getTemplate("Test4.vm");
        // getContext
        Context context = new VelocityContext();

        int a = 3;
        int b = 5;

        String s1 = "Hello";
        String s2 = "World";

        context.put("a", a);
        context.put("b", b);
        context.put("s1", s1);
        context.put("s2", s2);

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

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

    }
 
Example 24
Source Project: quartz-glass   Source File: VelocityTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void equals() {
    Context context = new VelocityContext();
    context.put("value", new Dummy("hi"));
    context.put("message", "hi");

    Assert.assertEquals(" hi ", merge("/org/n3r/quartz/glass/velocity/velocity-test-equals.vm", context));
}
 
Example 25
Source Project: qemu-java   Source File: SchemaWriter.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void run() throws IOException {
    File outputPackageDir = new File(outputDir, packageName.replace('.', '/'));
    outputPackageDir.mkdirs();
    for (QApiElementDescriptor element : model.elements.values()) {
        Context context = toolManager.createContext();
        Template template = engine.getTemplate("/velocity/" + element.getTemplateName() + ".vm");
        context.put("packageName", packageName);
        context.put("element", element);
        File outputFile = new File(outputPackageDir, element.getClassName() + ".java");
        FileWriter writer = new FileWriter(outputFile);
        template.merge(context, writer);
        writer.close();
    }
}
 
Example 26
Source Project: velocity-engine   Source File: EventCartridge.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Call invalid reference handlers for an invalid setter
 *
 * @param context
 * @param leftreference
 * @param rightreference
 * @param info
 * @return whether to stop further chaining in the next cartridge
 * @since 2.0
 */
public boolean invalidSetMethod(Context context, String leftreference, String rightreference, Info info)
{
    for (InvalidReferenceEventHandler handler : invalidReferenceHandlers)
    {
        if (handler.invalidSetMethod(context, leftreference, rightreference, info))
        {
            return true;
        }
    }
    return false;
}
 
Example 27
@Override
public String render(IApsEntity entity, String velocityTemplate, String langCode, boolean convertSpecialCharacters) {
	String renderedEntity = null;
	List<TextAttributeCharReplaceInfo> conversions = null;
	try {
		if (convertSpecialCharacters) {
			conversions = this.convertSpecialCharacters(entity, langCode);
		}
		Context velocityContext = new VelocityContext();
		EntityWrapper entityWrapper = this.getEntityWrapper(entity);
		entityWrapper.setRenderingLang(langCode);
		velocityContext.put(this.getEntityWrapperContextName(), entityWrapper);

		I18nManagerWrapper i18nWrapper = new I18nManagerWrapper(langCode, this.getI18nManager());
		velocityContext.put("i18n", i18nWrapper);
		StringWriter stringWriter = new StringWriter();
		boolean isEvaluated = Velocity.evaluate(velocityContext, stringWriter, "render", velocityTemplate);
		if (!isEvaluated) {
			throw new ApsSystemException("Rendering error");
		}
		stringWriter.flush();
		renderedEntity = stringWriter.toString();
	} catch (Throwable t) {
		_logger.error("Rendering error. entity {}", entity.getTypeCode(), t);
		//ApsSystemUtils.logThrowable(t, this, "render", "Rendering error");
		renderedEntity = "";
	} finally {
		if (convertSpecialCharacters && null != conversions) {
			this.replaceSpecialCharacters(conversions);
		}
	}
	return renderedEntity;
}
 
Example 28
Source Project: velocity-tools   Source File: VelocityPageContext.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param velocityContext The Velocity context.
 * @param velocityWriter The writer to be used when writing content.
 * @param viewContext The View context.
 */
public VelocityPageContext(Context velocityContext, Writer velocityWriter, ViewContext viewContext)
{
 this.velocityContext = velocityContext;
 this.velocityWriter = velocityWriter;
 this.viewContext = viewContext;
 this.request = viewContext.getRequest();
 this.response = viewContext.getResponse();
    jspWriter = new JspWriterImpl(velocityWriter);
    velocityContext.put("out", jspWriter);
}
 
Example 29
private Context newEscapeContext()
{
    Context context = new VelocityContext();
    context.put("test1","Jimmy's <b>pizza</b>");
    context.put("test1_js","Jimmy's <b>pizza</b>");
    context.put("test1_js_test","Jimmy's <b>pizza</b>");
    return context;
}
 
Example 30
Source Project: spring4-understanding   Source File: VelocityLayoutView.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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());
}