Java Code Examples for freemarker.core.Environment#process()

The following examples show how to use freemarker.core.Environment#process() . 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 check out the related API usage on the sidebar.
Example 1
Source File: FreeMarkerWorker.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * Renders a Template instance.
 * SCIPIO: NOTE: It's important that template renders go through this method in order to record the Environment for contexts where it's not otherwise accessible.
 * @param template A Template instance
 * @param context The context Map
 * @param outWriter The Writer to render to
 * @param autoFlush SCIPIO: if null, use default auto-flush setting; true/false enables/disables
 */
public static Environment renderTemplate(Template template, Map<String, Object> context, Appendable outWriter, Boolean autoFlush) throws TemplateException, IOException {
    // SCIPIO: 2015-12-15: we want a patch around the processing code to remove our saved copy of
    // the FTL environment. within this call we know that FTL will store its own environment and make accessible via
    // Environment.getCurrentEnvironment().
    // ideally we want at most one of the two to be non-null at any given time.
    // this method is the best effort we can do to try to enforce that.
    // @see FreeMarkerWorker#getCurrentEnvironment
    Environment savedEnv = threadEnv.get();
    threadEnv.set(null);
    try {
        // make sure there is no "null" string in there as FreeMarker will try to use it
        context.remove("null");
        // Since the template cache keeps a single instance of a Template that is shared among users,
        // and since that Template instance is immutable, we need to create an Environment instance and
        // use it to process the template with the user's settings.
        //
        // FIXME: the casting from Appendable to Writer is a temporary fix that could cause a
        //        run time error if in the future we will pass a different class to the method
        //        (such as a StringBuffer).
        Environment env = template.createProcessingEnvironment(context, (Writer) outWriter);
        applyUserSettings(env, context, autoFlush);
        env.process();
        return env;
    }
    finally {
        threadEnv.set(savedEnv);
    }
}
 
Example 2
Source File: TestWBFreeMarkerTemplateEngine.java    From cms with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressStaticInitializationFor("WBFreeMarkerTemplateEngine.class")
@PrepareForTest({Environment.class, WPBFreeMarkerTemplateEngine.class})
public void process_ok_no_messages()
{
	try
	{
		WPBFreeMarkerTemplateEngine templateEngine = new WPBFreeMarkerTemplateEngine(cacheInstancesMock);
		Whitebox.setInternalState(templateEngine, "configuration", configurationMock);
		String nameTemplate = "textXYZ";
		Map rootMap = new HashMap();
		rootMap.put(WPBModel.LOCALE_LANGUAGE_KEY, "en");
		Writer out = new StringWriter();
		
		Template templateMock = PowerMock.createMock(Template.class);
		EasyMock.expect(configurationMock.getTemplate(nameTemplate)).andReturn(templateMock);
		
		Locale locale = new Locale("en");
		CmsResourceBundle resourceBundleMock = PowerMock.createMock(CmsResourceBundle.class);
		EasyMock.expect(freeMarkerFactoryMock.createResourceBundle(EasyMock.anyObject(WPBMessagesCache.class), EasyMock.anyObject(Locale.class))).andReturn(resourceBundleMock);
		
		Environment envMock = PowerMock.createMock(Environment.class);
		EasyMock.expect(templateMock.createProcessingEnvironment(rootMap, out)).andReturn(envMock);
			
		envMock.process();
		Whitebox.setInternalState(templateEngine, "wbFreeMarkerFactory", freeMarkerFactoryMock);
		
		PowerMock.replay(cloudFileStorageMock, envMock, templateMock, resourceBundleMock, cacheFactoryMock, freeMarkerFactoryMock, configurationMock, templateLoaderMock, moduleDirectiveMock, messageCacheMock);
	
		templateEngine.process(nameTemplate, rootMap, out);
		
		PowerMock.verify(cloudFileStorageMock, envMock, templateMock, resourceBundleMock, cacheFactoryMock, freeMarkerFactoryMock, configurationMock, templateLoaderMock, moduleDirectiveMock, messageCacheMock);

		assertTrue (rootMap.containsKey(WPBModel.LOCALE_MESSAGES));
	} catch (Exception e)
	{
		assertTrue (false);
	}
	
}
 
Example 3
Source File: TestWBFreeMarkerTemplateEngine.java    From cms with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressStaticInitializationFor("WBFreeMarkerTemplateEngine.class")
@PrepareForTest({Environment.class, WPBFreeMarkerTemplateEngine.class})
public void process_ok_with_messages()
{
	try
	{
		WPBFreeMarkerTemplateEngine templateEngine = new WPBFreeMarkerTemplateEngine(cacheInstancesMock);
		Whitebox.setInternalState(templateEngine, "configuration", configurationMock);
		String nameTemplate = "textXYZ";
		Map rootMap = new HashMap();
		rootMap.put(WPBModel.LOCALE_LANGUAGE_KEY, "en");
		rootMap.put(WPBModel.LOCALE_MESSAGES, new Object());
		
		Writer out = new StringWriter();
		
		Template templateMock = PowerMock.createMock(Template.class);
		EasyMock.expect(configurationMock.getTemplate(nameTemplate)).andReturn(templateMock);
		
		
		Environment envMock = PowerMock.createMock(Environment.class);
		EasyMock.expect(templateMock.createProcessingEnvironment(rootMap, out)).andReturn(envMock);
			
		envMock.process();
		Whitebox.setInternalState(templateEngine, "wbFreeMarkerFactory", freeMarkerFactoryMock);
		
		PowerMock.replay(cloudFileStorageMock, envMock, templateMock, cacheFactoryMock, freeMarkerFactoryMock, configurationMock, templateLoaderMock, moduleDirectiveMock, messageCacheMock);
	
		templateEngine.process(nameTemplate, rootMap, out);
		
		PowerMock.verify(cloudFileStorageMock, envMock, templateMock, cacheFactoryMock, freeMarkerFactoryMock, configurationMock, templateLoaderMock, moduleDirectiveMock, messageCacheMock);

		assertTrue (rootMap.containsKey(WPBModel.LOCALE_MESSAGES));
	} catch (Exception e)
	{
		assertTrue (false);
	}
	
}
 
Example 4
Source File: FreeMarkerProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.repository.TemplateProcessor#process(java.lang.String, java.lang.Object, java.io.Writer)
 */
public void process(String template, Object model, Writer out)
{
    if (template == null || template.length() == 0)
    {
        throw new IllegalArgumentException("Template name is mandatory.");
    }
    if (model == null)
    {
        throw new IllegalArgumentException("Model is mandatory.");
    }
    if (out == null)
    {
        throw new IllegalArgumentException("Output Writer is mandatory.");
    }
    
    try
    {
        long startTime = 0;
        if (logger.isDebugEnabled())
        {
            logger.debug("Executing template: " + template);// + " on model: " + model);
            startTime = System.currentTimeMillis();
        }
        
        Template t = getConfig().getTemplate(template);
        if (t != null)
        {
            try
            {
                // perform the template processing against supplied data model
                Object freeMarkerModel = convertToFreeMarkerModel(model);
                Environment env = t.createProcessingEnvironment(freeMarkerModel, out);
                // set the locale to ensure dates etc. are appropriate localised
                env.setLocale(I18NUtil.getLocale());
                env.process();
            }
            catch (Throwable err)
            {
                throw new TemplateException(MSG_ERROR_TEMPLATE_FAIL, new Object[] {err.getMessage()}, err);
            }
        }
        else
        {
            throw new TemplateException(MSG_ERROR_NO_TEMPLATE, new Object[] {template});
        }
        
        if (logger.isDebugEnabled())
        {
            long endTime = System.currentTimeMillis();
            logger.debug("Time to execute template: " + (endTime - startTime) + "ms");
        }
    }
    catch (IOException ioerr)
    {
        throw new TemplateException(MSG_ERROR_TEMPLATE_IO, new Object[] {template}, ioerr);
    }
}
 
Example 5
Source File: FreeMarkerProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.repository.TemplateProcessor#process(java.lang.String, java.lang.Object, java.io.Writer, java.util.Locale)
 */
public void process(String template, Object model, Writer out, Locale locale)
{
    if (template == null || template.length() == 0)
    {
        throw new IllegalArgumentException("Template name is mandatory.");
    }
    if (model == null)
    {
        throw new IllegalArgumentException("Model is mandatory.");
    }
    if (out == null)
    {
        throw new IllegalArgumentException("Output Writer is mandatory.");
    }
    if (locale == null)
    {
        throw new IllegalArgumentException("Locale is mandatory.");
    }
    
    try
    {
        long startTime = 0;
        if (logger.isDebugEnabled())
        {
            logger.debug("Executing template: " + template);// + " on model: " + model);
            startTime = System.currentTimeMillis();
        }
        
        Template t = getConfig().getTemplate(template, locale);
        if (t != null)
        {
            try
            {
                // perform the template processing against supplied data model
                Object freeMarkerModel = convertToFreeMarkerModel(model);
                Environment env = t.createProcessingEnvironment(freeMarkerModel, out);
                // set the locale to ensure dates etc. are appropriate localised
                env.setLocale(locale);
                env.process();
            }
            catch (Throwable err)
            {
                throw new TemplateException(MSG_ERROR_TEMPLATE_FAIL, new Object[] {err.getMessage()}, err);
            }
        }
        else
        {
            throw new TemplateException(MSG_ERROR_NO_TEMPLATE, new Object[] {template});
        }
        
        if (logger.isDebugEnabled())
        {
            long endTime = System.currentTimeMillis();
            logger.debug("Time to execute template: " + (endTime - startTime) + "ms");
        }
    }
    catch (IOException ioerr)
    {
        throw new TemplateException(MSG_ERROR_TEMPLATE_IO, new Object[] {template}, ioerr);
    }
}