Saturday, October 3, 2015

Grails 3 and Netbeans 8.0.2 : warning about Gradle 2.3 compatibility


I had a warning in Netbeans IDE 8.0.2 about Gradle 2.3 compatibility.I followed the following steps to clear this warning. In files tab, I did a right clik on my project.I choose properties and Gradle project Categories.Then I changed the Gradle home to my Gradle 2.7 directory like the following :






And the annoying warning disappeared !

Saturday, September 26, 2015

Eclipse plugin :no menu in Extension when right clicks


I'm looking at eclipse plugin and I met a problem in extension view : I can't access to the extension menu when I did right click.

I have also the following warning in Extensions View : No schema found for the “org.eclipse.ui.menus” extension point

To solves it,  I add Eclipse RCP Target Components ( see http://stackoverflow.com/questions/8366303/no-schema-found-for-the-org-eclipse-ui-menus-extension-point )

  1. In Eclipse, go to Help > Install New Software... 
  2. Update site: http://download.eclipse.org/eclipse/updates/4.5
  3. Choose "Eclipse RCP Target Components" and press Next to install them

Now the menu appears :




Eclipse IDE for Java Developers
Version: Mars Release (4.5.0)














Sunday, September 20, 2015

Grails 3 and IDE support


I'm looking at support of grails 3 by the IDE.
To now, here is an overview :
  • Eclipse : none support, plug-in disappeared from STS.
  • Intellij : appears to be support but you to pay licensing ...
  • Netbeans : begins of support
The good point is Netbeans 8.0.2 recognizes Grails 3 project.So, i was able to create a new Grails 3 project.You can launch you application and there is also syntax highlights in GSP.
However, it's just the beginning and it needs some works.But, you can begin to practice with Grails 3.

https://stackoverflow.com/questions/29441503/grails-3-0-support-in-netbeans/32425071#32425071

One comment, under Eclipse, you can import Grails project as a Gradle project like said in documentation.But, I didn't find how to have syntax highlights in GSP.

Friday, September 18, 2015

Upgrade Grails 2.5.0 to 2.5.1

I successfully upgrade Grails to the version 2.5.1It's quite simple.You only have to follow the release note about plugins update.
I met only one problem.I had this warning : Script 'Upgrade' not found.

To solve that issue, you have to select 3 (SetGrailsVersion) ant it will make the update.

|Running pre-compiled script
|Script 'Upgrade' not found, did you mean:
   1) MigrateDocs
   2) IntegrateWith
   3) SetGrailsVersion
   4) InstallDependency
   5) DependencyReport
Please make a selection or enter Q to quit: 3


With this update, I solved the following error : http://stackoverflow.com/questions/32562678/grails-plugin-error-class-path-resource-cannot-be-resolved

Wednesday, September 16, 2015

How to import files in GRAILS ?

In business web site, we often used to import config files.There are many way to achieve this in GRAILS.In this paper, we will talk about two possibilities but not about batch because it doesn't work for me in GRAILS 2.5.0.

An IHM to import file

You can import files with a classical html form like the following :








A form example : form.gsp

Below, here is an example of Grails upload form by using g:uploadForm tags.This form, when submit, calls the init action from the admin controller.It passed files in parameter with Input tag.The input file with the parameter multiple will permit to upload severeal files.

<g:uploadForm action="init" controller="admin">
    <form role="form">
        <div class="form-group">
            <label for="files">Choix du fichier à parser</label>
            <input type="file" id="files" name="files[]" multiple>
            <p class="help-block">Vous devez choisir un fichier httpd.conf</p>
        </div>
        <div class="form-group">
            <label for="machinename">Nom de la machine</label>
            <input type="text" class="form-control" id="machinename" name="machinename"      placeholder="....ac-limoges.fr" value="">
        </div>
        <button type="submit" class="btn btn-info">Submit</button>
    </form>
</g:uploadForm>





Controller


For example, to parse a file, you could do the following :
      
class AdminController {
  
   def init() {
        if (request instanceof MultipartHttpServletRequest) {
            ...
            request.getFiles("files[]").each { file ->
                log.info("init() file to parse:" + file.originalFilename)
                       InputStream inputStream = file.inpustream
                       BufferedReader = new BufferedReader(new InputStreamReader(inputStream))

                        try {
                            String ldapUser = EMPTY
                            String ldapPwd = EMPTY
                            String ldapHost = EMPTY
                            String ldapPort = EMPTY

                            while ((line = br.readLine()) != null) {
                            ...
                            }
                        }
            }
            ...
        }
    }

...

The arry files[] will contain all import files.You have to notice that file is type of org.springframework.web.multipart.MultiPartFile and not java.io.File


Import files automaticaly


An other way, is to import files automaticaly. You just have to do a method in the controller like the following :

class AdminController {
    def reloadData() {
        def path = "E:\\projet\\toolprod\\import\\"

        log.info("reloadData() Initializing application from httpd.conf files in machine directory ...")
        new File(path).listFiles().findAll{
            if (it.isDirectory()) {
                log.info("reloadData() Machine name ( Directory name ) :" + it.name)
                String machineName = it.name
                log.debug("reloadData() files list:" + it.listFiles())
                for (File f : it.listFiles()) {
                ...

            }

        }

...

Then you need to access at the following url : http://localhost:8080/appli/admin/reloadData
After that, it's easy to make a crontab with a curl to make automatisation ...

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 http://stackoverflow.com/questions/29694796/null-pointer-exception-with-grails-rendering-plugin ).
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  
     log.info("Page number :" + pageNumber)  
     int countApp = 0  
           // for each page I draw table with datas  
     for (int i=1; i<=pageNumber; i++) {  
       log.info("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  
       contentStream.close();  
       document.addPage(page);  
     }  
     document.save("report.pdf");  
     document.close();  
     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++) {  
       contentStream.drawLine(margin,nexty,(float)(margin+tableWidth),nexty);  
       nexty-= rowHeight;  
     }  
     //draw the columns  
     float nextx = margin;  
     for (int i = 0; i <= cols; i++) {  
       contentStream.drawLine(nextx,y,nextx,(float)(y-tableHeight));  
       nextx += colWidth;  
     }  
     //now add the text  
     contentStream.setFont(PDType1Font.HELVETICA_BOLD,14);  
     contentStream.beginText();  
     contentStream.moveTextPositionByAmount((float)margin+cellMargin+10,(float)(y+20));  
     contentStream.drawString(title);  
     contentStream.endText();  
     contentStream.setFont(PDType1Font.HELVETICA_BOLD,12);  
     float textx = margin+cellMargin;  
     float texty = y-15;  
     //Define colunm title  
     contentStream.beginText();  
     contentStream.moveTextPositionByAmount(textx,texty);  
     contentStream.drawString("Nom");  
     contentStream.endText();  
     textx += colWidth;  
     contentStream.beginText();  
     contentStream.moveTextPositionByAmount(textx,texty);  
     contentStream.drawString("Description");  
     contentStream.endText();  
     textx += colWidth;  
     contentStream.beginText();  
     contentStream.moveTextPositionByAmount(textx,texty);  
     contentStream.drawString("Chemin dans ARENA");  
     contentStream.endText();  
     textx += colWidth;  
     texty-=rowHeight;  
     textx = margin+cellMargin;  
     contentStream.setFont(PDType1Font.HELVETICA,11);  
     apps.each {  
       contentStream.beginText();  
       contentStream.moveTextPositionByAmount(textx,texty);  
       contentStream.drawString(it.name);  
       contentStream.endText();  
       textx += colWidth;  
       contentStream.beginText();  
       contentStream.moveTextPositionByAmount(textx,texty);  
       String desc = it.description  
       if (desc.equals("EMPTY")) {  
         desc = ""  
       }  
       contentStream.drawString(desc);  
       contentStream.endText();  
       textx += colWidth;  
       contentStream.beginText();  
       contentStream.moveTextPositionByAmount(textx,texty);  
       String path = it.arenaPath  
       if (path == null) {  
         path = ""  
       }  
       contentStream.drawString(path);  
       contentStream.endText();  
       textx += colWidth;  
       texty-=rowHeight;  
       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 : http://fahdshariff.blogspot.fr/2010/10/creating-tables-with-pdfbox.html 

Hope this help,

See also : http://grails.github.io/grails-doc/2.5.x/ref/Controllers/render.html

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.

example

// 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.
 </div> 
 ...
 
// form that use remoteFunction 
<form>
   <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()}"
    onchange="
    cleanMsg();
    ${remoteFunction(
       controller:'tools',
       action:'ajaxCheckMailInLDAP',
       params:'\'id=\' + this.value + \'&rne=\' + document.getElementById(\'rne\').value',
       onSuccess:'checkLdapMail(data)')}"
    ></g:select> 
 </form>  


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 = {  
        log.info("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)
        log.info("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) {
        console.log("checkLdapMail()");

        document.getElementById('selecttype').value=0;
        document.getElementById('create_status_ko').style.display='none';
        document.getElementById('create_status_ok').style.display='none';
        document.getElementById('create_status_info').style.display='block';

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

        if (data.text == "EMPTY") {
            document.getElementById('create_status_info').style.display='none';
            document.getElementById('create_status_ko').style.display='block';
            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.