Grails Snippets

This is ongoing post to record different useful codes snippets related to Grails framework

1. Default and Shared Constraints.
It turns out you can specify default constraints that can be applied and shared in any Domain Class. For example, by default the ‘nullable’ constraint is set to ‘false’. If you wish change that,then updated conf/Config.groovy as follows:

grails.gorm.default.constraints = {
    '*'(nullable: false)
    noBlankSized(blank: fralse, size: 4..25)
}

The ‘*’ attaches the constraint to all property’ validations. The constraint ‘myShared’ can be references in any validation you choose as follows:

class User{
...
 static constraints = {
        favoriteDish shared: "noBlankSized"
    }
}

This way you able to share your own default validations while ability to reuse as you like

2. Suppor Handling Request params

A request parameter value can be converted to a specific type with method invocation:

params.long('book.id')

This takes book.id and converts it to long type. Grails supports other methods like byte(), long(), boolean(). Since Grails 2.0 also support for dates.

3. Access Domain class from Plugin
Say you developing plugin that needs to access domain class in the application.

String className = "com.foo.bar.MyDomainClass"
Class clazz = grailsApplication.getDomainClass(className).clazz
def findAnything = clazz.findByStuff(params.stuff)

If Domain class without package and name unique across all packages:

String className = "MyDomainClass"
Class clazz = grailsApplication.domainClasses.find { it.clazz.simpleName == className }.clazz
def findAThing = clazz.findByStuff(params.stuff)

This may not be best practices as we are coupling the plugin with particular applications, however,perhaps in some circumstance it necessary

4. Mocking Upload File feature with multipart/form-data

void testFileUpload(){
        def imgContentType = 'image/jpeg'
        def imgContentBytes = '123' as byte[]
...
        controller.metaClass.request = new MockMultipartHttpServletRequest()
        controller.request.addFile(
            new MockMultipartFile('image', 'myImage.jpg', imgContentType, imgContentBytes)
        )
...
        controller.save()
...
        assertEquals HttpServletResponse.SC_OK, controller.response.status
..
    }

Current Path from Request
To get current path from the current controller and action:

request.forwardURI

Groovy Snippets

This is ongoing blog where i plan to record groovy code snippets that convenient, useful and powerful

Generating Long Strings

Generating certain size string( used in testing to test sized string constraints)

def genString(size){
    def nameTooLong = 'x'
    size.times { nameTooLong <<= "x" }
    nameTooLong
}

-or-

'x'*100

Avoid Exception – MissingPropertyException

There is null safe operator (?.) to avoid exceptions when calling methods on null object, however. If you call a property or method that is not defined, you will receive an exception – ‘missingPropertyException’. To make it similar as null safe but this time exception safe, add the following to your class:

def propertyMissing( name ) {
  null
}

This will make call to a method, that hasn’t been defined, return null, instead throwing exception. Likewise, this will make access to a variable, that hasn’t been defined, return null instead of throwing exceptions

If you don’t have access to changing the class, then the alternative would something like:

def result = obj.hasProperty( 'b' ) ? obj.b : null

It requires much more to accomplish the same as adding the method – propertyMissing to the class only once, but it may work some situation better

 Remove last characters from string

assert 'some' == 'someString'[0..-7]

Checking if String

To determine whether its valid string, make sure check case for empty string like – ‘ ‘:

asset someString?.trim()

Java Gotchas

This is ongoing post where i hope to continue list different Java gotches

1. java.util.ConcurrentModificationException – Removing children from the parents’s collection while we’re iterating over it.

As example we use groovy. In our example, we have RentalUnit object that contains colection of Reviews and Reviews contain collection of RentalUnit all in many-to-many relationship

Error:

review1.rentalUnits*.removeFromReviews(review1)

Solution:

def r = []
r += review1.rentalUnits
r.each {RentalUnit renUnit ->
     renUnit.removeFromReviews(review1)
}