Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Groovy Script Config Source for Ratpack
package app
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ObjectNode
import com.google.common.io.ByteSource
import com.google.common.io.Resources
import ratpack.config.ConfigSource
import ratpack.file.FileSystemBinding
import java.nio.file.Files
import java.nio.file.Path
import static com.google.common.base.Preconditions.checkNotNull
class ConfigSlurperConfigSource implements ConfigSource {
private final String script
private final ConfigSlurper configSlurper
private ConfigSlurperConfigSource(ByteSource byteSource, String env) {
this(byteSource, new ConfigSlurper(env))
}
private ConfigSlurperConfigSource(ByteSource byteSource, ConfigSlurper configSlurper = new ConfigSlurper()) {
this.script = new String(byteSource.openStream().bytes)
this.configSlurper = configSlurper
}
@Override
ObjectNode loadConfigData(ObjectMapper mapper, FileSystemBinding fileSystemBinding) throws Exception {
def configObject = configSlurper.parse(script) as Map
mapper.convertValue(configObject, ObjectNode)
}
static ConfigSource groovyConfig(String path, String env = '') {
{ mapper, fileSystemBinding ->
new ConfigSlurperConfigSource(asPathByteSource(fileSystemBinding.file(path)), env)
.loadConfigData(mapper, fileSystemBinding)
}
}
static ConfigSource groovyConfig(Path path, String env = '') {
{ mapper, fileSystemBinding ->
new ConfigSlurperConfigSource(asPathByteSource(path), env)
.loadConfigData(mapper, fileSystemBinding)
}
}
static ConfigSource groovyConfig(URL url, String env = '') {
{ mapper, fileSystemBinding ->
new ConfigSlurperConfigSource(Resources.asByteSource(url), env)
.loadConfigData(mapper, fileSystemBinding)
}
}
private static ByteSource asPathByteSource(Path path) {
new PathByteSource(path)
}
private static class PathByteSource extends ByteSource {
private final Path path
private PathByteSource(Path path) {
this.path = checkNotNull(path)
}
@Override
public InputStream openStream() throws IOException {
Files.newInputStream(path);
}
@Override
public long size() throws IOException {
Files.size(path)
}
@Override
public byte[] read() throws IOException {
Files.readAllBytes(path)
}
}
}
app {
name = 'my awesome app'
}
environments {
development {
server {
port = 9999
}
}
production {
app {
name = 'my production app'
}
server {
port = 80
}
}
}
import static app.ConfigSlurperConfigSource.groovyConfig
import static ratpack.groovy.Groovy.ratpack
def environment = System.getProperty("env", "development")
ratpack {
serverConfig {
add(groovyConfig("config.groovy", environment))
sysProps()
env()
}
handlers {
get {
render "Hello World! - ${serverConfig.get('/app', Map).name}"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment