Friday, April 24, 2015

Grails and Pdf creation

In my businness application, I needed to print report in a pdf file.Before Grails 2.5.0, I used export-plugin with success.I tried to use with Grails 2.5.0 but I obtained compilation errors.That's why I looked for other solutions.
I found rendering plugin but I had an error when rendering ( see ).
Finaly, I decided to do it myself with apache pdfbox

In my BuildConfig.groovy, I added the dependency :

   dependency {  
     compile "org.apache.pdfbox:pdfbox:1.8.9"  

And here is the code in my controller :

 class AppRetailController {  
   def renderFormPDF(){  
     List<App> apps = new ArrayList<>()  
     String title = ""  
     String param = params.get("serverSelect")  
     Fill the list apps  
           title= "Liste de toutes les applications sur " + param  
           title += " (" + apps.size() + ")"  
           // Create all needed for Pdf document  
     PDDocument document = new PDDocument();  
     PDPage page = new PDPage();  
     PDPageContentStream contentStream;  
           // Here I want 30 rows by page  
     int pageNumber = apps.size()/30 + 1"Page number :" + pageNumber)  
     int countApp = 0  
           // for each page I draw table with datas  
     for (int i=1; i<=pageNumber; i++) {"countApp :" + countApp)  
       page = new PDPage();  
       contentStream = new PDPageContentStream(document, page);  
       int max = countApp + 30  
       if (max > apps.size()) {  
         max = apps.size() - 1  
       drawTable(page, contentStream, 700, 100, apps[countApp..max], title);  
       countApp = countApp + 30 + 1  
     render( file:new File("report.pdf"), fileName: "report.pdf")  
    * @param page  
    * @param contentStream  
    * @param y the y-coordinate of the first row  
    * @param margin the padding on left and right of table  
    * @param content a 2d array containing the table data  
    * @throws IOException  
   def drawTable(PDPage page, PDPageContentStream contentStream,  
                  float y, float margin,  
                  List<App> apps, String title) throws IOException {  
     final int rows = apps.size() + 1;  
     final int cols = 3;  
     final float rowHeight = 20f;  
     final float tableWidth = page.findMediaBox().getWidth()-(2*margin);  
     final float tableHeight = rowHeight * rows;  
     final float colWidth = tableWidth/(float)cols;  
     final float cellMargin=5f;  
     //draw the rows  
     float nexty = y ;  
     for (int i = 0; i <= rows; i++) {  
       nexty-= rowHeight;  
     //draw the columns  
     float nextx = margin;  
     for (int i = 0; i <= cols; i++) {  
       nextx += colWidth;  
     //now add the text  
     float textx = margin+cellMargin;  
     float texty = y-15;  
     //Define colunm title  
     textx += colWidth;  
     textx += colWidth;  
     contentStream.drawString("Chemin dans ARENA");  
     textx += colWidth;  
     textx = margin+cellMargin;  
     apps.each {  
       textx += colWidth;  
       String desc = it.description  
       if (desc.equals("EMPTY")) {  
         desc = ""  
       textx += colWidth;  
       String path = it.arenaPath  
       if (path == null) {  
         path = ""  
       textx += colWidth;  
       textx = margin+cellMargin;  

So, this is not the best solution.I would have preferred something like rendering plugin but it's works and I needed it immediately.A big thanks to this blog for the use of pdf library : 

Hope this help,

See also :

Friday, April 3, 2015

Grails : an example of remoteFunction with two parameters

In my businness web application, I wanted to use a selectbox which call a controller method to check mail address stores in ldap. On change of selectbox, it will automaticaly check if the mail exists in ldap.In this paper, we will talk about the use of remoteFunction with 2 parameters.I wrote it because I had difficulties with this ( especially the syntax ) and I hope it could help someone !

The gsp

In my gsp, I had an input text and a select box.The remoteFunction calls the action of the controller ajaxCheckMailInLDAP. Parameters are passed in params. ( Be carefull at the syntax ).Once achieved, the javascript method checkLdapMail(data) called.


// Show the result
 <div id="create_status_ok" class="alert alert-success" role="alert" style="display: none">
        <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
        <span class="sr-only">Info:</span>
        Vérification dans le LDAP OK ! vous pouvez créer cette adresse.
// form that use remoteFunction 
   <input type="text" class="form-control" id="rne" name="rne" placeholder="....087XXX" value="">  
   <g:select noSelection="['0':'Choisir un type de boîte']" optionKey="id" optionValue="fullNameType" name="shortNameType" id="selecttype" from="${toolprod.MailType.list()}"
       params:'\'id=\' + this.value + \'&rne=\' + document.getElementById(\'rne\').value',

The controller's action

Here is my controller wich render an array as JSON.Note that the name of data variable is important !

 class ToolsController {  
   def ajaxCheckMailInLDAP = { "ajaxCheckMailInLDAP()")
       String mail = params.rne + "@.."

        // Init JSON data
        def data = [:]
        data.put("id", "1")
        if (checkMail(mail)) {// just return a boolean
            data.put("text", "KO")
        } else {
            data.put("text", "OK")
        data.put("mail", mail)"ajaxCheckMailInLDAP() END" + mail)
        render data as JSON 

To finish, below is the javascript method :

     * Show result stored in data on html page
     * @param data JSON data send by ajaxCheckMailInLDAP in controller.
    function checkLdapMail(data) {


        if (data.text == "KO") {
            document.getElementById('create_status_ko').textContent= data.mail.toString() + " existe deja dans le LDAP !";
        if (data.text == "OK") {
            document.getElementById('btnSubmit').disabled = false;

        if (data.text == "EMPTY") {
            document.getElementById('create_status_ko').textContent= "le rne est vide !";

        console.log("checkLdapMail() : end");

To make it works, I use the parameter name data.An other important things, I used Grails 2.4.4 to make this example.
I hope it will help you in your developpement.

Tuesday, March 31, 2015

Upgrade Grails 2.4.4 to 2.5.0

I successfully upgraded Grails 2.4.4 to 2.5.0 by following the Release Version text files ( ).

I only upgraded plugins version in BuildConfig.groovy:

  • build ':tomcat:'
  • compile ':cache:1.1.8'
  • compile ':scaffolding:2.1.2'
  • compile ':asset-pipeline:2.1.5'

I also met an exception because I forget to change cache.region.factory_class in Datasource.groovy ( cf Release Version ).
Here is the exception :

2015-03-31 16:28:39,590 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener  - Error initializing the application: Error creating bean with name 'transactionManagerPostProcessor': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'transactionManager_lookup' while setting constructor argument with key [1]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager_lookup': Cannot resolve reference to bean 'sessionFactory_lookup' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory_lookup': Invocation of init method failed; nested exception is org.hibernate.cache.CacheException: net.sf.ehcache.CacheException: Another unnamed CacheManager already exists in the same VM. Please provide unique names for each CacheManager in the config or do one of following:
1. Use one of the CacheManager.create() static factory methods to reuse same CacheManager with same name or create one if necessary
2. Shutdown the earlier cacheManager before creating new one with same name.
The source of the existing CacheManager is: DefaultConfigurationSource [ ehcache.xml or ehcache-failsafe.xml ]

To solves it, I only have to do the following change in Datasource.groovy :

hibernate {
    cache.region.factory_class = 'org.hibernate.cache.SingletonEhCacheRegionFactory'

Tuesday, January 13, 2015

Grails update successfully from 2.3.11 to 2.4.4

I successfully update Grails from 2.3.11 to 2.4.4 by following and It was not a simple update due to a substancial existing web site.I had error at startup and many things to do to make it works.
So, here are some advices to help to complete this task :

Upgrade plugins

Be carefull, if you don't upgrade plugins like cache, hibernate, jquery, you will have stranges errors.

Plugin asset-pipeline replace resource plugin

You will have to move directory and organize them in assets directory and also change all include in GSP.Possibles surprises will perhaps appear : see

Plugin export:1.6

To now, it doesn't work for me


I delete templates directory end recreate it by command : grails install templates.
It fixes some errors.


There is a new annotation : @Validateable(nullable = true)

Sunday, December 14, 2014

Grails and GSON : Could not find artifact

I had the following problem by adding GSON at my project :

Error |
Resolve error obtaining dependencies: Could not find artifact in grailsCentral ( (Use --stacktrace to see the full trace)

Solution was simple.To solve this problem, put GSOn in dependencies section and not in plugin section :

dependencies {
        // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes e.g.
        runtime 'mysql:mysql-connector-java:5.1.24'
        compile ''
More details on :

Thursday, October 30, 2014

How to export your datas easily in different format with Grails ( pdf, excel ... )

In my business web site, I have array with datas and I want a way to publish it in severeal format.
To achieve this, it exists the Grails export plugin.Here is what you will have under your array :

This tutorial will explain how to quickly use the export plugin and problems I met.

Plugin install

To install, the plugin I added in BuildConfig.groovy :

repositories {
mavenRepo ""
plugins {

compile ":export:1.6"

If you don't add, the Maven Repositories, you will have this error :

Resolve error obtaining dependencies: Could not find artifact org.odftoolkit:odfdom-java:jar:0.8.5 in grailsCentral ( (Use --stacktrace to see the full trace)
Error |

Modify your GSP

     <r:require module="export"/>
     <export:formats /> 

The export tag will display icons and the require will had required css.
If you clic on pdf button,

Notes :
  • You can put the export tag where you want in the GSP
  • You can specify format you want :

<export:formats formats="['csv', 'excel', 'ods', 'pdf', 'rtf', 'xml']" /> 

Modify your controller

Here is my controller :

class ToolsController {

    // Export service provided by Export plugin

    def exportService

    def grailsApplication  //inject GrailsApplication

    def index() {

        if(!params.max) {

            params.max = 10


        if ((params.extension != null)) {


            def format=params.extension

            if ("xls".equals(params.extension)) {



            if(format && format != "html"){

                response.contentType = grailsApplication.config.grails.mime.types[format]

                response.setHeader("Content-disposition", "attachment; filename=check.${params.extension}")

                List fields = ["machineName", "fileName", "confServerName"]

                Map labels = ["machineName": "Nom de machine", "fileName": "Nom de fichier",   "confServerName":"Valeur du ServerName"]

                Map formatters = new HashMap()

                Map parameters = new HashMap()

                exportService.export(format, response.outputStream,Check.list(params), fields, labels, formatters, parameters)





I had a Check domain class with 3 fields : machineName, fileName, confServerName.These fields will be display in the pdf

Notes :
  • I had some problem with params.format values.In my case, it was always null and I don't know why.That's why my code is not exactly the same of the documentation
  • You can also format text and adjust column size with formatters and parameters.See documentation for more details.

If you want more details about plugin installation, you could see the documentation :
Here is my Grails configuration :
  • Grails 2.3.11
  • Plugin ; runtime ":resources:1.2.1"

Tuesday, September 16, 2014

Grails : database management in multiple environments

With Grails, you can use a database for a specific environments.If you change environments, Grails will use the database you define.

For example, you can define the following environments :

  • development: In memory database
  • test:               Mysql on localhost
  • production :   Mysql on production machine

Define your environments in DataSource.groovy

hibernate {
    cache.use_second_level_cache = true
    cache.use_query_cache = false
    cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory' // Hibernate 3
//    cache.region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory' // Hibernate 4

// environment specific settings
environments {
    development {
        dataSource {
            dbCreate = "create-drop" // one of 'create', 'create-drop', 'update', 'validate', ''
            url = "jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
        dataSource_lookup {
            pooled = true
            driverClassName = "org.h2.Driver"
            username = "sa"
            password = ""
    test {
        dataSource {
            pooled = true
            driverClassName = "com.mysql.jdbc.Driver"
            dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
            dbCreate = "create-drop"
            url = "jdbc:mysql://localhost/toolprod"
            username = "root"
            password = ""

    production {
        grails.config.locations = ["file:/opt/apache-tomcat-7.0.47/conf/ConfigToolprod.groovy"]

Production Environment

As you can see, the way you define production environment is quite different.You define a path where are stored datasource.
With this sort of configuration, you doesn't have to build your Grails project an other time if you want to change the login and password.Moreover, authentication is only in one place.I find it much better.

Below, there is an example of my ConfigToolprod.groovy file. An important thing, this configuration will permit Mysql database to reconnect automaticaly.

Comment : File contains a lot parameter because they had a bug in a old version of Grails.You certainly doesn't need all parameters.


dataSource {
    pooled = true
    dbCreate = "update"
    url = "jdbc:mysql://localhost/toolprod"
    driverClassName = "com.mysql.jdbc.Driver"
    dialect = org.hibernate.dialect.MySQL5InnoDBDialect
    username = "LOGIN"
    password = "PASSWORD"
    properties {
       // Documentation for Tomcat JDBC Pool
       jmxEnabled = true
       initialSize = 5
       maxActive = 50
       minIdle = 5
       maxIdle = 25
       maxWait = 10000
       maxAge = 10 * 60000
       timeBetweenEvictionRunsMillis = 5000
       minEvictableIdleTimeMillis = 60000
       validationQuery = "SELECT 1"
       validationQueryTimeout = 3
       validationInterval = 15000
       testOnBorrow = true
       testWhileIdle = true
       testOnReturn = false
       ignoreExceptionOnPreLoad = true
       jdbcInterceptors = "ConnectionState;StatementCache(max=200)"
       defaultTransactionIsolation = java.sql.Connection.TRANSACTION_READ_COMMITTED // safe default
       // controls for leaked connections
       abandonWhenPercentageFull = 100 // settings are active only when pool is full
       removeAbandonedTimeout = 120
       removeAbandoned = true
       // use JMX console to change this setting at runtime
       logAbandoned = false // causes stacktrace recording overhead, use only for debugging
       // JDBC driver properties
       // Mysql as example
       dbProperties {
           // Mysql specific driver properties
           // let Tomcat JDBC Pool handle reconnecting
           // truncation behaviour
           // mysql 0-date conversion
           // Tomcat JDBC Pool's StatementCache is used instead, so disable mysql driver's cache
           // Tomcat JDBC Pool's StatementFinalizer keeps track
           // performance optimization: reduce number of SQLExceptions thrown in mysql driver code
           // enable MySQL query cache - using server prep stmts will disable query caching
           // metadata caching
           // timeouts for TCP/IP
           // timer tuning (disable)
           // misc tuning