All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.mysema.commons.freemarker.MessageDirective Maven / Gradle / Ivy

There is a newer version: 0.2.4
Show newest version
/*
 * Copyright (c) 2009 Mysema Ltd.
 * All rights reserved.
 * 
 */
package com.mysema.commons.freemarker;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * MessageDirective GXP (Google XML Pages) like message localization
 *
 * @author tiwe
 * @version $Id$
 */
public class MessageDirective  extends FreeMarkerHelper {

    private MessageSource messageSource;
    
    // TODO : take optional context extra parameter
    
    @SuppressWarnings("unchecked")
    public void execute(Environment env, Map params, TemplateModel[] loopVars,
            TemplateDirectiveBody body) throws TemplateException, IOException {
        HttpServletRequest req = getRequest(env);
        StringWriter writer = new StringWriter();
        body.render(writer);        
        String output;
        // TODO : cache lookup results
        try{
            output = messageSource.getMessage(writer.toString(), new Object[0], req.getLocale());    
        }catch(NoSuchMessageException nsme){
            output = writer.toString();
        }
        env.getOut().write(output);        
    }

    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }
    
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy