Showing posts with label new resource. Show all posts
Showing posts with label new resource. Show all posts

Friday, July 31, 2015

Grails Add New Resources To MessageSource Dynamically


First create a groovy file with the following contents

package com.pkm.message.test

import grails.util.Environment
import javax.servlet.ServletContext

class MessageSourceCreator {
    public static def grailsApplication = null
    public static def servletContext = null
    public static def messageSource = null
    private static final String MESSAGE_FILE_DIR = "/WEB-INF/resources/messages"

    /**
     * @param fileName "some.message.properties"
     */
    public static void addNewMessageFile(String fileName) {
        String basePath = servletContext.getRealPath("/")
        fileName = fileName.substring(0, fileName.lastIndexOf("."))
        String relativeFilePath = "${MESSAGE_FILE_DIR}/${fileName}"

        if (Environment.isWarDeployed()) {
            messageSource.pluginBaseNames.add(0, relativeFilePath)
        } 
        else {
            String separator = Environment.current == Environment.TEST ? "/" : ""
            messageSource.pluginBaseNames.add(0, basePath + separator + relativeFilePath)
        }
    }

    public static void initialize(def ga, def sc, def ms) {
        grailsApplication = ga
        servletContext = sc
        messageSource = ms
    }
}



From BootStrap, need to call first initialize & then addNewMessageFile


/**
 * From BootStrap, need to call first initialize & then addNewMessageFile
 */
import com.pkm.message.test.MessageSourceCreator

class BootStrap {
    def grailsApplication
    def servletContext
    def messageSource

    def init = { servletContext ->
        MessageSourceCreator.initialize(grailsApplication, servletContext, messageSource)
        MessageSourceCreator.addNewMessageFile("some.message.properties")
    }

    def destroy = {

    }
}