Anuj Aneja « Intelligrape Groovy & Grails Blogs
Subscribe via E-Mail:

anuj

Posts by anuj:

  • Removing/replacing special character from database.

    11 Jun 2012 in Database

    Recently in one of my project i faced a problem that database was having special character, which is shown as space on the User Interface.

    So as to solve this issue i found a very simple solution which consists of following steps:

    1. First, you just need to identify which type special character to be removed/replaced like in my case it was shown as space but stored as <?> in the db.

    For that you can use the query.

    select HEX(email) from person;

    and you can also refer to this link for ASCII code of character. In my case it was 160.

    2.  Now, next step is simple just run this query.

     update person set email=replace(email,char(160),''); 

    Thats it !!!  :)

    It helps me a lot!!! Hope that helps you guys!!!

    Anuj Aneja

    Intelligrape Software Pvt. Ltd.

  • Mysql top just like we have top command in Linux

    08 Oct 2011 in Grails
    Once in my grails project i was facing the problem of freeze of server.When this happens tomcat becomes unresponsive.Later on by analyzing the thread dump we found that this problem might be due to the database and tomcat communication. So as to analyse how many connection are active at mysql end we found a query.

    Show processlist;

    Which gives us the result as:
    Output:
    +—–+——+———–+———————+———+——+——-+——————+

    | Id  | User | Host      | db                      | Command | Time | State | Info             |

    +—–+——+———–+———————+———+——+——-+——————+

    | 242 | root | localhost |      test_db    | Query   |    0 | NULL  | show processlist |

    +—–+——+———–+———————+———+——+——-+——————+

    The output shows how many connections are active and their properties.
    But for this you need to run the query again and again to analyse the connections information. For a better experience we can use mytop  which is very easy to install and just like the top in linux, simple steps need to be followed to make it work.

    Step 1:Install mytop using the following command.

    anuj@intelligrape:~$ sudo apt-get install mytop
    Step 2:
    After installation we need make a configuration file .mysqlconfig any where
    e.g
    anuj@intelligrape:~$ vim .mysqlconfig
    user=

    pass=

    host=localhost

    db=db_name

    delay=5

    port=330

    6socket=

    batchmode=0

    header=1

    color=1

    idle=1

    For more option you can refer to documentation of mytop .
    Step 3:
    Now just need run this command to see the mysqltop working.
    anuj@intelligrape:~$ mytop ~/.mysqlconfig
    output:

    Thats it ! Internally it runs the query “show processlist” and is very elegant for analysing mysql connections.

    This helps me! Hope this helps you guys!
    Anuj Aneja

    Intelligrape Software

  • Making your own custom command for a script file which can be executed from any user.

    05 Oct 2011 in Linux
    One way to execute the script file via command can be making of alias and put it in .bashrc , but this will only be available to that user. So for creating a user-defined command which can be executed from any where for any user following steps need to be followed:
    1. Make a script file which has the set of commands to be executed and add ‘x’ permission for all.e.g.

    Here is a script file(/home/anuj/myscript/myscript.sh) which echo’s current directory on the terminal.

    echo $PWD

    2. Make a symbolic link  mycommand pointing to myscript.sh in /usr/bin or /sbin/ or /usr/sbin directory  (Differences between them can referred from here).

    cd /sbinln -s /home/anuj/myscript/myscript.sh mycommand
    

    Now you can use command “which” to see which file will executed if we type the command named “mycommand”

    
    which mycommand
    
    Output:  /sbin/mycommand
    
    anuj@intelligrape:/tmp$ mycommand
    
    Output:  /tmp/
    
    

    Its done! :)  Next question would be where we can use it to make our life easier??. Well ! Generally we have deployment script for that we need to switch to user and then we need to run the script file instead of doing that we can make a softlink of the script file and put it in the /sbin or /usr/sbin etc. Like some software packages like apache put softlink to there script file in /sbin.e.g.  a2ensite is a softlink to a2enmode in /usr/sbin which is a executable script file.
    There can be some better way to achieve the same so suggestions are most welcomed.

    Hope this helps you guys !

    Anuj Aneja
    Intelligrape Software

  • Getting started with extJS

    14 Apr 2011 in Grails

    Ext.JS JavaScript Framework a cross-browser JavaScript library for building rich internet applications. It is built for developing high performance, customizable UI widgets and features a well designed, documented and extensible Component model. It is available in both Commercial and Open Source licenses are available.

    Step 1:
    First download the source css and js from here

    Step 2:
    Include the following css and js as

    <link rel="stylesheet" type="text/css" href="../../resources/css/ext-all.css" />
    <script type="text/javascript" src="../../adapter/ext/ext-base.js"></script>
    <script type="text/javascript" src="../../ext-all.js"></script>
    

    Now start writing the code in script tag or make js file.
    jQuery and extJS comparisions:

    Document is ready

    //document is raedy in jQuery
    <script type="text/javascript">
    $(document).ready(function() {
      // do stuff when DOM is ready
    });
    </script>
    
    //in extJS
    <script type="text/javascript">
    Ext.onReady(function() {
      // do stuff when DOM is ready
    });
    </script>
    

    Selecting elements

    // Selecting by ID in jQuery
    var myDiv = $("#element-id");
    // Selecting by ID in Extjs
    var myDiv = Ext.get('element-id');
    // Perform some action on it
    // Add a class
    myDiv.addClass('my-class');
    // Set the width 100 px,
    // true is for applying default animation on change
    myDiv.setWidth(100, true);
    // Retrive some information of the element
    // Get the elements box info as object {x, y, width, height}
    var box = myDiv.getBox();
    
    extJS:
    
    // Select elements with CSS Selector
    var imgs = Ext.select("#my-div div.member img");
    // or select directly from an existing element
    var members = Ext.get('my-div');
    var imgs = members.select('div.member img');
    // Now, any Ext.Element actions can be performed on all the elements in this collection
    

    Dom scripting

    var el1 = Ext.get("my-1st-div");
    var el2 = Ext.get("my-2nd-div");
    // Appending elements
    el1.appendChild("A new paragraph").appendTo(el2)
    // Replcing, removing
    var el3 = Ext.get("my-3rd-div");
    Ext.get("my-4th-div").replace(el3).insertAfter(el2);
    el2.remove()
    

    Events

    // Binding an event in jQuery
    $(".btn").click(function() {
    // Do something on button click
    });
    
    // Binding an event in Extjs
    Ext.select('.btn').on('click', function() {
    // Do something on button click
    });
    

    Ajax

    // Basic request in jQuery
    $.ajax({
    type: "POST",
    url: url,
    data: { x: 'y },
    success: function(msg){
    alert( "Data Saved: " + msg );
    }
    });
    
    // Basic request in Ext
    Ext.Ajax.request({
    url: url,
    params: { x: 'abc' },
    success: function(msg){
    alert( "Data Saved: " + msg );
    }
    });
    

    Here, I have listed the basic difference between jQuery and extJS for complete reference refer extJs API docs
    hope it helps you guys :)

    Anuj Aneja
    Intelligrape Software

  • Linux trick to get your user back to sudo access while you lost your Admin password and you are with no sudo prevailages.

    27 Feb 2011 in Grails

    I was trying to create new user on my machine but some how i create a new user but  i commited a mistake. That is  while making a new accout i forget to make it acive by giving password. And then i make this new account as Administrator and make my old account as Desktop User. Now the old_account can’t run ‘sudo’ command in and i don’t have access to my admin account.Everytime while running a sudo command it give me the error as shown below:

    old_user~$sudo -s
    

    your account is not in sudoers list So this event will be reported.

    And further in Ubuntu you have root account but it not by default active in there you  can switch to the root by typing:

    old_user$su -
    or
    old_user$sudo -s
    

    But will ask for root password which is not activated yet.

    In this situtation i found a solution which can be done by editing sudoers list or group list file stored in /etc/sudoers ,/etc/group but to edit you require root access or sudo access. Which i lost it. Now to come out safe from this fishy situation take the following step:

    1. Boot the system with any  Ubuntu live cd login as ubuntu now.
    2.The password for Ubuntu user is blank and it is also added to sudoers list so now you can run sudo command:

    ubuntu~$sudo -s
    root~$
    

    You are logged in as root.
    3. Now type the following command in order:

    root~$cd  /media/(some long name of you actual installation  folder)/etc/
    root-.......etc/~$chmod 777 group
    root-.......etc/~$vi group
    

    Now i put the old_username in in front of sudo option like :

    sudo:x:27:old_username
    

    And save this file.

    Now the old_user can run sudo command :)
    I restarted my system and run the following commands

    old_user~$sudo -s
    enter password of old user:
    root~$adduser old_user admin
    

    Now old_user become the part of the admin group can perform any sudo,and admin opearation.Hurray !:)
    The comment and any suggestion of doing this in a better way are always welcomed.
    It helps me hope this helps you cheers! :)
    Thanks
    Anuj Aneja
    Inelligrape Software

  • File Uploading using plupload plugin of jquery.

    In my grails project i was having the requirement of having multiple file uploading, but in current implementation there was the problem of button being not loaded in Internet Explorer.For that i found plupload very cool to implement this. It has very cool feature of drag and drop and support for almost all browser. Actually what it does is based on the browser, get the Runtime of the browser.For Documentation, js and css refer link

    In gsp we need to include the js of pluplaod api as shown below:

    <link rel="stylesheet" href="${resource(dir: 'css/plupload/css', file: 'plupload.queue.css')}" type="text/css" media="screen">
    <link rel="stylesheet" href="${resource(dir: 'css/plupload/css', file: 'jquery.ui.plupload.css')}" type="text/css" media="screen">
    <g:set var="fileExtension" value="${new FileExtension()}"></g:set>
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <p:javascript src='jquery-1.3.2'/>
    <script type="text/javascript" src="${resource(dir: "js/plupload", file: "gears_init.js")}"></script>
    <script type="text/javascript" src="${resource(dir: "js/plupload", file: "browserplus-min.js")}"></script>
    <!-- Load source versions of the plupload script files -->
    <script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.js")}"></script>
    <script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.gears.js")}"></script>
    <script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.silverlight.js")}"></script>
    <script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.flash.js")}"></script>
    <script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.browserplus.js")}"></script>
    <script type="text/javascript" src="${resource(dir: "js/plupload", file: "plupload.html5.js")}"></script>
    <script type="text/javascript" src="${resource(dir: "js/plupload", file: "jquery.plupload.queue.js")}"></script>
    <script type="text/javascript">
        var button = '${buttonId}';
    </script>
    
    

    Now we need to write script to load and bind the plupload plugin shown below:

    	<script type="text/javascript">
        var runtimesList;
        if (navigator.userAgent.indexOf("Firefox")!=-1){
            runtimesList='silverlight,browserplus,html4,gears,flash,html5';
        }else{
            runtimesList='html5,silverlight,browserplus,html4,gears,flash';
        }
        $(function() {
            var uploader = new plupload.Uploader({
                runtimes : runtimesList,
                browse_button : 'pickfiles',
                url : url,
                flash_swf_url : '${resource(dir: "js/plupload", file: "plupload.flash.swf")}',
                silverlight_xap_url : '${resource(dir: "js/plupload", file: "plupload.silverlight.xap")}',
                filters : [
                    {title : "Image files", extensions : "gif,png"},
                    {title : "Zip files", extensions : "zip"}
                ]
            });
    
            uploader.bind('Init', function(up, params) {
            });
    
            uploader.bind('FilesAdded', function(up, files) {
                $.each(files, function(i, file) {
                    $('#filelist').append('<div id="' + file.id + '"><span class="mcentd9d" style="font-size:12px; color:green;">File: ' + file.name + ' uploaded successfully!(' + plupload.formatSize(file.size) + ')<b></b><\/span>' + '</div>');
                });
            });
    
            uploader.bind('UploadFile', function(up, file) {
    
            });
    
            uploader.bind('UploadProgress', function(up, file) {
                $('#' + file.id + " b").html(file.percent + "%");
            });
    
            uploader.bind('QueueChanged', function(up) {
                $('#uploadfiles').click();
            });
    
            uploader.bind('FileUploaded', function(up) {
    
            });
            uploader.bind('Error', function(up) {
                alert('Error in uploading file');
            });
    
            $('#uploadfiles').click(function(e) {
                uploader.start();
                e.preventDefault();
            });
            uploader.init();
        });
    
    </script>
    	<div class="attachment">
                   <div id="filelist"></div>
                          <a href="#" class="plupload_button plupload_add" id="pickfiles" style="position: relative; z-index: 0; ">Select File</a>
                          <input type='hidden' id="uploadfiles"/>
              </div>
    

    Now we need to handle the saving part of the file,for each file uploaded in Queue there is separate call to
    the action.It saves the file to the filePath specified.

    def saveAttachment={
          def files = request.getFileMap()
          def file=files.get("file")
          String fileName = file.getOriginalFilename()
          byte[] data=file.getBytes()
          File dir=new File(filePath)//some path...
          if(!dir.exists()){
             dir.mkdirs()
          }
          File actualFile=new File(filePath, fileName)
          actualFile.withOutputStream {out ->
                 out.write data
          }
    }
    

    Disclaimer: As in some cases you might want to can the upload of all the files as there is a different call to action of you can save there files in session, but session for this plupload is different from current user session so you will have to make your own session handling for that!!!

    Note:The total length of files upload and and total uploaded differs in case IE and Firefox. The comments and any suggestions are welcomed.

    Hope it help you guys! Cheer! :)

    Anuj Aneja

    http://www.Intelligrape.com

  • PageChangeListener for debugging in functional testing using Geb

    13 Jan 2011 in Grails

    While using Geb for fuctional testing i require some deugging support so i use PageChangeListener and i found it very useful to find flow of pages while testing my application fuctionally.What it does is it will show the page flow from one page to another.For that we need to just register the PageChangeListener with browser in your Spock Test.

    PageChangeListener will look like this:-

    class EchoingPageChangeListener implements PageChangeListener {
    void pageWillChange(Browser browser, Page oldPage, Page newPage) {
    println "browser '$browser' changing page from '$oldPage' to '$newPage'"
    }
    }
    

    The SpockTest will be having the following code:-

    class TestSpec extends GebSpec{
    def setupSpec() {
    //a kind of init method for our SpockTest
    Browser.drive {
    def listener = new EchoingPageChangeListener()
    //this register the browser with PageChangeListener
    browser.registerPageChangeListener(listener)}
    }
    def "login test"(){
    given:
    to(GmailLoginPage)
    assert at(GmailLoginPage)
    loginModule.loginAs("username@gmail.com","password")
    when:
    assert at(GmailLoginPage)
    then:
    println "invalid username or password"
    
    }
    }
    

    Hope this help you guys!
    Thanks and Regards,
    Anuj Aneja
    anuj@intelligrape.com

    http://intelligrape.com/

  • Using custom tag for embedding the video in grails

    14 Dec 2010 in Grails

    I had to make a video available on my gsp page. So I looked at the grails flash-player plugin.  After going through the documentation I found that it could not be used with videos on Youtube.

    This code given below will generate the script for the flash player on your gsp for playing youtube videos.

    <object width="480" height="385">
    <param name="movie" value="http://www.youtube-nocookie.com/v/YG9RGKYauhE?fs=1&amp;amp;hl=en_US">
    </param>
    <param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always">
    </param>
    <embed src="http://www.youtube-nocookie.com/v/YG9RGKYauhE?fs=1&amp;amp;hl=en_US"
    type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480"
    height="385">
    </embed></object>
    

    This is the general code for a youtube video. URL in the browser for video looks like -http://www.youtube.com/watch?v=YG9RGKYauhE&feature=related.The common thing between embed code and URL of video is the key for the video which uniquely identifies it.So copy and paste the code of the in your gsp page and pass the video key to change the video as you want.
    But to make it simple I made a custom tag like–

    def video={attrs->
            def videoKey=attrs['videoKey']
             def vd={
               object(width:attrs['width']?:"640",height:attrs['height']?:"385"){
                 param(name:"movie",value:"http://www.youtube-nocookie.com/v/${videoKey}?fs=1&amp;amp;hl=en_US")
                 param(name:"allowFullScreen",value:"true")
                 param(name:"allowscriptaccess",value:"always")
                 embed(src:"http://www.youtube-nocookie.com/v/${videoKey}?fs=1&amp;amp;hl=en_US",
    type:"application/x-shockwave-flash",allowscriptaccess:"always",allowfullscreen:"true",
    width:"${attrs['width']?:'640'}", height:"${attrs['height']?:'385'}")
    
               }
    
             }
             def xml=new groovy.xml.StreamingMarkupBuilder().bind(vd)
             out<<xml
    }
    

    so you just need to write the following tag which  will set its default height,width etc.

    <my:image videoKey=”-------the key from youtube---------” />

    I hope it helps you guys.
    Thanks and Regards,
    Anuj Aneja
    anuj@intelligrape.com

    http://intelligrape.com/