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

Salil

http://www.IntelliGrape.com/

Technology Think Tank

Posts by Salil:

  • byobu: screen sessions in Linux

    13 Apr 2011 in Linux& System

    This post is just to talk about Screen Sessions in Linux (esp. ubuntu) using command “byobu”.

     

    What is Byobu?
    Byobu is a Japanese term for decorative, multi-panel screens. As an open source project, Byobu is an elegant enhancement of plain GNU Screen.

     

    Where can it be used?
    You SSH to some remote machine and Run some commands (application, service, etc). Now you want to logout of ssh session. But want your screen turned-on, so that you just resume it, the next time you access the machine.

     

    How to use it?
    It’s as simple as 2 steps process.

    Step 1: Enter command "byobu"
    Step 2: Press F2 (to create a new screen)
    

    here you go!

     

    Now you are in a detachable screen session. Enter your commands. And once you done –

    Press F6 (to detach the screen)
    

    If you are already logged-into some remote machine (using ssh), now you can logout. And your screen will remain there.
    Then, when you come back — you can resume your screen back by following commmand

    $ screen -r
    

    It’s good to read about other options (like, screen -x)

     

    Your comments are always Welcome. Please post if you have any!

     

    Cheers!
    Salil Kalia
    Salil [at] IntelliGrape [dot] com
    Twitter LinkedIn

    • Share/Bookmark
  • git branching model: choose branches for deletion – see whats remaining for the merge

    04 Mar 2011 in Grails

    This post is for people who are already familiar with Git and work on multiple branches (esp. feature branches).
    By practice, feature branches are the branches created from a root branch (master or any other as per your branching model) and once feature is complete/tested – they are merged back into the same root branch.



    Working in such a manner is pretty nice and clean. But things start getting messy if we don’t delete the branches on time (esp. after merging into root branch). In that case when we run command –

         git branch
    

    It shows us zillions of branches and we start getting feeling to get a rid of all futile branches. But we don’t know which branches are already merged and which are still under progress or yet to be tested.

    Solution to this problem:

          # I am assuming that your root branch is master
          git checkout master
          git branch --merged
    


    Above command will show you all branches which are already merged into the current branch (master branch in this case). This means you can delete these (feature) branches now.
    For deleting a branch on local: git branch {-d | D} ‘feature-branch-1′
    For deleting from remote: git push origin :feature-branch-1
    I assumed that origin is your remote.

    Similarly if you run

          git branch --no-merged
    

    It will give a list of branches which are yet to be merged.



    Question: I got a list of branches which are not merged yet. Now I want to see the commits in particular branch which are not merged into root branch yet?
    Solution:

          git log --pretty=oneline maser..branch1
    

    Again, master is your root branch. And branch1 is your feature branch having commits yet to be merged.

    Your comments are always Welcome. Please post if you have any!



    Cheers!
    Salil Kalia
    Salil [at] IntelliGrape [dot] com
    Twitter LinkedIn

    • Share/Bookmark
  • Load codecs in Unit tests using Groovy Grails

    23 Feb 2011 in Grails& Groovy& Unit Test

    This post is all about enabling codecs (like encodeAsURL, decodeURL, etc) in your Grails Unit tests. I am assuming that you are already familiar with writing unit tests.

    Scenario:
    In our application code, if we have something like below:

          String serviceUrl = "http://example.com/service"
          String username = "usernameStr"
          String password = "passwordvalue"
          String urlStr = "${serviceUrl}?u=${username.encodeAsURL()}&p=${password.encodeAsURL()}.."
    

    Above code works very well when we run the application or even Integration tests. As we know that Codecs are automatically injected by Grails when application starts up.

    Problem:
    When we use this code in our Unit Tests, it won’t work. Reason, Unit tests do not load Grails specific environment automatically. We have to mock or load the things (whatever required by test).

    Solution:
    GrailsUnitTestCase class provides a method loadCodec(CodecClass). So here, to make encodeAsURL() working in our Unit tests, we just need add following line of code in our test (setup method).

          loadCodec(URLCodec)
    


    That’s it. Rest of the work will be taken care by Grails :-)

    So whatever codec you need to load, just invoke loadCodec method with required codecClass in argument.

    Your comments are always Welcome. Please post if you have any!



    Cheers!
    Salil Kalia
    Salil [at] IntelliGrape [dot] com
    Twitter LinkedIn

    • Share/Bookmark
  • Groovy: Sort list of objects on the basis of more than one field

    25 Jan 2011 in Database& Grails& Groovy& Java tools

    Usually, when we deal with databases, we don’t face such kind of situation because we query database to get result-set in required order.

    But let’s say you have a List of objects that you want to sort on the basis of two fields. Let’s discuss it with an example.


    I have a list of Tasks (with date and priority fields). I want to sort these tasks ordered by Date and priority-wise (as second level sorting).

    Here, I gonna use Expando class, so I can directly run this in my groovyConsole. But definitely you can use some ‘Task’ class.

    Expando a = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-01'), priority:1)
    Expando b = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-01'), priority:2)
    Expando c = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-02'), priority:1)
    Expando d = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-01'), priority:3)
    
    def list = [a,d,c,b]
    

    If sorting was required on the basis of date only, it was very simple.

    list.sort(it.date)
    

    But as per our requirements – order by date (first level sorting) and priority (second level sorting). We can do something like following.

    list.sort{x,y->
      if(x.date == y.date){
        x.priority <=> y.priority
      }else{
        x.date <=> y.date
      }
    }
    

    Well, there could be some better way. If you know please put your comments. But it worked well in my case.



    Cheers!
    Salil Kalia
    Salil [at] IntelliGrape [dot] com
    Twitter LinkedIn

    • Share/Bookmark
  • How to use Thread-Pooling using Groovy

    16 Jan 2011 in Grails

    I really like the thread-pooling API (in java.util.concurrent package), especially when you are hitting x number of API dealing with outside network to fetch information for a single request.
    Example: A website dealing with some kind of ticket booking service and there are 4 different vendors (sources where you retrieve ticket status from).



    Classes you need to import.

    import java.util.concurrent.ExecutorService
    import java.util.concurrent.Executors
    import java.util.concurrent.Callable
    import java.util.concurrent.Executors
    import java.util.concurrent.TimeUnit
    import java.util.concurrent.Future
    



    I am discussing it here in a very simple Groovish manner.

    def myClosure = {num -> println "I Love Groovy ${num}"}
    def threadPool = Executors.newFixedThreadPool(4)
     try {
      List<Future> futures = (1..10).collect{num->
        threadPool.submit({->
        myClosure num } as Callable);
      }
      // recommended to use following statement to ensure the execution of all tasks.
      futures.each{it.get()}
    }finally {
      threadPool.shutdown()
    }
    

    In the above example, thread pool size is 4, that means concurrent 4 tasks would be executed in a single go. And task is the code in ‘myClosure’.



    Let’s say you rely on output from tasks. Then you need to do something like following

     Collection results = futures.collect{it.get()}
    

    Salil Kalia
    salil [at] intelligrape [dot] com

    • Share/Bookmark
  • Number Formating using regular expression and format method of String class

    14 Dec 2010 in Database& Grails& Groovy

    Hey guys, I found something very useful, so sharing it here.
    In one of my project there was a requirement to create a fixed length user-id. Let’s say it was 5 characters ID.


    So in other words we required to convert -
    ‘123′ to ‘00123′ and ‘1000′ to ‘01000′ and ‘12345′ will remain ‘12345′.
    It appears very simple, but the thing is how quick we do this.


    Earlier I thought to do this by calculating the length of id and prefixing required number of zeros.


    Alternate single-line and faster solution is -

          // following will return a String with size of 5 characters and prefixes zeros (if id has digits lesser than 5).
             String.format('%05d', id)
          // Note down, id is a digit here.
    

    That’s all. . isn’t it nice?. We can utilize it at many places like – converting date from ‘1-1-2010′ to ‘01-01-2010′.
    Idea is to introduce such kind of utility. If you already knew this, please ignore :-)
    please open the ideas – if you know something better than this.


    cheers!
    salil at IntelliGrape dot com

    • Share/Bookmark
  • Encode Content to MD5 Using GROOVY or GRAILS – with Webhook example

    12 Nov 2010 in Grails& Groovy

    Recently I was working on webhooks (which are getting quite popular for sending notifications to other applications using HTTP POST methods). MD5 encoded content is heavily used in webhooks for security concern.

    My purpose of writing this blog is neither to explain MD5 nor webhooks. But just to show you -
    1. a quicker way in Java/Groovy/Grails – How to encode a String (or Content) using MD5 algorithm.
    2. Receive Webhook request (containing MD5 encoded certificate)

          // Below is the content (received in http post request body)
          String contentRecievedInRequest = "StringcontentneedtobeverifiedbaseduponMD5algorithm"
          // Below is your secret key - this is not in request - but something that you and trust-party know only)
          String yourSecretKey = "kfkdjfxx8r7kdf"
          // Now Mix your secret key with the content received in http post request
          String claimedContent = "StringcontentneedtobeverifiedbaseduponMD5algorithmkfkdjfxx8r7kdf"
          // following is usually a hexa value - find in the same http-request-header
          String certificate = '3df5786adfe37430d8a8d72cb9e7fe56c'
    

    Now, what we need to do here is – Encode claimedContent as MD5.

    1. Using Groovy/Java

            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(claimedContent.getBytes());
            BigInteger hash = new BigInteger(1, md5.digest());
            String hashFromContent = hash.toString(16);
    

    2. Using Grails (Single line solution)

            String hashFromContent = claimedContent.encodeAsMD5();
    

    Now what ? Just see if encoded content matches with the certificate received in request-header. If it matches that means it’s valid request (not hacked one).

            if(hashFromContent == certificate){
                println "GOOD REQUEST -- Content Verified"
            }else{
                println "BAD REQUEST"
            }
    

    I hope it might help you somewhere.

    Salil Kalia
    salil [at] intelligrape [dot] com

    • Share/Bookmark
  • GORM feature: Bypass Grails Domain Constraints

    15 Oct 2010 in Database& Grails& Groovy

    I didn’t know this earlier, but found a very good feature of GORM – ‘bypass’ constraints or ‘customize’ validation while saving a domain-object. I am not sure if there’s any name for this feature. But I am naming it as ‘bypass constraints’.

    if(domainObject.validate(['field1', 'field2'])){
      domainObject.save(validate:false, flush:true)
    }
    

    Let’s discuss it with a use case. We create a user table with fields – id, name, email, password.
    And email/password are mandatory fields.

    Class User{
        Long id
        String name
        String email
        String password
    
        static constraints = {
            name(nullable: true)
        }
    }
    

    Now there’s a requirement in the application – An existing user can invite a friend.

    With the help of ‘bypass constraints’ feature, it’s easier to handle this use-case without actually creating any separate domain to store invited users information.

    Following code will create User entry with null password.

    User user = new User(name:userName, email:userEmail)
    if(user.validate(['email']) && user.save(validate:false, flush:true)){
    return true
    }
    


    NOTE: To achieve this, you just need to set ‘password’ column as nullable true in your ‘user’ table.

    Above example/use-case is just to explain ‘bypass constraints’ feature, nothing more than this. :-)

    I hope it might help you somewhere.

    Salil Kalia
    salil [at] intelligrape.com

    • Share/Bookmark
  • GRAILS specific LOCALE Handling – Change Language and return to the same page

    14 Sep 2010 in Grails

    It’s common requirement when we work on some portal – we need to provide support for various languages.
    messages.properties/ResourceBundle is out of the scope of this post. Here I am just mentioning –

    how to switch to a different language taking an advantage of GRAILS

    On your view (gsp) page add following -

    <%
    String targetUri = (request.forwardURI - request.contextPath)
    %>
     <g:link controller="lang" action="lang" params="[lang: 'en', targetUri: targetUri]">English</g:link>
     <g:link controller="lang" action="lang" params="[lang: 'fr', targetUri: targetUri]">French</g:link>
     <g:link controller="lang" action="lang" params="[lang: 'es', targetUri: targetUri]">Spanish</g:link>
    .....
    .....

    I just wanted to give you a rough idea. But you can create a custom tag for this – depending upon your requirement.



    Now the trick here is to send parameter with name “lang”. And GRAILS automatically recognizes it and set locale itself.
    Following is the code at server side (controller/action).

    //import org.springframework.context.i18n.LocaleContextHolder
    //import org.springframework.web.servlet.support.RequestContextUtils as RCU;
     
    class LangController {
    def lang = {
           String targetUri = params.targetUri ? params.targetUri : "/"
           // String language = params.lang ? params.lang : 'en'
           // LocaleContextHolder.setLocale(new Locale(language))
           // RCU.getLocaleResolver(request).setLocale(request, response, new Locale(language))
           redirect(uri: targetUri)
    }
    }

    If you notice above, I have commented out few lines (with the help of grails internal implementation, we need to do nothing explicitly to switch to a different language).

    So in SINGLE LINE:

    Base URL: http://example.com/cont/act/id  <!--Grails will use "messages.properties" now -->
    Locale specific URL: http://example.com/cont/act/id?lang=fr <!--Grails will use "messages_fr.properties" now -->

    Hope it helps!
    Salil Kalia

    • Share/Bookmark
  • Tips for Agile Development with Unit Testing approach.

    14 Jul 2010 in Grails& Groovy& Test& Unit Test

    This is more towards the best practices and my experiences for developing an application at a faster rate.

    In my current project, we are using many different APIs (for external services). And usually it takes time to explore, implement and then stabilize the application. Also, it’s not over once you stabilize your APIs based code. Because there are possibilities to have unexpected results such as server side errors, broken request, broken response, etc. Also you never know when Service provider makes some changes and your code breaks.

    Well, here are some tips which really helped me to achieve faster implementation and more stable application (esp. when working with third party APIs).

    TRY TO MAKE YOUR CODE UNIT TESTABLE as much as possible.

    1. Create Service layer for API based implementation. Keep this service layer independent from other application. So that you should run it without any other dependency.

    2. Try to make small chunks of code (in form of methods) with least dependency on external things.
    Avoid Domain/Database/Environment specific code. In other words, don’t put any kind of framework specific dependency. In some cases you can’t avoid. But try to avoid as much as possible. Because it could lead to integration testing and which again takes more time. Unit test is the fastest way to check your code stability.

    3. In case you have some dependencies (and that can not be avoided) – Try to mock it up. In many cases it’s possible. If you are using Grails/Groovy kind of framework/language – you have an edge to take an advantage of meta-programming.

    4. There is no specific way to do this. But it comes with practice. You can follow above tips to implement your Service Layer Code. And then create unit tests – invoke your API based service methods. And run it. Wow.. that’s it.

    Advantages:
    If there’s any kind of changes (from service provider), that can break your application’s functionality, test driven development will work as a “Life Saver”. It can tell you where’s the problem and why it happened. And you can make appropriate changes to stabilize it again.

    Same thing implements when you develop a new feature. Unit Test Case helps you see the results in few seconds. Instead of waiting for 10-15 minutes (until application starts).

    Isn’t it cool?

    I really appreciate this approach. Hope others will also use it.

    Thanks
    Salil Kalia

    • Share/Bookmark