Showing posts with label Grails. Show all posts
Showing posts with label Grails. Show all posts

Friday, February 8, 2019

GRAILS : Rendering Groovy GSP Code From A String | Grails – Rendering a Template from a String | Render Grails template from external source




package com.pkm.utils

import grails.util.Holders
import groovy.text.Template
import org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine
import org.springframework.core.io.ByteArrayResource
import org.springframework.web.context.request.RequestContextHolder

/**
 * Created by pritom on 29/11/2017.
 */
class InvoicePdfUtils extends UtilsBase {
    static def test() {
        GroovyPagesTemplateEngine engine = Holders.applicationContext.getBean(GroovyPagesTemplateEngine)
        StringWriter stringWriter = new StringWriter()

        String content = "CONTENT-\${a}--\${b.none?.none ?: 'None'}-MINE-XXX " +
                "<ui:serverURL/> <g:if test='true'>True</g:if> HERE??? YES ME IS HERE, ".toString()
        Map model = [a: '10', b: [:]]

        String pageName = engine.getCurrentRequestUri(RequestContextHolder.getRequestAttributes().request) // /grails/test.dispatch
        Template template = engine.createTemplate(new ByteArrayResource(content.getBytes("UTF-8"), pageName), pageName, true)
        Writable renderedTemplate = template.make(model)
        renderedTemplate.writeTo(stringWriter)

        println("Request-path=${engine.getCurrentRequestUri(RequestContextHolder.getRequestAttributes().request)}")
        println(stringWriter.toString())
    }
}


This code block will take input from yourself and then parse as a GSP parser and return output as String.

https://little418.com/2009/11/rendering-groovy-gsp-code-from-a-string.html

Sunday, June 17, 2018

Grails on Groovy > Invalidate Session > Error Handling - Session already invalidated

Problem is that in my grails application, when I invalidating the existing http session using session.invalidate() and creating a new session using request.getSession(true) is working fine for some time.
But this new session is not getting reflected everywhere in grails application. Due to this I do get 'Session already invalidated'.
I don't want to do request.getSession() everywhere, actually I would not get notified when this required or not. I am just using 'session'.
Grails holds the reference to a session object and every time you ask it for a session it returns the same reference.. so if you invalidate a session and then ask for the session it will return the same invalidated session, and cause 'session already invalidated' exception..
Execute following line Just after you do session.invalidate
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest

session.invalidate()
GrailsWebRequest.lookup(request).session = null

Grails on Groovy > Grails Filter to Redirect HTTP to HTTPS > Redirecting WWW to Root with Grails > Grails Append Something to URL before Redirect > URL Modification On Grails Filters

The problem is need to modify http to https as well as add www to domain name if not exists. To do so have to modify in our Grails Filters.

For Grails applications, a filter can be used to improved security by redirecting traffic from regular HTTP to encrypted HTTPS. The convention is that filters are written in Groovy using filenames ending in Filters, and the files go into the grails-app/conf folder.
Redirecting from HTTP to HTTPS provides a better user experience than simply blocking HTTP requests, as redirecting seamlessly forwards users to the web pages they expect to see.
The example below shows the redirect code
package com.pkm

import grails.util.Environment

import javax.servlet.http.HttpServletRequest

class SecurityFilters {
    String getDomainName(HttpServletRequest request) {
        return request.getRequestURL().substring(0, request.getRequestURL().indexOf("/", 8)) + request.contextPath
    }
    String getFullRequestURI(HttpServletRequest request) {
        String query = request.getQueryString()
        String request_uri = request.getAttribute("javax.servlet.forward.request_uri")
        if (request_uri == null) {
            return request.getRequestURL().toString().substring(0, request.getRequestURL().toString().length() - 1) + (query ? "?$query".toString() : "")
        }
        return request.getRequestURL().substring(0,request.getRequestURL().indexOf("/", 8)) + request_uri + (query ? "?$query".toString() : "")
    }

    def filters = {
        filter1(uri: "/**") {
            before = {
                Boolean isSecure = request.isSecure(), doRedirect = false
                String domain = getDomainName(request)
                String url = getFullRequestURI(request)

                println("SECURE=${isSecure.toString().capitalize()}" +
                        "\n\t >DOMAIN=${domain}" +
                        "\n\t\t>URL=${url}")

                /*if (!request.getServerName().toLowerCase().startsWith("www")) {
                    doRedirect = true
                    url = url.substring(0, url.indexOf("//")) + "//www." + url.substring(url.indexOf("//") + 2)
                }*/
                if (!request.isSecure() && !Environment.isDevelopmentMode()) {
                    doRedirect = true
                    url = "https://" + url.substring(url.indexOf("//") + 2)
                }
                if (!url.toLowerCase().endsWith("redirected=true-2")) {
                    doRedirect = true
                    url = url + (url.contains("?") ? "&redirected=true-2" : "?redirected=true-2")
                }
                if (doRedirect && request.isGet()) {
                    response.setStatus(302)
                    response.setHeader("Location", url)
                    response.flushBuffer()
                    return false
                }
            }
            after = { Map model ->

            }
            afterView = { Exception e ->

            }
        }
    }
}
If your server listens for https requests (or any requests on ports other than 80), you can add checks using the same format, replacing http and port 80 with the appropriate values. You can also redirect from any subdomain you want to the root site (or another subdomain), by simply swapping www with your subdomain.
And output would be like below. First request forwarded to second URL with additional parameters.
SECURE=False
  >DOMAIN=http://localhost:3346/CONTEXT_PATH
  >URL=http://localhost:3346/CONTEXT_PATH/home/index
SECURE=False
  >DOMAIN=http://localhost:3346/CONTEXT_PATH
  >URL=http://localhost:3346/CONTEXT_PATH/home/index?redirected=true-2

Grails on Groovy > Transactions > Transaction Block > Read Only Transactions > With New Transaction > Transactions With Read Only Stage

We all know that Grails services are transactional by default. When you create a service you see that there is a annotation @Transactional exists over class name. Transactional means all transactions will persist on database or no one will persist.
We can set transactions read only mode if we wish in a transactional block if we need. Below is a code snippet:
package com.pkm

import grails.transaction.Transactional
import org.springframework.transaction.TransactionStatus

@Transactional
class HomeService {
    TransactionStatus transactionStatus

    void callMe() {
        Table1 table1 = Table1.last()
        new Table2(table1: table1, subject: "S3", score: 3D).save()
        transactionStatus.setRollbackOnly()

        Table2.withNewTransaction { TransactionStatus tx ->
            table1 = Table1.last()
            new Table2(table1: table1, subject: "S4", score: 3D).save()
            tx.setRollbackOnly()
        }
    }
}
In above code block, we inject a bean named transactionStatus which actually maintain if a service definition is read only or not. We can set it to read only mode using transactionStatus.setRollbackOnly(). We can do the same job for when we do anything in withNewTransaction block. You can see there is another transactionStatus occur for that new region. So you can also set it to read only mode.

Grails on Groovy > Create Criteria > Create Alias > Grails Create Alias > Create Alias With Additional Criteria

We frequently use createAlias to create alias between entity. It actually create connection based on foreign key and primary key between two entities. Below is a example how we create alias between entities:
Table1.createCriteria().list {
    createAlias("scores", "scores")
}
Which will produce SQL like below where we can see that foreign key of table1 create a link with table2_child based on primary key id as following:
select ... from table1 this_ inner join table2_child scores1_ on (this_.id=scores1_.table1_id)
But if we need more on add to filter when joining them, yeah, we can do that. We can add extra conditions to on part of that SQL. To do so, first need to create a groovy file like below:
package com.pkm

import org.hibernate.Criteria
import org.hibernate.HibernateException
import org.hibernate.criterion.CriteriaQuery
import org.hibernate.criterion.Criterion
import org.hibernate.engine.spi.TypedValue

class CustomSqlJoin implements Criterion {
    private Double score = null;

    CustomSqlJoin(Double score) {
        this.score = score
    }

    //Use Example > createAlias("scores", "scores", JoinType.INNER_JOIN, new CustomSqlJoin(2D))
    @Override
    String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
        String alias = criteriaQuery.getSQLAlias(criteria)
        return "${alias}.score > ${this.score}"
    }

    @Override
    TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
        return new TypedValue[0]
    }
}
And you can use the above custom condition using as below example:
Table1.createCriteria().list {
    createAlias("scores", "scores", JoinType.INNER_JOIN, new CustomSqlJoin(2D))
    "ne" "id", System.currentTimeMillis()
}
Which will generate below SQL
select ... from table1 this_ inner join table2_child scores1_
on this_.id=scores1_.table1_id and ( scores1_.score > 2.0 )
where this_.id<>?

Saturday, June 16, 2018

Grails on Groovy > Bind Metamethod of Hibernate Criteria Builder > Create Custom Function / Custom Method Under HibernateCriteriaBuilder > HibernateCriteriaBuilder Meta Method

To bind custom method with hibernate criteria builder you first need to create a groovy file named HibernateCriteriaListener like below:
package com.pkm

import grails.util.Holders
import org.codehaus.groovy.grails.commons.GrailsApplication
import org.grails.datastore.mapping.core.Datastore
import org.grails.datastore.mapping.engine.event.*
import org.springframework.context.ApplicationEvent
import grails.orm.HibernateCriteriaBuilder

class HibernateCriteriaListener extends AbstractPersistenceEventListener {
    protected HibernateCriteriaListener(Datastore datastore) {
        super(datastore)

        HibernateCriteriaBuilder.metaClass.myMethod = { info, value = null ->
            println("NAME=${info} VALUE=${value}")
        }
    }

    @Override
    protected void onPersistenceEvent(AbstractPersistenceEvent event) {

    }

    @Override
    boolean supportsEventType(Class<? extends ApplicationEvent> aClass) {
        return false
    }

    static void initialize(GrailsApplication application) {
        application.mainContext.eventTriggeringInterceptor.datastores.each { k, datastore ->
            Holders.applicationContext.addApplicationListener(new HibernateCriteriaListener(datastore))
        }
    }
}
Now we need to register the above functionality from BootStrap, so you need to do following:
import com.pkm.HibernateCriteriaListener
import org.codehaus.groovy.grails.commons.GrailsApplication
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes
import org.hibernate.dialect.function.SQLFunctionTemplate
import org.springframework.context.ApplicationContext

class BootStrap {
    def init = { servletContext ->
        ApplicationContext applicationContext = servletContext.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
        GrailsApplication application = (GrailsApplication) applicationContext.getBean("grailsApplication")

        /* REGISTER HIBERNATE EVENT LISTENER */
        HibernateCriteriaListener.initialize(application)
    }

    def destroy = {

    }
}
And finally you can use custom criteria method using below sample:
Table1.createCriteria().list {
    delegate.myMethod("name", "value")
}

Grails on Groovy > Changing default id name and type from an entity > Custom ID field > Custom ID field value generate algorithm

While developing a simple application at work I need to specify id field to some other field suppose named 'my_id' and want to use assigned value instead of using default auto_generated.
I have a table with a column named my_id of type varchar. But GORM by default auto generate an id property with the long type. The solution is straight forward, just call the method id in the mapping closure, with the following param(s):
package com.pkm

class Foo {
    String my_id

    static constraints = {}

    static mapping = {
        id generator: 'assigned', name: 'my_id'
    }
}
The generator is the strategy to auto-generate the id, you can use a sequence or something like, since it’s a string the value will be assigned, not generated. The name is the current property to bind the value (my_id in this case).
We can use our custom class to generate id of entity. For to do this, we need to define a class like below:
package com.pkm

import org.hibernate.HibernateException
import org.hibernate.engine.spi.SessionImplementor
import org.hibernate.id.IdentifierGenerator

class IdGenerator implements IdentifierGenerator {
    static Map id = [:]

    @Override
    Serializable generate(SessionImplementor session, Object o) throws HibernateException {
        String name = o.class.simpleName
        if (!id[name]) {
            id[name] = Table1.executeQuery("select max(id) from ${name}")
            if (id[name]) id[name] = id[name][0]
            else id[name] = 0
        }
        return (++id[name])
    }
}
And we need to define our class like below:
package com.pkm

class Table1 {
    Long id
    String name
    String roll

    static mapping = {
        table("table1")
        id generator: "com.pkm.IdGenerator", column:"id", unique:"true"
    }
}
If you want to globally use same configuration then you have to modify Config.groovy, you have to add below entity to Config.groovy
grails.gorm.default.mapping = {
    version false
    id generator:"com.pkm.IdGenerator", column:"id", unique:"true"
}
And finally you can browse for more information
All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a very simple interface. Some applications can choose to provide their own specialized implementations, however, Hibernate provides a range of built-in implementations. The shortcut names for the built-in generators are as follows:

increment

generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. Do not use in a cluster.

identity

supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.

sequence

uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int

hilo

uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database.

seqhilo

uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.

uuid

uses a 128-bit UUID algorithm to generate identifiers of type string that are unique within a network (the IP address is used). The UUID is encoded as a string of 32 hexadecimal digits in length.

guid

uses a database-generated GUID string on MS SQL Server and MySQL.

native

selects identity, sequence or hilo depending upon the capabilities of the underlying database.

assigned

lets the application assign an identifier to the object before save() is called. This is the default strategy if no element is specified.

select

retrieves a primary key, assigned by a database trigger, by selecting the row by some unique key and retrieving the primary key value.

foreign

uses the identifier of another associated object. It is usually used in conjunction with a primary key association.

sequence-identity

a specialized sequence generation strategy that utilizes a database sequence for the actual value generation, but combines this with JDBC3 getGeneratedKeys to return the generated identifier value as part of the insert statement execution. This strategy is only supported on Oracle 10g drivers targeted for JDK 1.4. Comments on these insert statements are disabled due to a bug in the Oracle drivers.

Grails on Groovy > Grails 2.X > How is the invocation sequence of Grails filters defined | Sequence of Filter Execution

I am using filters to handle authentication and some other pre-condition checks for a Grails application. I've run into a situation where it'd be nice to ensure that filter A is always invoked before filter B
If several filters are declared within one class, it's obvious that they'll be executed in the order that they were declared like below code block.
package com.pkm

class SecurityFilters {

    def filters = {
        filter1(controller:'*', action:'*') {
            before = {
                println("FILTER-1")
            }
            after = { Map model ->

            }
            afterView = { Exception e ->

            }
        }

        filter2(uri: "/**") {
            before = {
                println("FILTER-2")
            }
            after = { Map model ->

            }
            afterView = { Exception e ->

            }
        }
    }
}
Now what will happen if they would defined in different classes. Yes, there is a way around and that is dependsOn. You can define dependsOn on which filter it will depend on. Say I created another filter named Security2Filters and set my first filter named SecurityFilters to dependsOn. So SecirutyFilters will be execute before Security2Filters.
package com.pkm

class Security2Filters {
    def dependsOn=[SecurityFilters]

    def filters = {
        all(controller:'*', action:'*') {
            before = {
                println("FILTER-3")
            }
            after = { Map model ->

            }
            afterView = { Exception e ->

            }
        }
    }
}

Grails on Groovy > Grails 2 > How to know programmatically if a view or a layout file exists in grails | Check if view or layout file exists

I want to know programmatically if a view or a layout exists in grails.
Since Grails 2.0, you can inject a GrailsConventionGroovyPageLocator:
package com.pkm

import org.codehaus.groovy.grails.web.pages.discovery.GrailsConventionGroovyPageLocator

class HomeController {
    GrailsConventionGroovyPageLocator groovyPageLocator

    def index() {
        println(groovyPageLocator.findView("myView"))
        println(groovyPageLocator.findViewByPath("/home/myView"))
        println(groovyPageLocator.findTemplate("myTemplate"))
        println(groovyPageLocator.findTemplateByPath("/home/myTemplate"))
        render(text: "Done")
    }
}
Will output like below, it no view found, null return.
URL [file:C:/Grails-project-path/grails-app/views/home/myView.gsp]

URL [file:C:/Grails-project-path/grails-app/views/home/myView.gsp]

URL [file:C:/Grails-project-path/grails-app/views/home/_myTemplate.gsp]

URL [file:C:/Grails-project-path/grails-app/views/home/_myTemplate.gsp]

Sunday, December 3, 2017

GRAILS GROOVY | GString Template Engine | Parse Simple String AS GString Template | String GSP Parser




def gEngine = new groovy.text.GStringTemplateEngine()
def binding = ["a": "a"]
String testVar = gEngine.createTemplate("MY ENGINE STRING AS=\${a}").make(binding).toString()
println(testVar)

Thursday, November 30, 2017

Simple try & catch TagLib | Tag Library for Grails GSP views

First you have to create a TagLib as below:









With following contents:


package com.pkm.taglib

class TryCatchTagLib {
    static namespace = "ui"

    def Try = { attrs, body ->
        try {
            out << body()
            request.exception = null
        }
        catch (Throwable e) {
            request.exception = e
        }
    }

    def Catch = { attrs, body ->
        if (request.exception) {
            out << body(exception: request.exception)
            request.exception = null
        }
    }
}


And use of try-catch as below:


<ui:try>
    SOME WORK I AM TRYING
</ui:try>
<ui:catch>
    GOT EXCEPTION=${exception}
</ui:catch>


Tuesday, November 21, 2017

Grails Groovy Sample DataSource Configuration For Database Connection

You need to edit DataSource.groovy file as below:


dataSource {
    pooled = true
    jmxExport = true
    driverClassName = "com.mysql.jdbc.Driver"
    dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
    dbCreate = "update"
    username = "root"
    password = ""
    logSql = false
    loggingSql = false
    properties {
        maxActive = 1000
        maxIdle = 100
        minIdle = 50
        initialSize = 1
        minEvictableIdleTimeMillis = 60000
        timeBetweenEvictionRunsMillis = 60000
        numTestsPerEvictionRun = 3
        maxWait = 10000
        testOnBorrow = true
        testWhileIdle = true
        testOnReturn = true
        validationQuery = "SELECT 1"
        minEvictableIdleTimeMillis = 1800000
        timeBetweenEvictionRunsMillis = 1800000
    }
}
hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = true
    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
    cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider'
    format_sql = false
    use_sql_comments = false
}

// environment specific settings
environments {
    development {
        dataSource {
            url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8"
            logSql = true
            loggingSql = true
        }
    }
    test {
        dataSource {
            url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8"
            logSql = true
            loggingSql = true
        }
    }
    production {
        dataSource {
            url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8"
        }
    }
}
log4j = {
    debug 'org.hibernate.SQL'
    trace 'org.hibernate.type.descriptor.sql.BasicBinder'
}



Grails Groovy Use Groovy Source Class As Singleton Bean | Custom Bean Definition | Transactional Bean



This will act as a transnational bean

First put the below settings to 'Config.groovy'

grails.hibernate.cache.queries = true
grails.databinding.convertEmptyStringsToNull = true

Need to add/modify below contents to 'BuildConfig.groovy' to enable database connection using MYSQL:

grails.project.dependency.resolver = "maven" // or ivy
grails.project.dependency.resolution = {
    // inherit Grails' default dependencies
    inherits("global") {
        // specify dependency exclusions here; for example, uncomment this to disable ehcache:
        // excludes 'ehcache'
    }
    log "error" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
    checksums true // Whether to verify checksums on resolve
    legacyResolve false // whether to do a secondary resolve on plugin installation, not advised and here for backwards compatibility

    repositories {
        inherits true // Whether to inherit repository definitions from plugins

        grailsPlugins()
        grailsHome()
        mavenLocal()
        grailsCentral()
        mavenCentral()
        // uncomment these (or add new ones) to enable remote dependency resolution from public Maven repositories
        //mavenRepo "http://repository.codehaus.org"
        //mavenRepo "http://download.java.net/maven/2/"
        //mavenRepo "http://repository.jboss.com/maven2/"
        mavenRepo "https://oauth.googlecode.com/svn/code/maven"
    }

    dependencies {
        // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes e.g.
        compile "org.springframework:spring-orm:$springVersion"
        runtime 'mysql:mysql-connector-java:5.1.29'
        runtime 'org.springframework:spring-test:4.0.5.RELEASE'
        runtime "commons-httpclient:commons-httpclient:3.1"
        runtime "org.apache.httpcomponents:httpclient:4.3.3"
        runtime 'net.oauth.core:oauth-httpclient4:20090913'
    }

    plugins {
        build ":tomcat:7.0.55"
        runtime ":hibernate4:4.3.6.1"
        compile ":rendering:1.0.0"
        compile ":browser-detection:0.4.3"
        compile ':cache:1.1.8'
        compile ":mail:1.0.5"
        compile ":asset-pipeline:1.9.9"
        compile ':quartz:1.0.2'
    }
}

Below may be you database configuration (DataSource.groovy):

dataSource {
    pooled = true
    jmxExport = true
    driverClassName = "com.mysql.jdbc.Driver"
    dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
    dbCreate = "update"
    username = "root"
    password = ""
    logSql = false
    loggingSql = false
    properties {
        maxActive = 1000
        maxIdle = 100
        minIdle = 50
        initialSize = 1
        minEvictableIdleTimeMillis = 60000
        timeBetweenEvictionRunsMillis = 60000
        numTestsPerEvictionRun = 3
        maxWait = 10000
        testOnBorrow = true
        testWhileIdle = true
        testOnReturn = true
        validationQuery = "SELECT 1"
        minEvictableIdleTimeMillis = 1800000
        timeBetweenEvictionRunsMillis = 1800000
    }
}
hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = true
    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
    cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider'
    format_sql = false
    use_sql_comments = false
}

// environment specific settings
environments {
    development {
        dataSource {
            url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8"
            logSql = true
            loggingSql = true
        }
    }
    test {
        dataSource {
            url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8"
            logSql = true
            loggingSql = true
        }
    }
    production {
        dataSource {
            url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8"
        }
    }
}
log4j = {
    debug 'org.hibernate.SQL'
    trace 'org.hibernate.type.descriptor.sql.BasicBinder'
}

Now create a domain class like below:

package com.pritom

class Home {
    Long id
    String name
    String roll

    static constraints = {
        name blank: false
        roll blank: false, unique: true
    }
}

Below is the most important class which will be act as a singleton bean in our system:

package com.pritom

import org.springframework.transaction.annotation.Transactional
/**
 * Created by pritom on 21/11/2017.
 */
@Transactional(rollbackFor = [Exception, NoClassDefFoundError])
class MyBean {
    {
        println("BEAN-INITIALIZATION----------------$from------------------")
    }

    private String from = null

    void setFrom(String x) {
        this.from = x
    }

    void testPrint(String a) {
        println("Bean-class=${this.toString()}===${a}-----------$from")
        Thread.sleep(2000L)
        if (true) new Home(name: "Home-" + Home.count(), roll: String.valueOf(System.currentTimeMillis())).save()
        println("Home-count=${Home.count()}")
        if (true) throw new NoClassDefFoundError("Yeah!!!")
    }
}

We are not completed yet, need to initialize bean from resource.groovy as below:

beans = {
    myBean(MyBean) { bean ->
        bean.scope = 'singleton' // Set bean as singleton
        from = "Resource.groovy" // Set value to a field of class MyBean when initializing
    }
}

And finally test bean from some controller like below:

package com.pritom

class HomeController {
    def myBean

    def index() {
        try {
            myBean.testPrint("1")
            myBean.testPrint("2")
        }
        catch (Throwable ex) {
            println("Error=${ex.getMessage()}")
        }
        render ""
    }
}

And you can download source code from here