1.3.x: Backport fixes for GRAILS-3168

The same implementation and test cases, but relocated to the old file structure for 1.3.x.