grails detecting environment - groovy & gsp code

Grails/Groovy working code snippet to detect the current environment (development, test, production, or your  custom). Custom environment are defined in config.groovy file.

Detecting Environment in GSP code :

Following checks if current environment is other than production.
    <g:if test="${env != "production"}">
        //your logic 

    </g:if>

Detecting environment in Groovy Code ( in Controller, Service, etc..), using switch-case comparison

        switch(Environment.current.getName()){
            case "development":
                //do your stuff 1
                break;
            case "test":
                //do your stuff 2
                break;
            case "production":
                //do your stuff 3
                break;
            case "my_environment":  // for custom environment : my_environment
                //todo:
                break;
        }

Simple comparison in groovy

if(Environment.current.getName()=="development") {
    //do your stuff
}

Grails - auto login in spring security

Consider a typical web application where you have multiple user roles (like SUPER_ADMIN, OPERATOR, VISITOR etc ) and you need to do login and switch between them frequently. It certainly consumes a lot of time if you do this manually. One simple solution would be to use the browser's password remember feature. But this would not be useful if you need to switch between different role.

Here, I am going to do show how we can setup this mechanism in Grails applications which uses Spring Security plugin.

If you are using Spring Security plugin then, by default you will have following names for html textbox for username and password : j_username and j_password. and you have login request url as http://localhost:8080/YOUR_APP/j_spring_security_check .

The required login script :

Groovy Grails - Dynamic Method n Variable name and invoking them

Groovy allows to use dynamic method name and variable name and invoke/use them.

Dynamic Variable Names

Groovy allows to use variable name dynamically. To test this lets introduce a variable  "dogname" to Dog class

class Dog {
def dogname
...
}

//Testing dynamic variable name
        def aDog= new Dog()
aDog.name="Hachi"
def prop="dogname"

println aDog."$prop" // prints Hachi