Thursday, 18 February 2016

The GRAILS WELT (WORLD) - GRAILS UNIT TESTING

Before proceeding on with GRAILS CACHING with EHCACHE, I just want to take some time out for Grails Unit Testing.

Grails provide an extensive Test Suite along with SPOCK. It provides well suited templates to carry out testing for Controllers, Domains etc and Grails provides extensive documentation for that.

When we create various components like Controllers, Domains, Interceptors etc. etc., the corresponding Test Suites are being created alongside by Grails. So what else!!!. Only we need to define the Unit Test Cases.... That's it..

But I was constantly facing some Stackframe Error while I was trying to execute the Unit Test case with Gradle.
The version of JDK that I was using is of version 1.7.0_45.
But on installing and using JDK 1.7.0_80 I was able to resolve the issue.
Following are the dependencies for Testing in Gradle.


 /**
     * Test Configuration
     */

 testCompile "org.hamcrest:hamcrest-core:1.3" // only necessary if Hamcrest matchers are used
    testRuntime "cglib:cglib-nodep:3.1"          // allows mocking of classes (in addition to interfaces)
    testRuntime "org.objenesis:objenesis:2.1"    // allows mocking of classes without default constructor (together with CGLIB)

    

    testCompile 'junit:junit:4.12'
    testCompile ('org.spockframework:spock-core:1.0-groovy-2.4'){
        exclude group: 'org.codehaus.groovy'
    }

Here are some of the Test Cases that I have written for reference.

The Controller for which we will be writing Test Case is:


class DoctorController extends RestfulController{

static responseFormats = ['xml','json']

    def index() {
        render( view:"registerDoc")
    }

    DoctorController()
    {
        super(Doctor.class, true)
    }

    def registerDoc(Doctor doctor)
    {
        println "The Doctor Name is:${doctor.name}"

        doctor.save()

       // doctor = doctor.find("1")

        println "The Saved Doctor is $doctor"
        respond doctor
    }

    def registerDoctorCommand(DoctorCommand doctorCommand)
    {
        println "The Doctor Command is:$doctorCommand"
        render "The Doctor name is ${doctorCommand.name}"
    }


}

The Unit Test Case class is:

@TestFor(DoctorController)
@Mock([Doctor,Hospital])
class DoctorControllerSpec extends Specification {

    def setup() {
    }

    def cleanup() {
    }

    void "test something"() {
        expect:"fix me"
            true == true
    }

    void "test index"() {
        when:
        controller.index()

        then:
        view == "/doctor/registerDoc"
    }

    void "test registerDoc"() {
        def result
         when:

            println "**** Mocking ****"
            Hospital hospital = new Hospital(name:'okkk')

         /**
          * In order to pass NULL hospital we can make the Domain constraint nullable
          * as true, which is by default false.
          *
          * Please refer to Doctor Domain class
          *
          */

         Doctor doctor = new Doctor(name: '1asd', regNo: '234', spec: 'ok', hospital: hospital)
         try {
             result = controller.registerDoc(doctor)
         }
        catch (e)
        {
            e.printStackTrace()
        }

        then:
            Doctor.count() == 1

    }

    void "test registerDoctorCommand"()
    {
        when:
        params.name = 'ok'
        params.regNo = 'ok123'
        params.spec = 'ok12345'

        controller.registerDoctorCommand()

        then:

        response.text == 'The Doctor name is ok1'
    }

}


Here the DoctorControllerSpec class by extending Specification supports testing using the Groovy Test framework i.e. SPOCK @TestFor annotation describes the Component for which we want to write the test for and @Mock depicts the components to be mocked.

The detailed description about Grails Testing and other features can be read from the comprehensive Official Documentation.

View Subhankar Paul's profile on LinkedIn

Wednesday, 17 February 2016

The GRAILS WELT (WORLD) - GRAILS EVENT HANDLING

Now Event Handling in Grails is very Intersting.

It follows neither any Callack nor Listener approach. But it follows a Reactive Approach(Rx), Basically the Observable-Subscriber Pattern.

Event Handling in Grails is being done using the following annotations(in Grails Components i.e Controller, Services):

1) @Selector.
2) @Consumer. etc.
Let's walk through an example.
The Code that we have within a service method, which acts as a Subsriber to an event named myEvent.select is:

@Consumer
@Transactional
class AuthorService {

 @Selector('myEvent.select')
 def eventSelector(Object object)
 {
  println " In AuthorService The Object is $object"
 }

}

The Consumer annotation manifests this service to be a consumer of events, published from various sources. With the help of Selector annotation, we annotatate methods within Grails Components to deal with various events published from various sources.
We can also send data(Objects) while publishing the Events, which can be handled in the Subscriber to that particular Event passed as a parameter to the method. Here we can see that the Object parameter to eventSelector() method is the data passed from the Event Published.

Now, the next Question that arises, that how we can publish Events along with Data so that the Subsribers could be in Action.

Subscribers Responsive to Stimulus!!!!



It can be done with the help of notify OR sendAndReceive methods.
The first parameter to notify() method is the Event name and the next is the Object Passed with the event i.e the Data.
For sendAndReceive the first and second parameters are same as notify, with this we can also pass a closure that gets executed after the value is being returned from the corresponding subsriber Subscriber and we can access the value as returned from the Subscriber in the closure.

By Default all the Services and Controllers in Grails implements Events trait, so with the help of @Consumer & @Selector annotation we can make a Sunscriber Component.

We can also make a POJO to subscribe to various events.
We need to declare the POJO to implement the Events trait and register it as normal bean in the Application Context, and then with the help of lifecycle phases of a bean(appropriate Lifecycle methods) we can make the POJO to subscribe to various events using the on() method.

Here is the example:

class MyEventListener implements Events {

    EventData eventData

    @PostConstruct
    void init() {
        on("myEvent.select") {
            println "Event fired! for $it"
        }
    }
}

and the declaration in resources.groovy is:

 /**
     * Registering Event Listener
     */
    
 eventData(EventData){
        data = 'All is Good'
    }

    myEventListener(MyEventListener){
        eventData =  ref('eventData')
    }

So when the bean named myEventListener gets registered in the Application Context, then during post initiaization of the bean, the init() gets executed which registers the subscriber for the Event Named myEvent.select with the help of on() method and the closure gets executed when this Subscriber receives the Event.

An Event can get fired or Published by any component at any point of time and if there are any Subscribers to that Event then, those are executed. Grails uses REACTOR API to achieve this, which is one of the Most innovative and updated topic in Present time i.e. The Reactive approach.

View Subhankar Paul's profile on LinkedIn

Friday, 12 February 2016

The GRAILS WELT (WORLD) - GRAILS AUTOBINDING

In this post we will be going on with the GRAILS AUTOBINDING feature during form submission.

Now, GRAILS documentation provides a comprehensive guide to Autobinding request to Domain or Command Objects.
So this post is not about all those features.

My objective is to bind list of objects from Front end (.gsp) to the underlying Domain or Command Object in Controller and then access them there.
I first started modelling following the Spring approach using the index (subscript) pattern (i.e. CommandObj[i]), but somehow it was failing to bind the values from the Request map to Domain or Command Object in Controller.

Below code excerpts provides the approach that I followed for the above mentioned problem.
I am dividing the post in to parts:

1. Part -1: Autobinding request to Command Object
2. Part -2: Autobinding request to Domain Object
Part -1

The View:





 <g:form  controller="book" action="submitBook" method="POST" name="BookRegistrationForm" >
    Title0:<gg:textField name="items[0].title"></g:textField> <br/>
    Author0:<gg:textField name="items[0].author"></g:textField> <br/>

    Title1:<gg:textField name="items[1].title"></g:textField> <br/>
    Author1:<gg:textField name="items[1].author"></g:textField> <br/>

    Title2:<gg:textField name="items[2].title"></g:textField> <br/>
    Author2:<gg:textField name="items[2].author"></g:textField> <br/>

    <gg:submitButton name="register" type="submit" value="Submit/Register"></g:submitButton>


<g/g:form>




The Corresponding Command Object is:



class BookCommand implements Validateable{

    List items = [].withLazyDefault {new Book() as Factory}

    static constraints = {}
}

Now, we have made the Command Object to implement Validateable just like Domain objects to so that we can put constraints/validation on the properties of the Command Object from within static constraint closure.

Within Commad Object we have instantiated a List of type Book lazily initialized and the elements of this list we are using in the View using the index subscript.

and the Controller where we are accessing the Command Object is:


class BookController {
   def index() {
  render( view:"registerBook")
 }
 
 def submitBook(BookCommand bookCommand)
 {
  bookCommand.items.each {Book book ->

   25.times {
    print "*"
   }

   println "Author:$book.author \n Title:$book.title"

   25.times {
    print "*"
   }

   println ""

  }
 }
 
 }

Part -2

The View:



<g:form  controller="hospital" action="createHospital" method="POST" name="HospitalRegistrationForm" >

    Name:  <g:textField name="name"></g:textField> <br/>
    Doctor Name:  <g:textField name="doctors[0].name"></g:textField> <br/>
    Doctor Reg No:  <g:textField name="doctors[0].regNo"></g:textField> <br/>
    Doctor Specialization:  <g:textField name="doctors[0].spec"></g:textField> <br/><br/><br/>

    Doctor Name:  <g:textField name="doctors[1].name"></g:textField> <br/>
    Doctor Reg No:  <g:textField name="doctors[1].regNo"></g:textField> <br/>
    Doctor Specialization:  <g:textField name="doctors[1].spec"></g:textField> <br/>

    <br/><br/>
    <g:submitButton name="register" type="submit" value="Submit/Register"></g:submitButton>



</g:form>



The Corresponding Domain Object is:


class Hospital {

    String name
    //Doctor doctor
    static hasMany = [doctors: Doctor]

    //List doctors

    static constraints = {
    }
}

Here, we can see that how we have bound the property name and doctors with the Form. Another important thing to notice out here is the doctors property which we has no explicit declaration on the Domain object but is being configured as List of type Doctor within the Domain Object by Grails (All the credits goes to GORM) and hence we can access this property just like other List Properties.

The Corresponding Controller is:

class HospitalController extends RestfulController {

    static responseFormats = ['xml','json']
 
 Environment environment

    @Value('${dataSource.driverClassName}')
    def driverClassName

    HospitalController(Class resource) {
        super(resource)
    }

    HospitalController()
    {
        this(Hospital.class)
    }

    def index() {

        println "The Environment is: $environment \n\n ${environment.getProperty('application.profile')} \n" +
                " ${environment.getProperty('hibernate.cache.use_second_level_cache')} \n" +
                "${environment.getProperty('dataSource.driverClassName')} \n\n Done Done-- $driverClassName"

        render(view:"registerHospital")

    }

    def createHospital(Hospital hospital)
    {
        def hospital2
        try {
            println "No of Doctors: ${hospital.doctors.size()}"
            hospital.save()

            hospital2 = new Hospital(name:'okkkiea')
            hospital2.addToDoctors(new Doctor(name:'bnm',regNo:'yhj',spec:'zzz'))
                    .addToDoctors(new Doctor(name:'fff',regNo:'ggg',spec:'mmm'))
                    .addToDoctors(new Doctor(name:'fff7',regNo:'ggg7',spec:'mmm7'))

            hospital2.save()

            println "No of Doctors2: ${hospital2.doctors.size()}"
        }
        catch(e)
        {
            e.printStackTrace()
        }
        println "The saved Hospital is:$hospital \n\n $hospital2"
    }
 
 }

So this is in short about Autobinding Collection Form Data with the Command and Domain Object.

Along with Auto Binding, if you take close look at the bove controller, there has also been demonstrated ways to access properties from the configuartion files using both @Value injection and also using Spring Environment.

Please feel free to add your comments and and feedback.
View Subhankar Paul's profile on LinkedIn

Monday, 8 February 2016

The GRAILS WELT (WORLD) - PROFILE BASED BUILD

Welcome Friends!!!!!

It has really been quite sometime, since I wrote last.
Actually, after going a bit through GPars, I somehow felt to learn something new at the beginning of the year, then I suddenly it came to mind that why not GRAILS.

All I knew upto this point that GRAILS uses both Spring and Groovy and it is a Web Development Framework, so I jumped into it instantly started to explore it starting from the Very Beginner's Level with the help of its Official Documentation.

The First this which I saw at the Official Doc site, is that all I will be learning about GRAILS 3.0.x and at that time even I do not have any idea about the differences it has with the earlier version as I was not aware of them either, So every thing is very very new to me. All I can say after this timespan i.e. A Month and More that GRAILS is Awesome..

I am at an infancy level as far as GRAILS is concerned and I am gonna share my expereinces that I have during this time.
There may be cases where I can be wrong Or I may have adopted some approaches which are not appropriate, Please correct me in all those cases.

Now the differences that Grails 3 has with its previous version is well documented in its official site along with all the Migration Strategies, but the noteworthy features of Grails 3 that I have explored till now which has really enthralled me are the following:

1> The Spring Boot support along with GrailsAutoConfiguration providing a web.xml free applicatication
2> GRADLE Build System
3> The configuration in .yml file etc.
Now in this Post I will be discussing, Building Grails Project in Gradle for various Profiles (like DEV,UAT,STAGING,PRODUCTION etc.).
The Profile wise build that we can easily carry out with Maven, I initially find it quite difficult in configuring it with GRADLE, as I am fairly new to this promising Build EcoSystem may be one of the reasons.

However GRAILS CommandLine along with configuration file application.yml does satisfy my objective with ease, but all I wanted to do is:

1) Build the artifact from the command line using GRADLE, by passing the Profile as an argument for which I want to go for.
2) Deploy the artifact (As prepared in step 1) in server. (I have used Jetty 8.7.x here)
As I have said earlier, Grails with its grails <> run-app command does everything and makes the application up with embedded Tomcat. A Single Command For All so great isn't!!!!

The Approach that I have followed to satisfy my end is:

1> I have included another config file (.yml), where I have set the profile as passed from command line with Resource Filtering.
2> Then included the config file as Resources Config in the application so that it becomes a part of "GrailsApplication".
3> Then the value of application.profile key from the above config file is then set as java environment variable giving the name "grails.env", as GRAILS internally looks for this System Property during startup for configuring profile specific properties from application.yml which GRAILS does on its own, only in application.yml we need to configure properties in proper yml format for different profiles.
Let's traverse the code, I think then it can be bit more clear.
Start with build.gradle. I have added a Task named "deploy" which mostly does all the work along with "processResource" task.

GRADLE build system is so GREAT, that we can embed programming logic here. I have included an Exception Handling, and all this is due to "Groovy Grace".

Here is the code Excerpt.


apply plugin: "war"

task deploy (dependsOn: [makePretty,clean,war]){
    try{
    environment = env
    //println "The environment is $environment
    }
    catch(e)
    {
        println "The Error is: ${e.getMessage()}"
        if(e instanceof MissingPropertyException)
        {
            println "Please Execute Deploy TASK by passing parameter for Environment \n USAGE: gradle -Penv=<> deploy"
        }
        
        //throw new StopActionException(e.getMessage())

        55.times {
            print "*"
        }

        println ""

        println "No Build environment is provided, so we are setting it to UAT"
        environment = 'UAT'

        55.times {
            print "*"
        }

        println ""

    }

    doLast {
        println "Setting System Property"
        println "System Prop set to $environment"

        println "Deploying War......"
        copy{
            from "build/libs"
            into "C:/Users/MIC/Desktop/Cloud/jetty-distribution-8.1.17.v20150415/webapps"
            include "*.war"
        }
        println "Deployment Done......"
    }
}


processResources {
    filter ReplaceTokens, tokens: [
        "GRAILS.ENV": environment
    ]


}

task makePretty(type: Delete) {
   delete 'C:/Users/MIC/Desktop/Cloud/jetty-distribution-8.1.17.v20150415/webapps/HelloGrails.war'
 }
 
 war{
    sourceSets {
        main {
            resources {
                include '**/*.groovy'
                include '**/*.gsp'
                include '**/*.properties'
                include "**/application-profile.yml"
                include "**/application.yml"
                include "**/*.xml"
                //exclude 'application-staging.yml'
            }
        }
    }
	archiveName = "HelloGrails.war"
}


We have also included war plugin, so that we can alter war confuration during build with the help of war closure. In the closure we have indicated which of the files needs to be in the generated war.

The deploy task is dependent on other task dependsOn: [makePretty,clean,war], included that as well and finally the resource filter block which will replace the token with name "GRAILS.ENV" with the property value named "env" that we pass as parameter while executing the deploy task. If we do not pass any then the default profile is "UAT"

The command that is going to perform the build process is:

gradle -Penv=<<PROFILE_NAME>> deploy, For example: gradle -Penv=UAT deploy, or gradle -Penv=staging deploy or gradle -Penv=dev deploy etc. Now following the approach that we have discussed before, corresponding to Point 1, the Config file where we will record the profile from the command line so that we can configure the application during its startup time is:


application:
    profile: @GRAILS.ENV@

The file has been named as application-profile.yml and it as been included in the generated war artifact after the build has carried out from gradle as indicated in the war closure in build.gradle.

After successful build this configuration file would look like:

application:
    profile: UAT

Now corresponding to Point 2, we have included the above application-profile.yml file as part of the resource config with the help of the follwoing code in Application.groovy.



class Application extends GrailsAutoConfiguration implements EnvironmentAware {

   

    void setEnvironment(Environment environment) {

        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver()
        Resource resourceConfig = pathMatchingResourcePatternResolver.findPathMatchingResources("classpath:application-*.yml")[0]

        YamlPropertiesFactoryBean ypfb = new YamlPropertiesFactoryBean()
        ypfb.setResources([resourceConfig] as Resource[])
        ypfb.afterPropertiesSet()

        Properties properties = ypfb.getObject()
        environment.propertySources.addFirst(new PropertiesPropertySource("environment.config", properties))

        def profile = environment.getProperty('application.profile')

        35.times {
            print "*"
        }

        println ""

        println "Starting Up for Profile is: $profile"

        35.times {
            print "*"
        }

        println ""

        System.setProperty("grails.env",profile)

    }

    static void main(String[] args) {

        println " *****  Going for StartUps......."
        GrailsApp.run(Application, args)
    }
}

We have made the Application.groovy to implement Spring EnvironmentAware, so that overriding the setEnvironment() method we add the above config file as a Property Resource with the help of Environment parameter.

Now, For Point 3, within the above method we accessed the property and set it as a System Parameter as:


System.setProperty("grails.env",profile)

After this property is set, Grails automatically access the property and configures its environment based on the value of the property (grails.env)

There are there know properties for Grails:

1) Development
2) Production
3) Test
Apart from all above properties, all other are conferred as CUSTOM.

This is in short about Profile Based Configuration in Grails with Gradle.

In my next post I will discuss Form submission in Grails with Collection Data (By Auto DataBinding with Command Objects)

Till next time Keep Sharing and Keep Contributing.........
View Subhankar Paul's profile on LinkedIn