Introduction
Sometimes you need to write code snippet logic that can be modified on the fly or customized by users without recompiling your main application. In Java environments, Groovy is an excellent choice for this capability. The following example demonstrates creating a small Groovy script that can be embedded into Java applications or invoked from tools like JMeter, Jenkins, and shell scripts.
NOTE: Ensure the Groovy framework is included in your classpath or configured via Maven/Gradle when compiling and running Java code.
Process
- Create a small Groovy script to generate random Spanish national ID numbers (DNI). Because it is simple and interpreted dynamically, it can be updated on disk even after packaging the main Java application:
/**
* Spanish ID generator on the fly
*
* @param withTimestamp If true, use the current timestamp to generate the DNI number
* @return valid Spanish ID as a string
*/
def randomDni(boolean withTimestamp = true) {
def possibleLetters = ["T", "R", "W", "A", "G", "M", "Y", "F", "P", "D", "X", "B", "N", "J", "Z", "S", "Q", "V", "H", "L", "C", "K", "E", "T"]
Random rand = new Random()
def dniNumber = Integer.valueOf(new Date().getTime().toString().substring(2, 10))
if (!withTimestamp) {
def lowerLimit = 10000000
def upperLimit = 99999999
dniNumber = Math.abs(rand.nextInt() % (upperLimit - lowerLimit) + lowerLimit)
}
def letterDni = possibleLetters[dniNumber % 23]
"${dniNumber}${letterDni}".toString()
}
def dni = randomDni(true)
def dni2 = randomDni(false)
assert Objects.nonNull(dni)
assert dni.size() > 0
assert Objects.nonNull(dni2)
assert dni2.size() > 0
return this
- Save the script as
/path/to/random_spanish_id.groovy. - Test it in groovyConsole:

- Invoke it from Java code using
GroovyShell:
import groovy.lang.GroovyShell;
import java.io.File;
import java.util.Objects;
public class Runner {
public static void main(String[] args) {
String groovyScriptDir = "/path/to/script/";
if (Objects.nonNull(System.getProperty("profile.groovy.dir"))) {
groovyScriptDir = System.getProperty("profile.groovy.dir");
}
String value =
(String)
(new GroovyShell()
.parse(new File(groovyScriptDir + "random_spanish_id.groovy"))
.invokeMethod("randomDni", true));
System.out.println("Value: " + value);
}
}
NOTE: Use a System property or environment variable such as
profile.groovy.dir(passed via-Dprofile.groovy.dir=...) to locate the script directory dynamically.