Time is a valuable resource. So principles as KISS and DRY are important and applicable here.

I apologize in advance by extreme simplification and excessive use of hyperlinks. Feel free to discuss whatever you consider relevant, using appropriate means.

Why Groovy and Grails?

Groovy = Java++

Grails = (Spring Framework + Hibernate)++

With time and maturity of the developer and the technology itself:

Groovy = Java **

Grails = (Spring Framework + Hibernate) **

You write the same kind of application, in significantly less time.

And if I discover that some piece of code in Groovy is affecting the performance of my application?
Continue reading

Tips on Gant scripts on Grails

  1. While GRAILS-7274 is not fixed, use try-catch when writing build event handlers;
    eventCreateWarEnd = {warName, stagingDir ->
    try {
    // Script logic goes here...
    } catch (Exception e) {
    throw e
  2. Add log verbosity to Gant, when appropriate:
    import org.codehaus.gant.GantState
    // (...)
    GantState.verbosity = GantState.VERBOSE
  3. Prefer AntBuilder.path to the use of nested classpath elements:
    ant.path(id: 'myClasspath', { pathelement(location: 'somewhere') }) 'aClass', dir: 'anyDir', fork: true,
    classpathref:'myClasspath') {}

The “prize” for having read this far is the necessary snippet to execute the weblogic.appc (among other activities, it will pre-compile the JSPs) after the creation of the .war file of your project:

// _Events.groovy
import org.codehaus.gant.GantState

eventCreateWarEnd = {warName, stagingDir ->

def beaHome = System.getenv('BEA_HOME')?: 'C:/bea'
try {
println "Executing weblogic.appc ${beaHome} ${warName}"

//GantState.dryRun = true
GantState.verbosity = GantState.VERBOSE

File warFile = new File(warName)
File tmpFile = new File(warFile.parentFile, "${'.')[0]}_tmp.war")
ant.move(file: warFile, tofile: tmpFile)

ant.path(id: 'appcClasspath', { pathelement(location: "${beaHome}/wlserver_10.3/server/lib/weblogic.jar") }) 'weblogic.appc', dir: warFile.parentFile, fork: true, classpathref:'appcClasspath') {
arg(line: "-output ${} -lineNumbers -g -O -keepgenerated ${}")
} catch (Throwable e) {
throw e

Additional references:

Continue reading

Searchable and browseable source code

For public source code written in Java, GrepCode may be helpful.

For private source code and/or written in other languages ​​(or stored using unusual version control systems), it is worth knowing the OpenGrok.

Additional references:

Continue reading

Performance improvement of freemarker-tags

For most applications the time spent in generating the outputs of their views is small and therefore any improvement in this aspect will be negligible.
For applications sensitive to that time, freemarker-tags has been redesigned, improving its performance. In version 0.7.0 of the plugin, the rendering speed of Grails Tag Libraries in a FTL template, is very close to that of a compiled GSP page:

A) quick_start application started using ‘grails prod run-war’ and tested using ‘ab-n 3000-c 30 url’

#request/second (mean)


list: 165.99 #/sec, 403.29 #/sec, 448.74 #/sec, 421.15 #/sec
create: 201.49 #/sec, 407.45 #/sec, 449.79 #/sec, 436.02 #/sec
show: 231.39 #/sec, 428.36 #/sec, 496.63 #/sec, 468.14 #/sec
edit: 186.29 #/sec, 348.25 #/sec, 388.07 #/sec, 372.15 #/sec


list: 248.94 #/sec, 714.39 #/sec, 777.56 #/sec, 688.66 #/sec
create: 251.24 #/sec, 712.82 #/sec, 891.65 #/sec, 813.68 #/sec
show: 250.04 #/sec, 742.08 #/sec, 990.49 #/sec, 918.49 #/sec
edit: 230.59 #/sec, 720.73 #/sec, 903.11 #/sec, 783.17 #/sec


list: 222.27 #/sec, 670.82 #/sec, 720.34 #/sec, 627.70 #/sec
create: 218.92 #/sec, 618.93 #/sec, 750.98 #/sec, 695.02 #/sec
show: 250.08 #/sec, 786.39 #/sec, 1040.83 #/sec, 878.74 #/sec
edit: 211.43 #/sec, 636.35 #/sec, 823.98 #/sec, 757.29 #/sec

In particular situations, the performance of a FTL template will be even better than a GSP page, thanks to FreeMarker itself:
Continue reading

Programmatic transaction management in Grails

Until GRAILS-7093 becomes part of the core, the feature will remain available as a Grails plugin: transaction-handling.

Examples of use:

User.withTransaction {

User.withTransaction(isolation: 'readUncommitted') {

User.withTransaction(readOnly: true, timeout: 'default') {

User.withTransaction(propagationBehaviorName: 'PROPAGATION_MANDATORY', timeout: 765) {

User.withTransaction(propagation: "mandatory") {

User.withNewTransaction {

User.withNewTransaction(isolationLevel: TransactionDefinition.ISOLATION_SERIALIZABLE) {

User.withNewTransaction(propagation: 'supports', readOnly: true, timeout: 612) {

User.withNewTransaction(isolationLevelName: 'ISOLATION_REPEATABLE_READ') {

Continue reading

GSP vs. FTL (microbenchmark)

Groovy Server Pages vs. FreeMarker Templates. Both are good tools, maintained by extremely qualified teams and available to Grails (FreeMarker through freemarker and freemarker-tags plugin).

As previously stated, microbenchmarks are just microbenchmarks. The following tests were motivated by an old argument over dynamic template rendering and the recent discussion on the rendering performance of various web frameworks.

These are the testing results for the mentioned scenario:

Apache HTTP server benchmarking tool (ab)

  • GSP

    Document Path: /grailsapp/products
    Document Length: 1037698 bytes

    Concurrency Level: 30
    Time taken for tests: 383.757685 seconds
    Complete requests: 3000
    Failed requests: 0
    Write errors: 0
    Total transferred: 3113592000 bytes
    HTML transferred: 3113094000 bytes
    Requests per second: 7.82 [#/sec] (mean)
    Time per request: 3837.577 [ms] (mean)
    Time per request: 127.919 [ms] (mean, across all concurrent requests)
    Transfer rate: 7923.27 [Kbytes/sec] received

    Connection Times (ms)
    min mean[+/-sd] median max
    Connect: 0 0 1.1 0 14
    Processing: 2105 3829 380.8 3831 5122
    Waiting: 2097 3824 381.0 3825 5120
    Total: 2105 3829 380.9 3831 5122

    Percentage of the requests served within a certain time (ms)
    50% 3831
    66% 3987
    75% 4092

  • FTL

    Document Path: /grailsapp-fm/products
    Document Length: 1026697 bytes

    Concurrency Level: 30
    Time taken for tests: 103.94286 seconds
    Complete requests: 3000
    Failed requests: 0
    Write errors: 0
    Total transferred: 3080604000 bytes
    HTML transferred: 3080091000 bytes
    Requests per second: 29.10 [#/sec] (mean)
    Time per request: 1030.943 [ms] (mean)
    Time per request: 34.365 [ms] (mean, across all concurrent requests)
    Transfer rate: 29181.07 [Kbytes/sec] received

    Connection Times (ms)
    min mean[+/-sd] median max
    Connect: 0 0 0.0 0 0
    Processing: 74 1027 646.1 962 4373
    Waiting: 71 988 643.3 915 4006
    Total: 74 1027 646.1 962 4373

    Percentage of the requests served within a certain time (ms)
    50% 962
    66% 1212
    75% 1376

Continue reading

Using Grails to build a simple batch system

Inspired by the discussion on ‘How would you launch a Quartz job from a script?’ and basing on the post about ‘Tiny GroovyServ’, I decided to write a simple batch system using Grails and quartz, spring-security-core and batch-launcher plugins.

The batch-launcher has been choosen because, in the company where I work, there are segregated environments for online (web) applications and batch applications. So in the exclusive environment for batch applications there isn’t Tomcat, WebLogic or any Web Container or Application Server. In this context, batch applications are responsible for all massive and asynchronous processing, especially when it is required to integrate two or more systems.

Basically I created an application made by services and scheduled tasks, whose synchronous or asynchronous invocation can be done through an SSH client. The step-by-step test:

  1. Download the file (its size is about 25 Mbytes and it contains all dependencies needed to run the application)
  2. Unzip the file in a directory
  3. Start the application (the only prerequisite for this step it is to have a installed JRE and make java available in the PATH)
  4. [daniel@techdm simple_batch_system-0.1]$ ./



  5. Start the execution of services or scheduled tasks logged in as admin0 (password is admin):ssh -p 8123 admin0@localhost task1Job,task3Service

Continue reading

Tiny GroovyServ

GroovyServ is an interesting solution for executing multiple Groovy scripts in a shared JVM. Unfortunately, as mentioned in this thread, restrictions in relation to the supported operating systems can become a problem.

As an alternative approach, a small SSH server was written using Groovy. In this way, any native SSH client would be able to send scripting execution commands to the server. The idea follows the same line of reasoning of the combination of ‘groovy-l’ and telnet. For handling the SSH protocol, Apache Mina SSHD was used.

It is noteworthy that the server is developed as a distant cousin, not optimized, insecure and functionally limited of GroovyServ, not having the intention of replacing it. For the execution in unrestricted environments, the use of a SecurityManager properly configured and the adoption of appropriate authentication mechanism are recommended.

Step-by-step instructions for use:

1. Download the source code of the server

2. Unzip the archive into a directory

3. Start the server

[user@techdm tiny-groovyserv]$ groovy tgserv.groovy


[user@techdm tiny-groovyserv]$ groovy tgserv.groovy 8123

4. Write some scripts on the same host

5. Start multiple command prompts or shells and simultaneously run the created scripts

[user@techdm test]$ ssh -p 8123 localhost /tmp/test/a.groovy abc 123

[user@techdm dir1]$ ssh -p 8123 localhost /tmp/test/dir1/b.groovy

[user@techdm dir2]$ ssh -p 8123 localhost /tmp/test/dir2/c.groovy

or using plink:

C:\tmp\test> plink -P 8123 -ssh -l x localhost c:/tmp/test/a.groovy abc 123

C:\tmp\test\dir1> plink -P 8123 -ssh -l x localhost c:/tmp/test/dir1/b.groovy

C:\tmp\test\dir2> plink -P 8123 -ssh -l x localhost c:/tmp/test/dir2/c.groovy

Project on GitHub.

Additional references:

Continue reading

Dynamic JRE: Stressing the machine

When considering whether to use WebLogic Server as a Grails EmbeddableServer, replacing Tomcat or Jetty in the execution of ‘grails run-app’, I came across with some limitations. Certain features of the Java runtime environment are not prepared to be changed after starting the JVM (or are they?). Despite all hype, it’s just software and use it in an unconventional manner won’t trigger the end of the world.

The following solutions (workarounds or tricks, if you prefer) require a SecurityManager or security policies permissive enough. They can be implemented using Groovy or “pure” Java. Basically makes use of AcessibleObject.setAcessible and how some classes of Java core libraries work internally, in particular the implementations available with the Oracle/Sun JDK or JRE and the OpenJDK.

1. Dynamically adding paths to the CLASSPATH (java.class.path)


// groovy change_classpath.groovy

def changeClasspath = {paths ->
def systemClassLoader = ClassLoader.systemClassLoader
assert systemClassLoader.metaClass.respondsTo(systemClassLoader, 'addURL',
def pathSeparator = File.pathSeparator
def classpathExtension = new StringBuilder()
for (path in paths) {
def lib = new File(path); assert lib.exists()
classpathExtension.append(pathSeparator); classpathExtension.append(lib.canonicalPath)
// Required under certain conditions
System.setProperty('java.class.path', System.getProperty('java.class.path', '') + classpathExtension.toString())

def classes = ['Lib1', 'Lib2', 'Lib3', 'Lib4']
for (className in classes) {
try {Class.forName(className); assert false} catch(ClassNotFoundException e) {assert true}

def extraPaths = ['lib1.jar', 'lib2classes']
extraPaths.addAll((new File('extraLibs').list() as List).collect {'extraLibs/' + it})

for (className in classes) {
def lib = Class.forName(className)
println "${className}.classLoader ${lib.classLoader}"

// java -ea ChangeClasspath

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class ChangeClasspath {

public static void main(String [] args) throws, NoSuchMethodException, IllegalAccessException, java.lang.reflect.InvocationTargetException, ClassNotFoundException {
String [] classes = {"Lib1", "Lib2", "Lib3", "Lib4"};
for (String className : classes) {
try {Class.forName(className); assert false;} catch(ClassNotFoundException e) {assert true;}

List <String> extraPaths = new ArrayList();
extraPaths.add("lib1.jar"); extraPaths.add("lib2classes");
for (String path : new File("extraLibs").list()) {
extraPaths.add("extraLibs/" + path);


for (String className : classes) {
Class lib = Class.forName(className);
Method doSomethingMethod = lib.getDeclaredMethod("doSomething");
System.out.println(className + ".classLoader " + lib.getClassLoader());

private static void changeClasspath(List <String> paths) throws NoSuchMethodException, IllegalAccessException,, java.lang.reflect.InvocationTargetException{
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
assert systemClassLoader instanceof;

String pathSeparator = File.pathSeparator;

StringBuilder classpathExtension = new StringBuilder();
Method addURLMethod ="addURL",;

for (String path : paths) {
File lib = new File(path); assert lib.exists();
addURLMethod.invoke(systemClassLoader, lib.toURI().toURL());
// Required under certain conditions
System.setProperty("java.class.path", System.getProperty("java.class.path", "") + classpathExtension.toString());


Continue reading