Chandan Luthra | Intelligrape Groovy & Grails Blogs
Chandan Luthra

http://www.IntelliGrape.com

I am an Open Source Enthusiast...A great lover of Java Technologies. Apart from server side coding and configurations, I love to optimize applications on the client side (browser) as well. I also co-authored a book on Firebug. I am a software developer by profession and Heart. I Love to code using Groovy and Grails with JQuery sauce on it to beautify an app ;) LinkedIn: http://in.linkedin.com/in/luthrachandan

Posts by Chandan Luthra:

Sleep in Jquery.

15 Dec 2010 in Javascript/Ajax/JQuery

Few days earlier, for achieving “Thread.sleep()” functionality in Jquery, I use javascript’s “setTimeout()” method.

I found that Jquery has a finer and better way for doing this, The “delay()” method

Example: If I want to show an element after 1000 mili seconds then I would do it in following way:

$("div .heading").delay(1000).show()

Hope this little sharing helps to you.

~Chandan Luthra~
chandan(at)intelligrape(dot)com

Grails way for rendering the GSP templates: The tmpl namespace.

01 Oct 2010 in Grails&Groovy

Today while working on a project, I paired up with my colleague (Uday)  and we found that we can render a gsp template in a different manner also. Grails provide us a “tmpl” namespace for rendering the GSP templates.


The old way that we use to render a gsp template

<g:render template="templateName" model="[books:books, authors:authors]"/>

The other way for  rendering the template.

<tmpl:templateName books=${books}  authors="${authors}"/>

Like me, you also must be wondering that if the template is in some other path like some shared folder “/shared/templateName” then how this <tmpl/> would work?

e.g.

<g:render template="/shared/templateName" model="[books:books, authors:authors]"/>

The answer is: <tmpl:/shared/templateName/>

<tmpl:/shared/templateName books=${books}  authors="${authors}"/>

* you can find the documentation for this on http://www.grails.org/doc/latest/guide/single.html


Concerns, comments or suggestions are always welcome.
Cheers!!!!!
~Chandan Luthra~
chandan(aT)intelligrape(dOt)com
http://in.linkedin.com/in/luthrachandan/

Changing the behaviour/Scope of Services in Grails.

15 Sep 2010 in Grails&Groovy

Sometimes our services are so tightly bound with the Controllers that we actually think that a new Service instance should be get created on every request or the member variables in the services can be defined only for the current user. But by default the Services are “singleton” scoped which means that clients of a service only ever use a single instance (a singleton) of the service. We should be very careful about storing state in a service and in fact we should never store any state in the Service.

The default “singleton” behavior of the service can be overridden by adding a static property “scope” to your Service Class.

Syntax:

class MyService {
	static scope = "session"
        .......
}

By adding a static property scope = “session”, we can actually store info related to current user within the session.

Grails provide us following 7 scopes (including singleton) through which we can change the scope of a Service.

  1. prototype – A new service is created every time it is injected into another class
  2. request – A new service will be created per request
  3. flash – A new service will be created for the current and next request only
  4. flow – In web flows the service will exist for the scope of the flow
  5. conversation – In web flows the service will exist for the scope of the conversation. ie a root flow and its sub flows
  6. session – A service is created for the scope of a user session
  7. singleton (default) – Only one instance of the service ever exists

Note: If your service is “flash”, “flow” or “conversation” scoped then it will need to implement java.io.Serializable and can only be used in the context of a Web Flow.

Hope it helps you and saves your time.

Cheers!!!!!

~Chandan Luthra
chandan@intelligrape.com
http://www.IntelliGrape.com

JavaScript Profiling through Firebug’s Console API.

Sometimes we want to know which line of codes or methods in the JavaScript is taking time which slows up the page load. Many times our browser gets hanged due to execution of JavaScript.

Firebug allows us to profile the JavaScript. Following are the two methods that are used for profiling JavaScript:
console.profile()
console.profileEnd()

After the execution of the JS, Firebug generates a nice stats through which one can figure out the problematic line of code(if any).

Type this following code in an HTML file, save it and open it up with Firebug enabled Firefox(if Firebug is not enabled then press F12 key to activate it) :

<html>
<head><title>Firebug</title>
<script>
function bar(){
	console.profile('Measuring time')
	foo()
	console.profileEnd()
}
function foo(){
	loop(1000)loop(100000)loop(10000)
}
function loop(count){
	for(var i=0i<counti++){}
}
</script></head><body>
Click this button to profile JavaScript
<input type="button" value="Start" onclick="bar()"/>
</body></html>

Click on the button to start the JavaScript profiler. You would see table is generated in the Firebug’s Console panel.
JS profiling
Description and purpose of the columns:
Function: This column shows the name of each function.
Call: It shows the count of how many a particular function has been invoked. (3 times for loop() function in our case.)
Percent: It shows the time consuming of each function in percentage.
Own Time: It shows the duration of own script in a particular function. For example foo() function has none of its own code. Instead, it is just calling other functions. So, its own execution time will be approx ~0ms. If you want to see some values for that column, add some looping in this function.
Time: It shows the duration of execution from start point of a function to the end point of a function. For example foo() has no code. So, its own execution time is approx ~0ms, but we call other functions in that function. So, the total execution time of other functions is 4.491ms. So, it shows 4.54ms in that column which is equal to own time taken by 3 loop() function + own time of foo().
Avg: It shows the average execution time of a particular function. If you are calling a function one time only, you won’t see the differences. If you are calling more than one time, you will see the differences. The formula for calculating the average is:
Avg = Own time / Call
Min and Max columns: It shows the minimum execution time of a particular function. In our example, we call loop() for 3 times. When we passed 1000 as a parameter, it probably took only a few millisecond (let’s say 0.045ms.) and when, we passed 100000 to that function, it took much longer than first time (let’s say 4.036ms). So, in that case, 0.045ms will be shown in Min column and 4.036ms will be shown in Max column.
File: It shows the file name of file with line number where the function is located

Any comments and suggestions are welcome :)
~~Chandan Luthra~~
References:
Book https://www.packtpub.com/firebug-1-5-editing-debugging-and-monitoring-web-pages/book
Refcard http://refcardz.dzone.com/refcardz/getting-started-firebug-15

How to send a POST request in window.open() function of JavaScript.

14 Jun 2010 in Javascript/Ajax/JQuery

Hey,

Recently, I need to show some printing stuff using window.open() method of JavaScript. I got stuck when the implementation demands sending POST call to the server for generating the print view.

I googled a lot and found few JavaScript code snippets that provides some workaround for doing this stuff. Finally, I found some cool way for sending POST request in window.open(). I thought, it’ll be worth sharing.

Here is the code:

<form onsubmit="window.open(' ','myWindow','status=yes,scrollbars=yes,
width=100,height=100')" action="generatePrintMaterial.html" method="POST" target="myWindow">
...........................................................
...................//input fields.......................
..........................................................
<input name="Print" type="submit" />
</form>

Notice the name of the window (‘myWindow’) is same as the name given in form’s ‘target’ attribute. On submitting this form, javascript will open a new window and the output of the form will get rendered in that window.

Hope this helps..

~Chandan Luthra~
chandan(AT)intelligrape(DOT)com

http://in.linkedin.com/in/luthrachandan

http://twitter.com/chandanluthra

Reloading a GSP in test & production environment.

15 Apr 2010 in Grails&Groovy

In one of my project I need to generate GSP (groovy server pages) on the fly and write them on the file system. There was a quartz job that updates the GSP page on regular intervals.

The problem was, this functionality worked flawless in the development environment but fails in test and production environment. In test and production environment you can force and reload the GSP in order to see the latest one.

You can force the GSP to reload by writing this following code in your Config.groovy file:

grails.gsp.reload.enable = true

Any suggestions and comments are welcome.

Cheers
~Chandan Luthra~

Fetching the last day of the month

21 Aug 2009 in Groovy

Note: Months are from 0 to 11. Hence the 7th month is “August”

Calendar calendar = GregorianCalendar.instance
calendar.set(2009, 7, 21)
println "Last Day of a Month: ${calendar.getActualMaximum(GregorianCalendar.DAY_OF_MONTH)}"

Cheers!!!
~Chandan Luthra~
chandan@intelligrape.com
www.intelligrape.com

Grails Functional Testing: Uploading a file using G-Func plugin

22 Apr 2009 in Grails

At Intelligrape we face many challenges while developing web-applications. One of the small challenge was to test the web pages that contains file input field <input type=”File”>(to upload files). After few hours drilling with Canoo webtest plugin I decided to use the new fabulous plugin, Grails functional Testing by Marc Palmer (http://www.grails.org/Grails+Functional+Testing).

The syntax for setting value for the file input field is

NameOfFileInputField.setValueAttribute("PathOfFileAsString")

Let me explain you with an example:
Following component’s HTML is

<input name="FileInputField" type="file" />

The name of the file input field is FileInputField.The code for setting value/path will be

FileInputField.setValueAttribute("testFile.txt")

any kind of suggestions and comments are welcome……

Cheers,
Chandan Luthra

www.IntelliGrape.com

How to use $.getJSON() method of jQuery with grails?

How to use $.getJSON() method of jQuery with grails?

Retriving a JSON string from Grails is very easy. You have to just write the following in your controller’s action

Let me explain you with an example of populating a HTML table using JSON response:
In this example, we have table with columns – name,address and gender. We want the table to be populated without doing a full page refresh, using an Ajax call.

Domain Class:

class MyDomain {
    String name
    String address
    String gender
}

Controller Class :

class MyController {
   def someaction = {
      List myDomains = MyDomain.findAllByGender(params.gender)
      <em>/*Let say 5 objects are retrieved*/</em>
      render myDomains as JSON
   }
}

The above code in action will render a JSON string in the following format:

[
{
"name" : "John",
"address" : "New York",
"gender" : "Male"
},
{
"name" : "Rob",
"address" : "Indonasia",
"gender" : "Male"
},
{
"name" : "Shayam",
"address" : "New Delhi",
"gender" : "Male"
},
{
"name" : "Chang",
"address" : "Thailand",
"gender" : "Male"
},
{
"name" : "Ali",
"address" : "London",
"gender" : "Male"
}
]

following script would be writtent on the client Side (in the GSP):

<script>
$.document.ready(function(){
$('#someid').click(function(){
<strong>$.getJSON</strong>("${createLink(controller:'my',action:'someaction')}",{gender:'Male', ajax: 'true'}, function(myDomains){
var myHTMLString = ''
for(var i = 0 ; i < myDomains.length ; i++)
{
myHTMLString = myHTMLString + '<tr><td>' + myDomains[i].name + '</td>'
myHTMLString = myHTMLString + '<tr><td>' + myDomains[i].address + '</td>'
myHTMLString = myHTMLString + '<tr><td>' + myDomains[i].gender + '</td></tr>'
}
$('table#mytable').html(myHTMLString)
})
})
})
</script>

The HTML code would be like this :

<div id=”someid”>
Click for JSON Response
</div>
<table id=”mytable”>
<!–empty table –>
</table>

When you click on the displayed text the html page would become like following:

<div id="someid">
Click for JSON Response
</div>
<table id="mytable">
<tr>
<td>John</td>
<td>New York</td>
<td>Male</td>
</tr>
<tr>
<td>Rob</td>
<td>Indonasia</td>
<td>Male</td>
</tr>
<tr>
<td>Shayam</td>
<td>New Delhi</td>
<td>Male</td>
</tr>
<tr>
<td>Chang</td>
<td>Thailand</td>
<td>Male</td>
</tr>
<tr>
<td>Ali</td>
<td>London</td>
<td>Male</td>
</tr>
</table>

any kind of suggestions and comments are welcome……

Regards,
Chandan Luthra

http://www.IntelliGrape.com