In my Config.groovy I consolidate properties files in the following way:
grails.config.locations << "file:${userHome}/environment.properties" << "file:${userHome}/passwords.properties"
I have two problems:
When autowiring in the Service layer, with GrailsApplication I can retrieve properties defined in Config.groovy BUT NOT those properties defined in the files
I cannot autowire GrailsApplication in my Jobs (using Quartz plugin)
Can anyone shed light on these issues?
What I do is to have an external Config.groovy file, for instance: MyConfig.groovy
At the end of the standard grails Config.groovy file, I have the following:
def ENV_NAME = "MY_EXTERNAL_CONFIG"
if(!grails.config.locations || !(grails.config.locations instanceof List)) {
grails.config.locations = []
}
if(System.getenv(ENV_NAME)) {
grails.config.locations << "file:" + System.getenv(ENV_NAME)
} else if(System.getProperty(ENV_NAME)) {
grails.config.locations << "file:" + System.getProperty(ENV_NAME)
} else {
println "No external Configs found."
}
So now you can have a MyConfig.groovy file anywhere in production environment (for example) and then set an Environment system variable to point to this file (or pass it as parameter to startup.sh), before you start tomcat:
MY_EXTERNAL_CONFIG="/home/tomcat/configs/MyConfig.groovy"
export MY_EXTERNAL_CONFIG
That's it. Now you have an external MyConfig.groovy file. The properties in it are accessible from your grails app as they were part of the standard Config.groovy
import org.codehaus.groovy.grails.commons.*
//...
ConfigurationHolder.config.foo.bar.hello
how about trying this!(just a guess, it should not make any difference! however give it a shot and let me know if doesnt work!)
grails.config.locations = [ "file:${userHome}/environment.properties",
"file:${userHome}/passwords.properties" ]
Related
In our Grails web applications, we'd like to use external configuration files so that we can change the configuration without releasing a new version. We'd also like these files to be outside of the application directory so that they stay unchanged during continuous integration.
The last thing we need to do is to make sure the external configuration files exist. If they don't, then we'd like to create them, fill them with predefined content (production environment defaults) and then use them as if they existed before. This allows any administrator to change settings of the application without detailed knowledge of the options actually available.
For this purpose, there's a couple of files within web-app/WEB-INF/conf ready to be copied to the external configuration location upon the first run of the application.
So far so good. But we need to do this before the application is initialized so that production-related modifications to data sources definitions are taken into account.
I can do the copy-and-load operation inside the Config.groovy file, but I don't know the absolute location of the WEB-INF/conf directory at the moment.
How can I get the location during this early phase of initialization? Is there any other solution to the problem?
There is a best practice for this.
In general, never write to the folder where the application is deployed. You have no control over it. The next rollout will remove everything you wrote there.
Instead, leverage the builtin configuration capabilities the real pro's use (Spring and/or JPA).
JNDI is the norm for looking up resources like databases, files and URL's.
Operations will have to configure JNDI, but they appreciate the attention.
They also need an initial set of configuration files, and be prepared to make changes at times as required by the development team.
As always, all configuration files should be in your source code repo.
I finally managed to solve this myself by using the Java's ability to locate resources placed on the classpath.
I took the .groovy files later to be copied outside, placed them into the grails-app/conf directory (which is on the classpath) and appended a suffix to their name so that they wouldn't get compiled upon packaging the application. So now I have *Config.groovy files containing configuration defaults (for all environments) and *Config.groovy.production files containing defaults for production environment (overriding the precompiled defaults).
Now - Config.groovy starts like this:
grails.config.defaults.locations = [ EmailConfig, AccessConfig, LogConfig, SecurityConfig ]
environments {
production {
grails.config.locations = ConfigUtils.getExternalConfigFiles(
'.production',
"${userHome}${File.separator}.config${File.separator}${appName}",
'AccessConfig.groovy',
'Config.groovy',
'DataSource.groovy',
'EmailConfig.groovy',
'LogConfig.groovy',
'SecurityConfig.groovy'
)
}
}
Then the ConfigUtils class:
public class ConfigUtils {
// Log4j may not be initialized yet
private static final Logger LOG = Logger.getGlobal()
public static def getExternalConfigFiles(final String defaultSuffix, final String externalConfigFilesLocation, final String... externalConfigFiles) {
final def externalConfigFilesDir = new File(externalConfigFilesLocation)
LOG.info "Loading configuration from ${externalConfigFilesDir}"
if (!externalConfigFilesDir.exists()) {
LOG.warning "${externalConfigFilesDir} not found. Creating..."
try {
externalConfigFilesDir.mkdirs()
} catch (e) {
LOG.severe "Failed to create external configuration storage. Default configuration will be used."
e.printStackTrace()
return []
}
}
final def cl = ConfigUtils.class.getClassLoader()
def result = []
externalConfigFiles.each {
final def file = new File(externalConfigFilesDir, it)
if (file.exists()) {
result << file.toURI().toURL()
return
}
final def error = false
final def defaultFileURL = cl.getResource(it + defaultSuffix)
final def defaultFile
if (defaultFileURL) {
defaultFile = new File(defaultFileURL.toURI())
error = !defaultFile.exists();
} else {
error = true
}
if (error) {
LOG.severe "Neither of ${file} or ${defaultFile} exists. Skipping..."
return
}
LOG.warning "${file} does not exist. Copying ${defaultFile} -> ${file}..."
try {
FileUtils.copyFile(defaultFile, file)
} catch (e) {
LOG.severe "Couldn't copy ${defaultFile} -> ${file}. Skipping..."
e.printStackTrace()
return
}
result << file.toURI().toURL()
}
return result
}
}
I am trying to load the properties file externally, by setting up the system environment.
In my config.groovy file,
println "Config file location --->" + System.getenv("SAM_ENV")
grails.config.locations = ["file:"+ System.getenv("SAM_ENV")]
I have set the system env SAM_ENV value as C:\test\config.properties.
When I try to run the application,I am getting the print value as
Config file location ---> C:\test\config.properties prints properly.
The problem is when I try to access the properties file in my controller as
print "PAGINATION1"+grailsApplication.config.PAGINATION1
the value of PAGINATION1 is not getting printed properly.
Can any one help me what configuration has to be done to access the external properties file in grails application.
Add the below line in config.groovy
grails.config.locations = [ "classpath:grails-app-config.properties"]
environments {
development {
grails.logging.jul.usebridge = true
grails.config.locations = ["file:C:\\conf\\externalfile.groovy"]
}
production {
grails.logging.jul.usebridge = false
grails.config.locations = ["file:/opt/config/externalfile.groovy"]
// TODO: grails.serverURL = "http://www.changeme.com"
}
}
If you want to access any property from external configuration(config.groovy) then just declare the property like
property = property value eg:(ImagePath = "C:\\Users\\Saved Pictures")
access it like grailsApplication.config."property"
eg:(grailsApplication.config.ImagePath)
NOTE: dont use def just a property and its value.
What you're looking for is extending the classpath, which you can achieve by adding a post compilation event in _Events.groovy. Try this:
eventCompileEnd = {
ant.copy(todir:classesDirPath) {
fileset(file:"C:\test\config.properties")
}}
You can find more help here
How to update external config files (e.g.: config-ex.groovy, config-ex.properties) without rebuilding the war file in Grails?
Restarting the application server will apply the new updates from external config files.
If I understand well you want to externalized Grails config outside the war.
You can define an external config in your config.groovy like this
grails.config.locations = ["file:path/to/your/Configfile.groovy"]
See the Grails doc 4.4 Externalized Configuration
Define your external Grails config with:
grails.config.locations = ["file:some/path/to/Config.groovy"]
Then to reload them at runtime, you can use code like this:
def config = grailsApplication.config
def locations = config.grails.config.locations
locations.each {
String configFileName = it.split('file:')[0]
config.merge(new ConfigSlurper().parse(new File(configFileName).text))
}
I have the above code in an admin protected Controller.
Went around the houses for this one, thanks Gregg
For services or groovy src files you could use:
import org.springframework.context.ApplicationContext
ApplicationContext ctx = (ApplicationContext) org.codehaus.groovy.grails.web.context.ServletContextHolder.getServletContext().getAttribute(org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes.APPLICATION_CONTEXT);
def grailsApplication = ctx.getBean("grailsApplication")
ConfigObject config = ctx.getBean(GrailsApplication).config
def locations = config.grails.config.locations
locations.each {
String configFileName = it.split("file:")[1]
config.merge(new ConfigSlurper().parse(new File(configFileName).text))
}
And for abstract classes that are typically extended from controllers:
import grails.util.Holders
def config = Holders.config
def locations = config.grails.config.locations
locations.each {
String configFileName = it.split("file:")[1]
config.merge(new ConfigSlurper().parse(new File(configFileName).text))
}
I have an application where the config is externalized. In Config.groovy, I'm updating
grails.config.locations=[file:/.../myapp-log4j.groovy, file:/.../myapp-config.properties]
That works fine for datasources and such. But later in Config.groovy, I have:
springws {
wsdl {
MyApp {
// In this case the wsdl will be available at <grails.serverURL>/services/v1/myapp/myapp-v1.wsdl
wsdlName= 'myapp-v1'
xsds= '/WEB-INF/myapp.xsd'
portTypeName = 'myappPort'
serviceName = 'myappService'
locationUri = "${grails.serverURL}/services/v1/myapp"
targetNamespace = 'http://www..../myapp/v1/definitions'
}
}
}
And ${grails.serverURL} contains [:] which is not what is in my config file. The config file contains (among the datasource details):
grails.serverURL=http://samiel:9011/xid
My guess would be that the updated grails.config.locations is only used after I return from Config.groovy.
So, what are my options to setup my web service details based on the externalized serverURL ?
This is what I get when I run your example (just confirming your starting postion):
def testExternalConfig() {
println "grails.serverURL: ${ConfigurationHolder.config.grails.serverURL}"
println "springws.wsdl.MyApp.locationUri ${ConfigurationHolder.config.springws.wsdl.MyApp.locationUri}"
}
--Output from testExternalConfig--
grails.serverURL: http://samiel:9011/xid
springws.wsdl.MyApp.locationUri http://localhost:8080/soGrails/services/v1/myapp
Like you said, Config.groovy does not see the value set in the external config. I believe that Grails processes external
configs after Config.groovy, and this test appears to confirm that. The logic being that you likely have external config file
values that you want to have precedence over config in war file.
Fix is to override the full property in myapp-config.properties:
grails.serverURL=http://samiel:9011/xid
springws.wsdl.MyApp.locationUri=http://samiel:9011/xid/services/v1/myapp
With that change I get this:
--Output from testExternalConfig--
grails.serverURL: http://samiel:9011/xid
springws.wsdl.MyApp.locationUri http://samiel:9011/xid/services/v1/myapp
I want to add linux based or windows based system properties in Grails as my app needs to run in the both. I know that we can add grails.config.locations location specified in Config. groovy.
But I need the if and esle condition for the file to be picked.
the problem is config.grrovy has userHome grailsHome appName appVersion
I would need something like osName.
Either I can go ahead with syetm.properties or if soembody can tell me how these (only) properties are availble in Config.groovy (through DefaultGrailsApplication or otherwise. that woyuld be great.
Also, somewjhat moer elegant would be if where I need those properties I make my service as user-defined-spring-bean. Would that be right and feasible approach?If yes, some example
You could do something like this in your Config.groovy:
environments {
development {
if (System.properties["os.name"] == "Linux") {
grails.config.locations = [ "file:$basedir/grails-app/conf/linux.properties" ]
} else {
grails.config.locations = [ "file:$basedir/grails-app/conf/windows.properties" ]
}
}
...
}
Alternatively, for a service based approach, you could bundle up all the OS specific behavior into implementations of service interface. For example:
// OsPrinterService.groovy
interface OsPrinterService {
void printOs();
}
// LinuxOsPrinterService.groovy
class LinuxOsPrinterService implements OsPrinterService {
void printOs() { println "Linux" }
}
// WindowsOsPrinterService.groovy
class WindowsOsPrinterService implements OsPrinterService {
void printOs() { println "Windows" }
}
Then instantiate the correct one in grails-app/conf/spring/resources.groovy like so:
beans = {
if (System.properties["os.name"] == "Linux") {
osPrinterService(LinuxOsPrinterService) {}
} else {
osPrinterService(WindowsOsPrinterService) {}
}
}
Then the correct service will be automatically injected into your objects by spring.
Create a custom enviorenment for both Windows and Linux. Something like the following should work if placed in config.groovy
environments {
productionWindows {
filePath=c:\path
}
productionLinux {
filePath=/var/dir
}
}
You should then be able to use the grails config object to get the value of filePath reguardless of weather your on Windows or Linux. For more details on this see section 3.2 of
http://www.grails.org/doc/1.0.x/guide/3.%20Configuration.html If you wanted to create a war file to run on Linux you would execute the following command.
grails -Dgrails.env=productionLinux war
And then to get a file path you stored in config.groovy for the specific environment your running in.
def fileToOpen=Conf.config.filePath
fileToOpen will contain the value you assigned to filePath in your config.groovy based on the environment your currently running as, so when running with productionLinux as the environment it will contain the value /var/dir